Python course · Module 3: Control flow · Lesson 14 of 63
Quick answer: These Python exercises for beginners practise everything from Lessons 1 to 13: variables, numbers, strings, input() and print(), if/elif/else, match, for loops and while loops. There are 10 exercises, from easy to harder, each with a full solution and its real output. The lesson ends with a mini project: a number guessing game, built step by step with random.randint(), a while loop and break.
In this lesson you will:
- solve 10 graded exercises that use only what you have learned so far
- compare your answers with tested solutions and real outputs
- use
random.randint()andrandom.seed()for the first time - build a complete number guessing game in five small steps
Before you start: finish Lesson 13, Python while Loops, and the lessons before it. Nothing in this lesson is new except the random module, which is explained when the game needs it. All examples were tested on Python 3.14.6 and behave the same on Python 3.15.2, the newest release on python.org; random numbers without a seed are different on every run, as explained below.
Table of Contents
How to use this practice set
Try each exercise yourself before you read its solution. Type the code, run it in a terminal (Lesson 3; on Windows, type python or py instead of python3), and test it with more than one answer. Your code does not have to look exactly like the solution; if it gives the right output for every case, it is correct.
| No. | Exercise | Level | Practises |
|---|---|---|---|
| 1 | Greeting card | Easy | input(), f-strings, len() |
| 2 | Rectangle calculator | Easy | float(), arithmetic, format specs |
| 3 | Minutes to hours | Easy | // and % |
| 4 | Positive, negative or zero | Medium | if, elif, else |
| 5 | Grade calculator | Medium | elif chain, conditional expression |
| 6 | Times table | Medium | for and range() |
| 7 | Reverse a word | Medium | looping over a string |
| 8 | FizzBuzz | Harder | for, if, % and and |
| 9 | Leap year check | Harder | and, or, brackets |
| 10 | Calculator menu | Harder | while True, break, match |
If you get stuck, go back to the lesson: variables (Lesson 5), numbers (Lesson 6), strings and f-strings (Lesson 7), type conversion (Lesson 8), operators (Lesson 9) and input and output (Lesson 10), then Lessons 11 to 13 for decisions and loops.
Try it yourself
Exercise 1: Greeting card (easy)
Ask for the user’s name and city. Print Hello, <name> from <city>! and then how many letters the name has.
Exercise 2: Rectangle calculator (easy)
Ask for the length and width of a room in metres (decimals allowed). Print the area and the perimeter with two decimal places. Perimeter = 2 × (length + width).
Exercise 3: Minutes to hours (easy)
Ask for a number of minutes and print it as hours and minutes. For 135 minutes the answer is 2 hours and 15 minutes.
Exercise 4: Positive, negative or zero (medium)
Ask for a number and print Positive, Negative or Zero.
Exercise 5: Grade calculator (medium)
Ask for marks out of 100. Grade A is 80 or more, B is 65 or more, C is 50 or more, and anything lower is F. Print the grade and whether the student passed (any grade except F).
Exercise 6: Times table (medium)
Ask for a number and print its times table from 1 to 10, with the columns lined up.
Exercise 7: Reverse a word (medium)
Ask for a word and print it backwards, using a for loop (not slicing, which comes in Lesson 20). If the word reads the same both ways, like level, say so.
Exercise 8: FizzBuzz (harder)
Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both.
Exercise 9: Leap year check (harder)
Ask for a year and say whether it is a leap year. The rule: a year divisible by 4 is a leap year, except years divisible by 100, which are leap years only if they are also divisible by 400. Test 2024, 1900 and 2000.
Exercise 10: Calculator menu (harder)
Write a calculator that keeps running: ask for an operation (+, -, * or /), then two numbers, and print the result. Use match for the operations. Typing q ends the program. Do not crash on division by zero.
Solutions
Solution 1
name = input("Your name: ")
city = input("Your city: ")
print(f"Hello, {name} from {city}!")
print(f"Your name has {len(name)} letters.")
$ python3 ex01_greeting.py
Your name: Sara
Your city: Multan
Hello, Sara from Multan!
Your name has 4 letters.
Both answers stay strings, so no conversion is needed.
Solution 2
length = float(input("Length in metres: "))
width = float(input("Width in metres: "))
area = length * width
perimeter = 2 * (length + width)
print(f"Area: {area:.2f} square metres")
print(f"Perimeter: {perimeter:.2f} metres")
$ python3 ex02_rectangle.py
Length in metres: 4.5
Width in metres: 3
Area: 13.50 square metres
Perimeter: 15.00 metres
float() accepts both 4.5 and 3, and :.2f always shows two decimal places.
Solution 3
total_minutes = int(input("Minutes: "))
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes is {hours} hours and {minutes} minutes.")
$ python3 ex03_minutes.py
Minutes: 135
135 minutes is 2 hours and 15 minutes.
// gives the whole hours and % gives the minutes left over.
Solution 4
number = float(input("Enter a number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
$ python3 ex04_sign.py
Enter a number: -2.5
Negative
$ python3 ex04_sign.py
Enter a number: 0
Zero
If a number is neither above nor below 0, it must be 0, so else needs no condition.
Solution 5
marks = int(input("Marks out of 100: "))
if marks >= 80:
grade = "A"
elif marks >= 65:
grade = "B"
elif marks >= 50:
grade = "C"
else:
grade = "F"
result = "passed" if grade != "F" else "failed"
print(f"Grade {grade}: you {result}.")
$ python3 ex05_grade.py
Marks out of 100: 72
Grade B: you passed.
$ python3 ex05_grade.py
Marks out of 100: 41
Grade F: you failed.
The highest grade is checked first, as Lesson 11 explained. The conditional expression picks the word passed or failed.
Solution 6
n = int(input("Times table for: "))
for i in range(1, 11):
print(f"{n} x {i:>2} = {n * i:>3}")
$ python3 ex06_times_table.py
Times table for: 9
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
range(1, 11) stops before 11, and :>3 keeps results of up to three digits in line.
Solution 7
word = input("Word: ")
reversed_word = ""
for letter in word:
reversed_word = letter + reversed_word
print("Reversed:", reversed_word)
if reversed_word == word:
print("It reads the same both ways!")
$ python3 ex07_reverse.py
Word: python
Reversed: nohtyp
$ python3 ex07_reverse.py
Word: level
Reversed: level
It reads the same both ways!
Each new letter is added to the front of reversed_word, so the last letter ends up first.
Solution 8
for number in range(1, 16):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
The “both” test must come first. If number % 3 == 0 came first, 15 would print Fizz.
Solution 9
year = int(input("Year: "))
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
$ python3 ex09_leap_year.py
Year: 2024
2024 is a leap year.
$ python3 ex09_leap_year.py
Year: 1900
1900 is not a leap year.
$ python3 ex09_leap_year.py
Year: 2000
2000 is a leap year.
The brackets matter: without them, and would run before or (Lesson 9) and change the rule.
Solution 10
print("Simple calculator. Type q to quit.")
while True:
operation = input("Operation (+ - * /): ")
if operation == "q":
print("Bye!")
break
a = float(input("First number: "))
b = float(input("Second number: "))
match operation:
case "+":
print(f"{a} + {b} = {a + b}")
case "-":
print(f"{a} - {b} = {a - b}")
case "*":
print(f"{a} * {b} = {a * b}")
case "/":
if b == 0:
print("You cannot divide by zero.")
else:
print(f"{a} / {b} = {a / b}")
case _:
print(f"Unknown operation: {operation}")
$ python3 ex10_calculator.py
Simple calculator. Type q to quit.
Operation (+ - * /): +
First number: 8
Second number: 2
8.0 + 2.0 = 10.0
Operation (+ - * /): /
First number: 9
Second number: 0
You cannot divide by zero.
Operation (+ - * /): %
First number: 5
Second number: 3
Unknown operation: %
Operation (+ - * /): q
Bye!
while True keeps the menu running until break, and case _: catches any operation the program does not know.
Mini project: a number guessing game
The computer picks a secret number from 1 to 100. The player guesses, and the program answers “Too low!” or “Too high!” until the guess is right. We build it in five steps; run each step before moving on.
Step 1: Pick a random number
Python comes with a random module for random numbers. import random at the top of the file loads it (Lesson 27 covers modules and import). Then random.randint(1, 100) gives a random whole number. The random module docs say it returns a random integer N “such that a <= N <= b“, so both 1 and 100 are possible. Unlike range(), the end number is included.
import random
secret = random.randint(1, 100)
print("Secret number:", secret)
We ran this script three times and got a different number each time. Your numbers will be different again:
$ python3 game1_random.py
Secret number: 96
$ python3 game1_random.py
Secret number: 82
$ python3 game1_random.py
Secret number: 33
Step 2: Use a seed while testing
A different number every time makes testing hard. random.seed() fixes the starting point of the random numbers, so the same seed gives the same numbers. The docs explain: “By reusing a seed value, the same sequence should be reproducible from run to run”.
import random
random.seed(2026)
secret = random.randint(1, 100)
print("Secret number:", secret)
$ python3 game2_seed.py
Secret number: 16
$ python3 game2_seed.py
Secret number: 16
Seed 2026 gave 16 on Python 3.14.6 and 3.15.2. The docs warn that most of the module’s algorithms “are subject to change across Python versions”, so another version may give a different number. We keep the seed for Steps 3 and 4 and remove it in Step 5.
Step 3: One guess
import random
random.seed(2026)
secret = random.randint(1, 100)
guess = int(input("Guess a number from 1 to 100: "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("Correct!")
$ python3 game3_one_guess.py
Guess a number from 1 to 100: 50
Too high!
The if/elif/else from Lesson 11 gives exactly one hint. But the game ends after one guess.
Step 4: Keep guessing until correct
Put the guess inside while True and break when the guess is right. A counter records the number of tries.
import random
random.seed(2026)
secret = random.randint(1, 100)
attempts = 0
print("I am thinking of a number from 1 to 100.")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! You found it in {attempts} tries.")
break
$ python3 game4_loop.py
I am thinking of a number from 1 to 100.
Your guess: 50
Too high!
Your guess: 25
Too high!
Your guess: 12
Too low!
Your guess: 18
Too high!
Your guess: 15
Too low!
Your guess: 16
Correct! You found it in 6 tries.
Step 5: The final game
The final version removes the seed, gives the player 7 tries, ignores guesses outside 1 to 100 with continue, and uses while ... else from Lesson 13 to reveal the number when the tries run out.
import random
secret = random.randint(1, 100)
max_tries = 7
attempts = 0
print("I am thinking of a number from 1 to 100.")
print(f"You have {max_tries} tries.")
while attempts < max_tries:
guess = int(input(f"Try {attempts + 1}: "))
if guess < 1 or guess > 100:
print("Please guess from 1 to 100.")
continue
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! You found it in {attempts} tries.")
break
else:
print(f"Out of tries! The number was {secret}.")
Here are two real runs. In the first, each guess was the middle of the numbers still possible; in the second, the player wasted the tries on 1, 2, 3 and so on. There is no seed now, so your secret number, and with it the hints and guesses, will be different.
$ python3 game5_final.py
I am thinking of a number from 1 to 100.
You have 7 tries.
Try 1: 50
Too high!
Try 2: 25
Too low!
Try 3: 37
Too low!
Try 4: 43
Too high!
Try 5: 40
Correct! You found it in 5 tries.
$ python3 game5_final.py
I am thinking of a number from 1 to 100.
You have 7 tries.
Try 1: 150
Please guess from 1 to 100.
Try 1: 1
Too low!
Try 2: 2
Too low!
Try 3: 3
Too low!
Try 4: 4
Too low!
Try 5: 5
Too low!
Try 6: 6
Too low!
Try 7: 7
Too low!
Out of tries! The number was 31.
Notice three details. 150 did not use up a try, because continue jumps back before attempts += 1. The else block ran only in the second game, when the loop ended without break. And 7 tries are always enough if you guess the middle each time: each wrong guess leaves at most half of the numbers (at most 50, then 25, 12, 6, 3 and 1), so the seventh guess is always right.
One weakness remains: typing a word crashes the game with ValueError: invalid literal for int() with base 10: 'fifty'. You will fix that with try and except in Lesson 35.
Common mistakes
- Writing
random.randint(1, 100)withoutimport random. Python stops withNameError: name 'random' is not defined. Did you forget to import 'random'?. Putimport randomat the top of the file. - Thinking randint() works like range().
random.randint(1, 100)can return 100;range(1, 100)stops at 99. - Leaving the seed in the finished game. With
random.seed(2026)the secret number is the same every time, so the game is no fun. Use a seed only while testing. - Checking FizzBuzz conditions in the wrong order. Test “divisible by 3 and 5” first, or 15 prints
Fizz. - Using
randomfor passwords or codes. The docs warn that this module “should not be used for security purposes”; Python’ssecretsmodule is made for that.
Frequently asked questions
What Python exercises should a beginner do first?
Start with small programs that use one idea each: reading input and printing it, simple arithmetic, one if/else decision, and one loop. Then combine them, as in the calculator and the guessing game. Exercises 1 to 10 above follow that order.
How do I generate a random number in Python?
Write import random at the top of your file, then call random.randint(a, b), which returns a whole number from a to b, both included. For example, random.randint(1, 6) works like a dice roll.
How many guesses do you need to find a number from 1 to 100?
At most 7, if you always guess the middle of the numbers that are still possible. Each “too high” or “too low” removes at least half of them, so after six wrong guesses only one number is left.
Summary
- Ten exercises practised input, numbers, strings, decisions and loops from Lessons 1 to 13.
random.randint(a, b)returns a random whole number fromatob, including both ends.random.seed()makes random results repeatable, which helps while testing.- The guessing game combines
while,if/elif/else,break,continueandwhile ... else.
Next lesson
Next: Lesson 15, Python Lists.
Sources
- random: Generate pseudo-random numbers (Python docs)
- More Control Flow Tools (Python tutorial)
- Built-in Functions: input(), int(), float() and range() (Python docs)
- Python downloads page (python.org)





