Project: Guessing Game
Lesson 9 builds a guessing game in Python with random.randint, a while loop, an attempt counter, too high and too low feedback, and validation of invalid input.
By the end of this lesson, you should have built a complete guessing game, applying the concepts from the previous lessons in a practical project: random number generation, a repetition loop, a counter for attempts and feedback to the user.
This lesson is a guided project. Unlike the previous lessons, the focus is not on introducing new concepts, but on integrating what has already been learned into a functional and engaging program. We will build the game in stages, testing each step before moving on.
1. What the game will do
Before writing code, it is worth describing the expected behavior:
The program picks a secret number between 1 and 100.
The player tries to guess the number.
On each attempt, the program tells the player whether the guess was too high, too low or correct.
The game continues until the player guesses correctly.
At the end, the program displays how many attempts were needed.
This is a simple project, but it brings together several concepts: data input, type conversion, conditionals, loops, counters and random number generation.
2. Generating the secret number with random
To generate a random number, Python offers the random module, which is part of the standard library. No installation is needed.
The most suitable function for our case is randint(start, end), which returns an integer between the two values, including both.
import random secret_number = random.randint(1, 100) print(secret_number)
Run the program a few times and notice that the number changes on each execution.
Important details about random
import randommust come at the top of the file, before any use.randint(1, 100)includes both1and100. This is different fromrange(), which excludes the upper bound.For testing, it is common to print the secret number during development. Later, this line should be removed or commented out.
Alternative: random.choice()
It is also possible to draw from a sequence:
secret_number = random.choice([10, 20, 30, 40])
randint() is more suitable for continuous intervals, and choice() for specific collections.
3. Loop until the guess is correct
Now that we have the secret number, we need to let the player try to guess it. Since we do not know how many attempts will be needed, the most appropriate loop is while.
First version of the game
import random secret_number = random.randint(1, 100) guess = 0 while guess != secret_number: guess = int(input("Enter your guess (1 to 100): ")) if guess == secret_number: print("Congratulations, you got it right!")
Let us analyze what happens:
The secret number is generated.
guessis initialized to0so that thewhilecondition is true on the first check.The loop asks for a guess and compares it with the secret number.
If the guess is correct, the success message is displayed.
The condition
guess != secret_numberis false and the loop ends.
Problems with this version
There is no feedback beyond "correct" or nothing.
There is no attempt counter.
If the user types something that is not a number, the program crashes with
ValueError.If the user types a number outside the range, nothing prevents it.
We will solve these problems in the next sections.
4. Feedback: too high, too low or correct
Feedback is what makes the game playable. Without it, the player guesses in the dark. We add conditionals to compare the guess with the secret number.
import random secret_number = random.randint(1, 100) guess = 0 while guess != secret_number: guess = int(input("Enter your guess (1 to 100): ")) if guess < secret_number: print("Too low, try again.") elif guess > secret_number: print("Too high, try again.") else: print("Congratulations, you got it right!")
The if/elif/else structure here covers the three possibilities:
Guess lower than the secret: too low.
Guess higher than the secret: too high.
Guess equal: correct.
Note that the else does not need an explicit condition. It captures the only remaining case: equality.
5. Attempt counter
To know how many attempts were needed, we add a counter. It is incremented on each guess and displayed at the end of the game.
import random secret_number = random.randint(1, 100) guess = 0 attempts = 0 while guess != secret_number: guess = int(input("Enter your guess (1 to 100): ")) attempts += 1 if guess < secret_number: print("Too low, try again.") elif guess > secret_number: print("Too high, try again.") else: print(f"Congratulations, you got it right in {attempts} attempts!")
Where to place the increment
The increment must happen after reading the guess and before any message, so that the count matches the number of valid guesses. If it is placed before the read, it counts one extra attempt. If it is placed only in the else, it counts only the correct attempts — which is not what we want.
6. Handling invalid input
A real program needs to deal with input that is not what was expected. If the user types "abc" as a guess, int() raises ValueError and the program crashes. We can handle this with a simple check before conversion, or with try/except (which will be covered in a future lesson).
For now, a check with .isdigit() solves it:
entry = input("Enter your guess (1 to 100): ").strip() if not entry.isdigit(): print("Error: enter only whole numbers.") continue guess = int(entry)
The continue interrupts the current iteration and sends the loop back to the top. Since the counter is only incremented after validation, invalid attempts are not counted.
7. Final version of the game
Putting everything together, we arrive at the complete program:
import random print("Guessing Game") print("=" * 20) print("I picked a number between 1 and 100. Try to guess it!") secret_number = random.randint(1, 100) attempts = 0 while True: entry = input("\nEnter your guess: ").strip() if not entry.isdigit(): print("Error: enter only whole numbers.") continue guess = int(entry) if guess < 1 or guess > 100: print("Error: the guess must be between 1 and 100.") continue attempts += 1 if guess < secret_number: print("Too low, try again.") elif guess > secret_number: print("Too high, try again.") else: print(f"\nCongratulations, you got it right in {attempts} attempts!") break
How the program works
It imports the
randommodule and generates a secret number between 1 and 100.It initializes the attempt counter to
0.It enters a
while Trueloop, controlled by an internalbreak.It reads the input as text and removes spaces.
It checks whether the input is numeric. If not, it displays an error and returns to the top with
continue.It converts to integer and checks whether it is within the valid range. If not, it displays an error and returns to the top.
It increments the counter only after successful validation.
It compares the guess with the secret number and provides the appropriate feedback.
When the player guesses correctly, it displays the total number of attempts and ends the loop with
break.
A note on the structure
We used while True instead of while guess != secret_number. This choice makes the loop explicitly infinite, with the exit controlled by break. It is easier to read because the exit condition is visible at the moment it occurs, not at the top of the loop. It is a very common pattern in games and interactive menus.
8. Suggested tests
Before considering the project complete, it is worth testing the different situations:
| Scenario | Input | Expected behavior |
|---|---|---|
| Valid guess below the number | lower number | "Too low" and next attempt |
| Valid guess above the number | higher number | "Too high" and next attempt |
| Correct guess | equal number | Success message and exit |
| Input with letters | "abc" | Type error, without counting an attempt |
| Input out of range | "200" or "-5" | Range error, without counting an attempt |
| Guess with spaces | " 50 " | Handled correctly by .strip() |
Testing each case is part of the process. Programs that seem to work often fail in scenarios we did not imagine.
9. Possible improvements
The game is functional, but there are several ways to expand it as learning progresses:
Attempt limit: the player has only 7 attempts. This is possible with a
for i in range(7)or a check of the counter in thewhile.Difficulty levels: easy (1 to 50), medium (1 to 100), hard (1 to 500). Just ask the user and adjust the
randint().Play again: after guessing correctly, ask whether they want to play again. An outer
whilesolves it.Guess history: store the guesses in a list and display them at the end. This will be possible with lists.
Game time: measure how long the player took. This will be possible with the
timemodule.
There is no need to implement all of them now. What matters is realizing that the project has room to grow, which is characteristic of any real software.
Lesson wrap-up
In this lesson, you built a complete guessing game, integrating random number generation, a repetition loop, conditionals, counters and input validation. The program works, is readable and follows the patterns of the previous lessons.
What deserves emphasis is the combination of elements: no concept here is new, but integrating them produces a program with real behavior. This is the kind of reasoning that distinguishes someone who learned the syntax from someone who knows how to program.
In the next lesson, we will look at lists, the most used data structure in Python, and how to store and manipulate collections of values.
Suggested exercise
Modify the game to limit the number of attempts to 7. If the player does not guess correctly within 7 attempts, display the secret number and end the game with a defeat message.
Hint: replace while True with while attempts < 7, keeping the break on success. After the loop, check whether the player guessed correctly to decide which message to display.
📄 Copyright: Unless otherwise noted, all articles are original. Please cite the source when sharing.
🔗 Link: http://usandopy.com/en/python-para-iniciantes/projeto-jogo-de-adivinhacao/