Loops
Computers are good at doing the same thing many times without getting bored. Loops are how you ask them to.
for loops and range
for i in range(5):
print(i)
This prints 0, 1, 2, 3 and 4. range(5) produces the numbers from 0 up to, but not including, 5. You can also give a start, a stop and a step:
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8
range(5, 0, -1) # 5, 4, 3, 2, 1
A for loop can walk over any sequence, including the characters of a string:
for ch in "code":
print(ch.upper())
The accumulator pattern
A very common job is building up a result one step at a time. Start with an empty value, then update it in the loop:
total = 0
for n in range(1, 101):
total += n
print(total) # 5050
total += n is short for total = total + n.
while loops
A while loop keeps going as long as its condition is true. Use it when you do not know in advance how many times to loop:
n = 1
while n < 1000:
n *= 2
print(n) # 1024
If the condition never becomes false, the loop runs forever. Press Ctrl + C in the terminal to stop a stuck program.
break and continue
break leaves the loop immediately. continue skips to the next round.
while True:
word = input("Word (or 'quit'): ")
if word == "quit":
break
if word == "":
continue
print(word[::-1])
Nested loops
A loop inside a loop runs the inner loop completely for every round of the outer one:
for row in range(1, 4):
line = ""
for col in range(1, 4):
line += f"{row * col:4}"
print(line)
This prints a 3 by 3 multiplication table. :4 pads each number to four characters so the columns line up.
Exercises
1. Countdown
Print the numbers from 10 down to 1, then print "Liftoff!".
Show answer
for i in range(10, 0, -1):
print(i)
print("Liftoff!")
2. Count the vowels
Ask for a sentence and print how many vowels (a, e, i, o, u) it contains, ignoring case.
Show answer
text = input("Sentence: ")
count = 0
for ch in text.lower():
if ch in "aeiou":
count += 1
print(count)
in checks whether one string appears inside another.
3. Guessing game
Pick a secret number with import random and random.randint(1, 100). Let the user guess until they get it, saying "higher" or "lower" each time, then print how many guesses they took.
Show answer
import random
secret = random.randint(1, 100)
guesses = 0
while True:
guess = int(input("Guess: "))
guesses += 1
if guess < secret:
print("higher")
elif guess > secret:
print("lower")
else:
break
print(f"Got it in {guesses} guesses.")
With the best strategy you never need more than 7 guesses for 1 to 100. Why? See the "Guess the number" daily problem.