Lesson 10 of 10
Time to combine conditionals and loops into real programs. You'll build two.
Part 1: FizzBuzz
FizzBuzz is the most famous beginner programming exercise there is — it shows up in real job interviews. The rules, for the numbers 1 to 15:
- Multiples of 3 print
Fizz - Multiples of 5 print
Buzz - Multiples of both print
FizzBuzz - Everything else prints the number itself
The tool you need is %, the remainder operator. n % 3 == 0 means "n divides evenly by 3."
for n in range(1, 16):
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
The order is the whole trick. The FizzBuzz check has to come first. If you tested n % 3
first, then 15 would match it and print Fizz — the combined case would never be reached.
Remember from lesson 2.3: Python takes the first true branch and skips the rest.
Part 2: The guessing game
Now something interactive. The program holds a secret number and keeps asking until the player gets it, giving a "higher" or "lower" hint each time.
This pulls together while True, input(), int(), if/elif/else, break, and a counter.
secret = 7
guesses = 0
while True:
guess = int(input("Guess a number (1-10): "))
guesses += 1
if guess < secret:
print("Higher!")
elif guess > secret:
print("Lower!")
else:
print(f"Correct! It took you {guesses} guesses.")
break
The loop is deliberately infinite — the break in the else branch is the only way out, and it
only fires on a correct guess. guesses is a counter, exactly the pattern from lesson 2.8.
The secret is hardcoded to 7 for now. In Module 7 you'll meet the random module and can make
the computer pick a real random number.
Take it further
If you want to push yourself:
- Give the player only 3 attempts, then reveal the answer.
- Print
"Too far off"when the guess is more than 3 away from the secret. - Extend FizzBuzz to 100, or add
Bazzfor multiples of 7.
Module 2 complete
You can now write programs that make decisions and repeat work — if/elif/else, while,
for, range(), break, continue, and the accumulator and counter patterns. That is the
control flow that every program is built from.
Next up: Module 3 — Data Structures, where you'll learn to store many values at once instead of one variable at a time.
Questions about this lesson
Log in to ask a question.