For
The for statement is used to execute code many times just like the while statement.
for.py
count = 0 #print('While Loop Start ----') #while count < 5: # count = count + 1 # print(count) #print('While Loop End ----') # index will contain values 0 to 4 print('For Loop Start range(5) ----') for index in range(5): print(index) print('For Loop End ----') # index will contain values 1 to 4, 5 is not included print('For Loop Start range(1,5) ----') for index in range(1,5): print(index) print('For Loop End ----') # fruits is actually a list of items fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) print("Done.")
We'll discuss lists, arrays, and collections later.
Output:
For Loop Start range(5) ---- 0 1 2 3 4 For Loop End ---- For Loop Start range(1,5) ---- 1 2 3 4 For Loop End ---- apple banana cherry Done.
Links
Exercises (5 mins)
-
Take the times_table.py and convert to use a for loop.
times_table.py
count = 0 while count < 5: count = count + 1 print(f'{count} * 2 is {count * 2}') print("Done.")
Output:
1 * 2 is 2 2 * 2 is 4 3 * 2 is 6 4 * 2 is 8 5 * 2 is 10 Done.