Number guessing games are an excellent way to start learning Python. They allow you to practice fundamental programming concepts like variables, loops, conditional logic, and functions while creating an interactive and engaging game.
In this comprehensive guide, you’ll learn how to code a number guessing game in Python step-by-step. We’ll cover key topics like generating random numbers, taking user input, using loops and conditional statements, defining functions, tracking attempts, and adding replay options.
Table of Contents
Open Table of Contents
- Overview of the Number Guessing Game
- Import the Random Module
- Generate the Random Number
- Take User Input for the Guess
- Use a Loop for Repeated Guessing
- Check if Guess is Correct
- Give Feedback on Wrong Guess
- Print Remaining Attempts
- Complete Game Loop
- Define a Function for Game Logic
- Add Replay Option
- Complete Python Program for Number Guessing Game
- Key Concepts and Techniques
- Summary
Overview of the Number Guessing Game
The objective of the game is for the player to guess a random number generated by the computer within a limited number of attempts. The game gives feedback on whether each guess is too high or too low and keeps count of remaining guesses. Once the player guesses the number correctly or runs out of attempts, the game ends and gives the option to play again.
Some key features of the game:
-
The computer randomly selects an integer between 1 and 20 that the player must guess.
-
The player has a maximum of 5 attempts to guess the number.
-
After each guess, the computer tells the player if their guess was too high or too low.
-
The game tracks number of remaining guesses and ends once the player guesses correctly or uses up all attempts.
-
Option to play the game again at the end without having to restart the program.
Below we will go through the step-by-step process of coding this game in Python along with explanations and code examples.
Import the Random Module
Since we want the computer to randomly generate the number for the user to guess, we need to import the random
module. This module contains functions for generating pseudo-random numbers in Python.
import random
Generate the Random Number
Next, we need to actually generate the random number for the game. The random
module provides a function called randint()
that allows you to generate a random integer between two specified values (inclusive).
Let’s use randint()
to generate a random number between 1 and 20:
random_number = random.randint(1,20)
This will store the randomly generated number between 1 and 20 in the variable random_number
.
Take User Input for the Guess
We need a way to get input from the user for their guess. Python provides the input()
function for this. It allows you to prompt the user for input and store that input in a variable.
Let’s prompt the user to enter a guess and store it:
guess = int(input("Enter your guess between 1 and 20: "))
A few things to note here:
-
We use the
input()
function to display a prompt and wait for the user’s input. This is stored as a string. -
We convert the input to an integer using
int()
since we want to compare it numerically later. -
The prompt clearly tells the user to enter a number between 1 and 20.
Use a Loop for Repeated Guessing
We want to allow the user to keep guessing repeatedly within the attempt limit. For this, we’ll use a while
loop.
The loop will continue running as long as the user has attempts left and has not guessed the number correctly. We can track both these conditions using variables.
attempts_left = 5
number_guessed = False
while attempts_left > 0 and not number_guessed:
# Game logic goes here
attempts_left -= 1
-
attempts_left
variable tracks number of guesses left. We initialize it to 5 attempts. -
number_guessed
variable is a boolean that tracks if the user guessed the number correctly. It starts as False. -
On each iteration, we reduce
attempts_left
by 1 to track remaining guesses. -
The loop exits when either attempts use up or the user guesses the number correctly.
Check if Guess is Correct
Inside the loop, we need to check if the user’s guess matches the random number generated by the computer.
We can do this simply using an if
statement:
if guess == random_number:
print("You guessed the number correctly!")
number_guessed = True
If guess matches random number, we print a success message and update number_guessed
to True
to exit the loop.
Give Feedback on Wrong Guess
If the guess is wrong, we need to give the user feedback if their guess was too low or too high, so they can adjust accordingly.
if guess < random_number:
print("Your guess was too low!")
if guess > random_number:
print("Your guess was too high!")
Using two if
statements, we can check if guess is lower or higher than random number and print the appropriate hint.
Print Remaining Attempts
As we loop through repeatedly for guesses, we also want to print the remaining attempts left on each iteration, so user knows how many guesses they have left.
We can simply print the attempts_left
variable which we decrement each loop.
print("You have {attempts_left} attempts left".format(attempts_left = attempts_left))
This prints a message with the attempts formatted in.
Complete Game Loop
Putting it all together, here is what the complete game loop looks like:
attempts_left = 5
number_guessed = False
while attempts_left > 0 and not number_guessed:
guess = int(input("Enter your guess (1-20): "))
if guess == random_number:
print("You guessed the number correctly!")
number_guessed = True
elif guess < random_number:
print("Your guess was too low!")
else:
print("Your guess was too high!")
attempts_left -= 1
print("You have {attempts_left} attempts left".format(attempts_left = attempts_left))
print("Game over! The number was", random_number)
This allows repeated guessing within attempt limit, gives feedback on each guess, and exits the loop either when user guesses correctly or runs out of turns.
Define a Function for Game Logic
As the game logic grows, we can wrap it in a function to make the code more modular and reusable.
This also allows us to easily call the game again if user wants to play repeatedly.
def play_game():
attempts_left = 5
number_guessed = False
random_number = random.randint(1,20)
while attempts_left > 0 and not number_guessed:
# Game loop logic
print("Game over! The number was", random_number)
play_game()
Now we can call play_game()
whenever we want to play the game again rather than having all logic cluttered in global scope.
Add Replay Option
To give the user the option to play again without restarting the program, we can add a replay loop.
play_again = 'y'
while play_again == 'y':
play_game()
play_again = input("Do you want to play again? (y/n) ")
We initialize play_again
to y
and start a while
loop checking for this condition.
Inside the loop, we call the game function and then prompt if user wants to play again, storing their option in play_again
.
This allows the game to be played repeatedly unless user enters n
to quit.
Complete Python Program for Number Guessing Game
Here is the complete Python program putting all the concepts together:
import random
def play_game():
attempts_left = 5
number_guessed = False
random_number = random.randint(1,20)
print("I have randomly chosen a number between 1 and 20.")
while attempts_left > 0 and not number_guessed:
guess = int(input("Make a guess: "))
if guess == random_number:
print("You guessed the number correctly!")
number_guessed = True
elif guess < random_number:
print("Your guess was too low!")
else:
print("Your guess was too high!")
attempts_left -= 1
print("You have {attempts_left} attempts left".format(attempts_left = attempts_left))
print("Game over! The number was", random_number)
play_again = 'y'
while play_again == 'y':
play_game()
play_again = input("Do you want to play again? (y/n) ")
This gives you a complete number guessing game in Python with all the key features, playable repeatedly.
To add more polish, you can keep track of wins and losses, customize the attempt limit, or add difficulty levels. But the core gameplay is fully functional.
Key Concepts and Techniques
Building this game allowed us to practice several fundamental Python programming concepts:
Random Number Generation - Used the random
module to generate a random number unknown to the user. Useful for games, simulations, cryptography, and more.
Variables - Used variables like random_number
, guess
, attempts_left
etc. to store values and refer to them programmatically.
User Input - Took keyboard input from the user with input()
and stored it in a variable to use later.
Conditional Logic - Used if
, elif
, else
statements and booleans to implement decision making.
Loops - Used while
loop to repeat game logic and allow multiple guesses until a condition is met.
Functions - Broke game logic into reusable function play_game()
for cleaner code.
Printing - Printed messages to give game feedback and guide the user.
This covers many core programming basics like variables, data types, boolean logic, control flow, functions, and more. The game format helps cement these concepts through practice.
Summary
In this guide, we went through a step-by-step process to code a number guessing game in Python.
We learned how to generate random numbers, take user input, use loops and conditionals, define functions, give game feedback, and add replay options.
The full source code is available above to use as a template for your own Python games.
Some ways to expand on this basic game include:
- Keeping score of wins and losses
- Increasing difficulty by modifying attempt limit
- Hints or powerups to help user guess
- Different difficulty levels to choose from
- Styling with ASCII art
- Saving high scores across sessions
Coding games like this help reinforce key programming skills while being fun and rewarding to build. You can apply these concepts to more complex Python projects as you continue learning.