Loops — repeating yourself
When you need to do something more than once, reach for a loop. Python has two:
for (when you know what you're looping over) and while
(when you keep going until something changes).
for — looping over a sequence
names = ["Sam", "Pat", "Riley"]
for name in names:
print(f"Hello, {name}!")
Hello, Sam!
Hello, Pat!
Hello, Riley!
Read it as: "for each name in names, do this".
range() — looping a fixed number of times
range(n) produces the numbers 0, 1, 2, … n-1:
for i in range(5):
print("Tick", i)
Tick 0
Tick 1
Tick 2
Tick 3
Tick 4
range can take a start and a step too:
print(list(range(2, 10, 2))) # [2, 4, 6, 8]
Looping over a string
for letter in "hello":
print(letter)
h
e
l
l
o
while — keep going until…
A while loop runs while its condition is true:
count = 3
while count > 0:
print(f"{count}...")
count = count - 1
print("Lift off!")
3...
2...
1...
Lift off!
Avoid infinite loops
Make sure something inside the loop eventually makes the condition false. Otherwise your
program will hang. (If that happens, hit
Ctrl+C in the terminal to stop it.)
break and continue
break exits the loop immediately. continue skips to the next iteration:
for n in range(10):
if n == 5:
break # stop the whole loop at 5
if n % 2 == 0:
continue # skip even numbers
print(n)
1
3
A practical example: a guessing game
secret = 7
while True:
guess = int(input("Guess (1-10): "))
if guess == secret:
print("Got it!")
break
elif guess < secret:
print("Too low.")
else:
print("Too high.")
Quick recap
for loops over a sequence (list, string, range). while
loops as long as a condition holds. break stops a loop, continue
skips to the next iteration.