This post is part of an ongoing series - see all the posts below.
We have covered a lot of ground so far, variables, data types, control flow, lists and dictionaries, functions, and modules. That is more than enough to actually build something. Before we move on to the next section, let's stop and put everything together into a small project.
We are going to build a number guessing game. The computer picks a random number between 1 and 100, and the user tries to guess it. After each guess, the script tells the user whether their guess is too high, too low, or correct. We will also keep track of how many attempts it took, and put a limit on the number of guesses.
This is a classic beginner project, but it is a great way to revisit everything we have learned. By the end of this chapter, you will have used:
- Variables and data types
- f-strings
- User input and type conversion
if/elif/elsestatements- A
whileloop withbreak - The
randommodule - A function to wrap it all together
Step 1 - Pick a Random Number
The first thing we need is for the computer to pick a number. We just learned about the random module, so this is a perfect use case for random.randint().
import random
secret_number = random.randint(1, 100)
print(f"The secret number is {secret_number}")
The secret number is 73
Right now we are printing the secret number so we can see it while we build the game. We will remove that print statement once everything is working.
Step 2 - Get a Guess from the User
Next, we need to ask the user for a guess. We learned about input() back in Chapter 3, and we also know that input() always returns a string, so we need to convert it to an integer using int().
import random
secret_number = random.randint(1, 100)
guess = int(input("Guess a number between 1 and 100: "))
print(f"You guessed {guess}")
Guess a number between 1 and 100: 50
You guessed 50
Step 3 - Compare the Guess
Now we use an if/elif/else block to compare the guess with the secret number and give feedback.
import random
secret_number = random.randint(1, 100)
guess = int(input("Guess a number between 1 and 100: "))
if guess < secret_number:
print("Too low")
elif guess > secret_number:
print("Too high")
else:
print("Correct!")
Guess a number between 1 and 100: 50
Too low
This works for a single guess, but a real guessing game lets the user keep trying until they get it right. That is where a loop comes in.
Step 4 - Loop Until the User Gets It Right
We want the script to keep asking for guesses until the user gets the correct answer. This is exactly what a while loop is for. We will use while True to loop forever, and break to exit the loop when the user guesses correctly.
import random
secret_number = random.randint(1, 100)
while True:
guess = int(input("Guess a number between 1 and 100: "))
if guess < secret_number:
print("Too low")
elif guess > secret_number:
print("Too high")
else:
print("Correct!")
break
Guess a number between 1 and 100: 50
Too low
Guess a number between 1 and 100: 75
Too high
Guess a number between 1 and 100: 63
Too low
Guess a number between 1 and 100: 70
Correct!
The game now keeps running until the user guesses the right number.
Step 5 - Track the Number of Attempts
It would be nice to tell the user how many guesses it took. We can do this by adding a counter that starts at zero and goes up by one inside the loop.
import random
secret_number = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if guess < secret_number:
print("Too low")
elif guess > secret_number:
print("Too high")
else:
print(f"Correct! You got it in {attempts} attempts.")
break
Guess a number between 1 and 100: 50
Too low
Guess a number between 1 and 100: 75
Too high
Guess a number between 1 and 100: 63
Too low
Guess a number between 1 and 100: 70
Correct! You got it in 4 attempts.
Step 6 - Add a Limit on the Number of Guesses
Right now, the user has unlimited guesses. Let's make it more interesting by limiting them to 7 attempts. If they do not get it within 7 tries, the game ends and reveals the secret number.
import random
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
while attempts < max_attempts:
guess = int(input(f"Guess a number between 1 and 100 (attempt {attempts + 1}/{max_attempts}): "))
attempts += 1
if guess < secret_number:
print("Too low")
elif guess > secret_number:
print("Too high")
else:
print(f"Correct! You got it in {attempts} attempts.")
break
else:
print(f"Out of guesses! The number was {secret_number}.")
Guess a number between 1 and 100 (attempt 1/7): 50
Too low
Guess a number between 1 and 100 (attempt 2/7): 75
Too high
Guess a number between 1 and 100 (attempt 3/7): 60
Too low
Guess a number between 1 and 100 (attempt 4/7): 65
Correct! You got it in 4 attempts.
Notice the else block attached to the while loop. The else block runs only if the while loop finishes naturally, without hitting a break. So if the user runs out of guesses, the else block runs and reveals the number. If they guess correctly, the break skips the else.

