Python Tutorial Series - Loops

Python has two ways to loop through data.

For Loop



The first is the for loop. The for loop is used when you know how many iterations to make.

Example to loop through a dictionary using a for loop:
Show keys:


to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}
print ("TO DO ITEM KEYS:")
for key in to_do_dict:
    print (key)


Show items:


to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}
print ("TO DO ITEMS:")
for key, item in to_do_dict.items():
    print (item)


Show keys and items:


to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}
print ("TO DO KEYS AND ITEMS:")
for key, item in to_do_dict.items():
    print (key, item)


While Loop



The second type of loop is the while loop. This is used to do something until a condition is met.

Example to loop through a dictionary using a while loop:
Show keys:


to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}
count = 0
print ("TO DO ITEM KEYS:")
items = list(to_do_dict.items())
while (count < 2):
    print(items[count][0])
    count += 1


Show items:


to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}
count = 0
print ("TO DO ITEM KEYS:")
items = list(to_do_dict.items())
while (count < 2):
    print(items[count][1])
    count += 1


Show keys and items:


to_do_dict = {'a':'groceries', 'b':'laundry', 'c':'wash car', 'd':'vacuum'}
count = 0
print ("TO DO ITEM KEYS:")
items = list(to_do_dict.items())
while (count < 2):
    print(items[count])
    count += 1



More Python







Comments