For new programmers looking to build their skills, few projects are as useful (and fun!) as creating games. One of the best games to start with is a classic number guessing game.
In this in-depth tutorial, we‘ll code a fully-playable number guessing game in Python. You‘ll learn key programming concepts like variables, loops, user input, and more.
By the end, you‘ll have built your first complete program – with plenty of room to expand and customize it!
Why Build a Number Guessing Game?
Before we dive into the code, let‘s look at why number guessing games are such effective educational tools for aspiring developers:
-
Teaches core programming skills – Variables, random number generation, loops, conditionals – you‘ll use them all.
-
Allows creativity – Start simple then add features like hints, scoring, and difficulty levels.
-
Provides a sense of accomplishment – Finishing your first complete program builds confidence!
-
Develops problem solving abilities – You‘ll learn how to break problems down logically.
-
Practices computational thinking – Formulating solutions and algorithms systematically.
-
Introduces game development concepts – Apply programming to interactive entertainment.
Studies confirm that learners retain information better when acquiring skills through creating games rather than traditional methods. So let‘s start our Python journey by building an entertaining number guessing game!
A Brief History of Number Guessing Games
Number guessing games trace their origins back centuries, but became especially popular in the 20th century. Early versions used cards or dice, with players betting on whether their guess would be higher or lower.
The format we know today emerged along with the earliest computers. One of the first computer programs ever written was a simple number guessing game for the EDSAC in 1952.
Text-based number guessing games were common ways for early programmers to learn coding. Versions appeared built into operating systems, programming libraries, and as examples in coding books.
Today, number guessing games are most often used as tutorials when learning a new language like Python. But variations also exist as standalone mobile and web apps, bringing this classic formula to new platforms.
Alright, let‘s start building our own number guessing game as generations of new coders have done before us!
How to Generate a Random Number in Python
The first thing our game needs is a random number for the player to guess. Python‘s built-in random module makes this easy.
To generate a random integer between 1 and 100, we import random and call randint():
import random
random_number = random.randint(1,100)
randint() takes two parameters – the lowest and highest value allowed. It then randomly returns an integer within that range.
We store the result in a variable called random_number to use later when checking the player‘s guess against it.
Pro Tip: For truly random numbers, use
secretsinstead ofrandomwhich is pseudo-random. Importsecretsand callrandbelow(100)to get a secure random int from 0-99.
Now that we can generate a random number, we need to get input from the player.
Accepting User Input in Python
Python‘s input() function allows us to prompt for and accept user input. Let‘s use it to get the player‘s guess:
user_guess = input("Make a guess: ")
This displays the text "Make a guess: " and waits for the user to enter their number, which gets stored as a string in user_guess.
Good to Know:
input()always returns a string. We‘ll need to convert it to an int before comparing to our random number.
Let‘s look at converting user input and comparing the values next.
Converting Input to an Integer and Comparing Values
Since input() returns a string, we need to cast the user‘s guess to an integer with int() before comparing:
user_guess = int(user_guess) # Convert string to int
if user_guess == random_number:
print("You guessed correctly!")
Now we can use the == operator to check if user_guess matches random_number. If so, we congratulate the player on their win!
We‘re making great progress! Next up is letting the player keep guessing until they get it right.
Using Loops for Repeated Guessing
Rather than ending after one guess, we should use a while loop to let the player guess repeatedly:
while user_guess != random_number:
user_guess = int(input("Make a guess: "))
if user_guess == random_number:
print("You guessed it! You win!")
break # Exit loop if guess is correct
This continues looping until the player‘s guess matches the random number, at which point we break out of the loop and congratulate them on their victory!
Providing Hints to Help Guide the Player
Guessing completely blind would get boring quick. Let‘s add helper hints:
if user_guess < random_number:
print("Too low! Guess again!")
elif user_guess > random_number:
print("Too high! Guess again!")
Using if/elif, we can check if their guess is too high or low. The hints make the game more engaging and steer the player in the right direction.
Tracking Number of Guesses Taken
Let‘s add one final touch by tracking how many guesses the player needed to win:
guesses = 1
while True:
# Existing game code
guesses += 1
print(f"You got it in {guesses} guesses!")
Each time through the loop we increment guesses, then print it out after they guess correctly. Now we can see how efficient our player was!
Putting It All Together: The Complete Game Code
We covered a lot of ground, so let‘s look at the full number guessing game code:
import random
print("Guess the number between 1 and 100!")
random_number = random.randint(1,100)
guesses = 0
while True:
guesses += 1
user_guess = int(input("Make a guess: "))
if user_guess == random_number:
print(f"You got it! It took you {guesses} guesses.")
break
elif user_guess < random_number:
print("Too low! Guess again.")
else:
print("Too high! Guess again.")
print("Game over! Thanks for playing.")
In just 25 concise lines, we now have a complete playable number guessing game in Python!
Not only that, but along the way we learned:
- Using the
randommodule - Accepting user input with
input() - Data type conversion with
int() - Comparing values with
== - Looping with
while - Using
breakto exit loops - Conditional logic with
if / elif / else
Now let‘s look at how we can build on this base code.
Expanding the Game by Adding New Features
Part of the fun of programming is taking a simple program and expanding it. Let‘s look at some ways we could add new features to our game:
Limit the number of guesses
Use a counter variable to limit guesses, ending the game if max is reached:
max_guesses = 10
guesses = 0
while True:
guesses += 1
if guesses > max_guesses:
print("You lost - exceeded max guesses!")
break
Implement difficulty levels
Let the player choose easy (1-50), medium (1-100), or hard (1-200) ranges:
difficulty = input("[E]asy, [M]edium or [H]ard? ").lower()
if difficulty == ‘e‘:
max_num = 50
elif difficulty == ‘m‘:
max_num = 100
else:
max_num = 200
random_number = random.randint(1,max_num)
Add scoring
Award points based on number of guesses – fewer guesses, more points:
if guesses <= 3:
print("3 guesses? Amazing - 5 points!")
elif guesses <= 6:
print("Nice work - 3 points")
else:
print("1 point for you.")
Create two player mode
Take turns guessing against each other to see who wins.
Provide hints
Hint if guess is too high/low, or if number is prime/odd/even.
Allow custom range
Let player set any min and max value for random number.
Add a countdown timer
Import time module and give limited time to guess correctly.
The possibilities are endless! See what fun extensions you can come up with and use them to practice your skills.
Common Errors to Watch For
When you‘re just starting out, it‘s easy to make minor coding mistakes. Here are some common errors to look out for:
- Forgetting to convert input to int before comparing
- Using a single = rather than == for comparisons
- Infinite loops caused by incorrect loop condition
- Failing to validate input before using it
Make sure to run your code often and use print statements to debug values. Fixing errors in your code is key programming experience!
Summary and Key Takeaways
And there we have it – a complete walkthrough of building a number guessing game in Python!
We started with a high-level overview explaining why number guessing games are such effective learning tools. Then dove step-by-step into the key concepts:
- Generating random numbers with
randint() - Getting user input with
input() - Converting strings to ints before comparing
- Looping with
whileto allow repeated guesses - Using
if/elif/elsefor hints and win conditions - Tracking guesses taken and scoring
After coding the core game, we looked at how to extend it by adding new features like difficulty levels, timers, scores, and more.
I hope this guide provided a hands-on, newbie-friendly introduction to coding in Python. Learning the fundamentals through creating games is a proven way to develop programming skills.
For more practice, try building other classic games like rock paper scissors, hangman, or tic tac toe. And check out these resources to continue mastering Python.
Happy coding! Let me know if you have any other topics you‘d like me to cover. I‘m always happy to help fellow learners on their programming journey.