The for loop is "syntactic sugar", that is it combines the concept of looping (like the while loop) with the idea of iterating, either using a counter or elements in a sequence, such as a Python list.
You can always create equivalent code using a while loop and additional variables, but 'for' is often more convenient.
# While loop version
i = 0
while(i < 10):
print("i is: " + str(i))
i = i + 1
# The for loop version
for i in range(10):
# Range returns an iteratable sequence
# from 0 (inclusive) to 10 (exclusive)
print("i is: " + str(i))
# Range can do all sorts of fancy iterations
for i in range(9, -1, -1): # Backwards
print("i is: " + str(i))
# Jumping two steps at a time
for i in range(0, 10, 2):
print("i is: " + str(i))
# For loops also allow iteration over sequences, such as lists:
# Note: we'll cover lists in detail later
for color in [ "pink", "yellow", "blue", "green" ]:
print("My favorite color is now " + color)
We saw nested conditionals, we can also nest loops.
While loops, for loops and other control flow elements can all be nested together.
# Example of nested for loops
for i in range(4):
for j in range(4):
print("The values are, i: " + str(i) + " j: " + str(j))
# This may mess with you, but it is just the logical extension
# of the ideas we've covered.
i = 1
while True:
print(i)
i = i + 1
if i > 10:
break
i = 0
while True:
print(i)
i = i + 1
if i < 5:
continue
if i >= 10:
break
Example
Example
Example