BeginnerLesson 4 of 12
Loops: for & while – Python
Repeating tasks – over numbers, lists and more.
The for loop runs over any collection. range(n) produces the numbers 0 to n-1.
for i in range(3):
print("Round", i)
for frucht in ["Apple", "Pear", "Cherry"]:
print(frucht.upper())
for i, frucht in enumerate(["A", "B"], start=1):
print(i, frucht)while runs as long as a condition holds. break ends the loop, continue jumps to the next iteration.
n = 0
while True:
n += 1
if n % 2 == 0:
continue
if n > 7:
break
print(n) # 1 3 5 7WarningWith
while, make sure the condition eventually becomes false – otherwise you get an infinite loop.