The number guessing game is one of the best first projects you can write in Python. It is short enough to finish in a single sitting, but it forces you to use loops, conditionals, user input, and the standard library all at once — the exact skills that show up in every real Python program.
Python's random module picks a secret number. A while loop keeps asking the player for guesses. An if/elif/else block gives higher/lower feedback after each guess. When the player lands on the right number, the loop ends and Python prints the result. That is the whole game in four sentences — and by the time you finish this tutorial, you will have written every line of it from scratch.
What the Game Does
Before writing code, it helps to know exactly what you are building. The higher/lower number guessing game works like this: Python secretly picks a random integer between 1 and 100. The player types a number. Python responds with "Too high," "Too low," or "Correct!" If the player guesses correctly, the game prints how many attempts it took and exits.
The game runs entirely in the terminal. There is no graphical interface. All input and output happens through input() and print().
Here is what the complete finished game looks like when a player runs it:
Guess a number between 1 and 100: 50
Too high!
Guess a number between 1 and 100: 25
Too low!
Guess a number between 1 and 100: 37
Too high!
Guess a number between 1 and 100: 31
Correct! You got it in 4 attempts.
Build the correct statement to import the random module and generate a number between 1 and 100:
The Tools You Need
The game uses three Python features. You do not need to install anything extra — all three come with every standard Python installation.
- What it does
- Returns a random integer N where a <= N <= b. Both endpoints are included in the possible range.
- Why you need it
- It generates the secret number the player is trying to guess. Without it, every game would have the same answer.
- What it does
- Repeats a block of code as long as a condition remains true. When the condition becomes false, execution moves to the next line after the loop.
- Why you need it
- The player may need many guesses. A while loop keeps prompting without you having to predict how many rounds the game will take.
- What it does
- Tests conditions in order and executes only the first branch whose condition is true.
elifstands for "else if" and lets you chain multiple conditions. - Why you need it
- There are three possible outcomes for any guess: too high, too low, or correct. Each outcome needs its own response, which is exactly what if/elif/else handles.
- What it does
input()reads a line of text from the player and returns it as a string.int()converts that string to an integer.- Why you need it
- You cannot compare a string to an integer with > or <. Wrapping input() with int() gives you a number you can actually do math with.
This code tries to read the player's guess and compare it to the secret number, but there is one mistake. Click the line you think is wrong, then hit check.
guess = int(input("Your guess: ")). input() always returns a string. Comparing a string to an integer using > raises a TypeError in Python 3. Wrapping the call with int() converts the player's text to an integer so the comparison works correctly.
Building the Game Step by Step
The full game is built piece by piece below. Each code block builds on the last. By the end of this section you will have a complete, working program.
Step 1 — Import and generate the secret number
The first two lines set everything up. import random loads Python's random number module. random.randint(1, 100) picks a whole number anywhere from 1 to 100, inclusive, and stores it in secret. The player never sees this value.
import random
secret = random.randint(1, 100)
Step 2 — Set up the game loop
Before the loop starts, two variables are initialised. attempts tracks how many guesses the player has made. guess is set to None so the while condition is true from the very first iteration. The loop runs as long as guess does not equal secret.
import random
secret = random.randint(1, 100)
attempts = 0
guess = None
while guess != secret:
# game logic goes here
pass
Setting guess = None before the loop is a common Python pattern. None != secret is always true, which guarantees the loop body runs at least once without needing a separate do-while construct (Python does not have one).
Step 3 — Read the player's guess
Inside the loop, increment attempts, then read a guess from the player. The int() wrapper is required: input() returns a string, and you cannot compare a string to an integer using > or < in Python 3.
while guess != secret:
attempts += 1
guess = int(input("Guess a number between 1 and 100: "))
Step 4 — Give higher/lower feedback
Immediately after reading the guess, an if/elif/else block evaluates it against the secret number and prints the appropriate hint. The else branch is never reached during normal game flow — it would only run if guess == secret, but in that case the loop condition becomes false and execution falls through to the win message anyway. The branch is included here for clarity and can be removed in the final version.
if guess > secret:
print("Too high!")
elif guess < secret:
print("Too low!")
Step 5 — Print the win message and the complete game
After the while loop exits, the player has guessed correctly. One print() call using an f-string tells them how many attempts it took. Here is the entire game in one block:
import random
secret = random.randint(1, 100)
attempts = 0
guess = None
while guess != secret:
attempts += 1
guess = int(input("Guess a number between 1 and 100: "))
if guess > secret:
print("Too high!")
elif guess < secret:
print("Too low!")
print(f"Correct! You got it in {attempts} attempts.")
"Simple is better than complex." — The Zen of Python (PEP 20)
How to Build a Number Guessing Game in Python
Follow these six steps from a blank file to a working higher/lower game. Each step maps directly to a section of the code above.
-
Import the random module
Add
import randomat the very top of your file. This makes therandom.randint()function available. Without this line, Python does not know where to find it. -
Generate the secret number
Write
secret = random.randint(1, 100). Python picks a random integer between 1 and 100 inclusive and stores it. This value does not change for the rest of the game. -
Set up the game loop
Declare
attempts = 0andguess = None, then writewhile guess != secret:. The loop body will repeat until the player guesses the correct number. -
Read and convert the player's guess
Inside the loop, write
attempts += 1followed byguess = int(input("Guess a number between 1 and 100: ")). Theint()call converts the player's text to a number so it can be compared. -
Give higher/lower feedback
Add an
if guess > secret: print("Too high!")block followed byelif guess < secret: print("Too low!"). These two branches cover all wrong guesses and tell the player which direction to adjust. -
Print the win message
After the loop (at zero indentation), write
print(f"Correct! You got it in {attempts} attempts."). This line runs once — as soon as the while condition becomes false.
Python Learning Summary Points
- The
whileloop is the right tool whenever the number of iterations is not known in advance. The game could end on guess 1 or guess 50 — the loop handles both without any changes to the code. input()always returns a string. Any time you need to do arithmetic or comparisons on user-provided values, you must convert them first withint(),float(), or another conversion function.- The
randommodule is part of Python's standard library. You do not install it — you only import it. Understanding how to use standard library modules is a core Python skill that scales directly into larger projects. - f-strings (introduced in Python 3.6) are the preferred way to embed variable values inside strings. The pattern
f"You took {attempts} attempts"is cleaner and faster than older string formatting approaches. - A well-defined game loop — initialise state, check a condition, update state, repeat — is a pattern that appears far beyond games. It shows up in data processing pipelines, network polling, and any other situation that requires repeated actions until a goal is reached.
The version above is intentionally minimal so the core mechanics are easy to read. When you are ready to extend it, consider adding a maximum attempt limit (use a separate counter with an or condition in the while), wrapping the int(input(...)) call in a try/except ValueError block to handle non-numeric input gracefully, or letting the player choose a difficulty level that adjusts the range from 1–100 to something larger.
Frequently Asked Questions
A number guessing game teaches while loops, if/elif/else conditionals, the random module, user input with the input() function, integer conversion with int(), and basic game loop logic — all in around 15 lines of code.
random.randint(a, b) returns a random integer N such that a <= N <= b. Both endpoints are included in the possible range. Calling random.randint(1, 100) can return any integer from 1 through 100, inclusive.
The input() function always returns a string. You must wrap it with int() to convert that string to an integer before comparing it to the randomly generated number. Without the conversion, Python raises a TypeError when it tries to evaluate "50" > 37.
The while loop keeps the game running until the player guesses correctly. It checks the condition guess != secret before each iteration and repeats the guess-and-check cycle until that condition becomes false — meaning the player found the right number.
Declare an integer variable such as attempts = 0 before the loop, then increment it with attempts += 1 at the start of each loop iteration. After the loop exits, attempts holds the total number of guesses.
Without error handling, int() raises a ValueError and the program crashes. You can prevent this by wrapping the int() call in a try/except ValueError block that catches the error and prompts the user to enter a valid number before continuing the loop.
Ask the player to choose a difficulty before the game starts. Map each choice to a maximum number of allowed attempts — for example, Easy: 10, Medium: 7, Hard: 5. Then modify the while condition to while guess != secret and attempts < max_attempts: so the game ends early if the player runs out of guesses.
You need import random once per file, at the top. You do not repeat it before every function call. Python loads the module once when it first encounters the import statement; after that, all calls to random.randint() in the same file work without re-importing.