Build a Number Guessing Game in Python
Build a command-line number guessing game using Python fundamentals.
Introduction
30 Second Summary
Think about the last time you played a guessing game. Someone picks a number, you guess, and they tell you "higher" or "lower" until you nail it.
In this project, you will build that exact game in Python. You'll write a program that picks a secret number between 1 and 100, gives you hints after each guess, and celebrates when you win.
What You'll Build
You'll run your finished game from the terminal, type in guesses, and watch as Python tells you "Too high!" or "Too low!" until you crack the code and see your final score.
By the end of this project, you'll have:
- A working number guessing game you can run from your terminal that generates a secret number, gives hints after each guess, and counts your attempts.
- Error handling that keeps the game running smoothly even when someone types nonsense instead of a number.
- Clean, organized code using functions, f-strings, and early returns that you can explain and modify confidently.
- Secret Mission: Add difficulty levels (Easy/Medium/Hard) with different number ranges and an attempt limit that ends the game if you guess too many times.
Are there any prerequisites?
None. This project starts from zero and includes full setup instructions for Python and your text editor.
Before We Start
Before we dive in, let's lock in what you're about to build and why it matters.
Install Python and Verify Your Setup
You cannot write or run Python code without the interpreter installed and accessible from your terminal. This step gets you from zero to a working Python environment on Windows.
You will download Python, verify it works from the terminal, and set up your project folder with a test file. By the end, you will have a complete workflow: edit code, save, run.
In this step, get ready to:
- Install Python 3.14.6 on Windows 11.
- Verify Python runs from your terminal.
- Create your project folder and run your first script.
Download and install Python 3.14.6
Python is the programming language you will use for this entire project. The installer adds the python command to your terminal so you can run scripts from anywhere.
- Open your browser and go to the Python downloads page:
- https://www.python.org/downloads/release/python-3146/
- Scroll down to the **Files** section and click python-3.14.6-amd64.exe to download the Windows installer (64-bit).
- Once downloaded, double-click the installer file to launch it.
- On the first screen of the installer, check the box that says Add Python to PATH.
- Click Install Now and wait for the installation to complete.
- Click Close when the installer finishes.
Why does Add Python to PATH matter?
PATH is a list of folders your terminal searches when you type a command. Without it, typing python would result in a "command not found" error because your terminal would not know where to find the Python program.
Don't see the Add Python to PATH checkbox?
If the installer shows a different layout, look for any option mentioning PATH or environment variables and enable it. If you accidentally skip it, you can re-run the installer, select Modify, and enable the PATH option.
Help me fix my Python PATH on Windows.
Verify Python is installed
You need to open a fresh terminal to pick up the new PATH settings the installer just configured.
- Press the Windows key to open your search bar.
- Type Terminal and press Enter to open it.
- Check your Python version by running this command:
python --version
✔️ I see Python 3.14.6
Your terminal printed Python 3.14.6. Python is installed and ready to go.
ⓧ I see an older version
If you see a version lower than 3.14 (such as 3.12 or 3.9), your system is finding an older Python installation first.
- Go back to the Python 3.14.6 installer and re-run it.
- Select Modify, then make sure the PATH checkbox is enabled.
- Close your terminal completely and open a new one.
- Run python --version again.
If you still see an older version, open Windows settings, search for App execution aliases, and disable any Python aliases listed there. Then close and reopen your terminal.
Help me get the right Python version showing up.
ⓧ Command not found
If you see an error like "python is not recognized" or "command not found", the installer did not add Python to your PATH.
- Re-run the python-3.14.6-amd64.exe installer.
- Select Modify.
- Make sure the PATH option is checked, then complete the installation.
- Close your terminal completely and open a brand new one.
- Run python --version again.
You must open a new terminal after modifying PATH. Existing terminals do not pick up environment variable changes.
Help me troubleshoot Python not being found.
Now try the interactive interpreter. This is a scratch pad where you can type Python code and see results immediately.
- Enter the Python interactive interpreter by running:
python
You should see a >>> prompt appear. This means Python is waiting for you to type code.
- Type this line and press Enter:
print("Hello, Python!")
You should see Hello, Python! printed on the next line.
- Exit the interpreter by typing:
exit()
What is the interactive interpreter?
The >>> prompt is called the REPL (Read-Eval-Print Loop). It reads your code, evaluates it, prints the result, and loops back for more input.
It is great for quick experiments, but for real programs you will save code in files and run them instead.
Create your project folder and first file
Every project needs its own folder to keep files organized. You will create a folder on your Desktop and put your first Python file inside it.
- Move to your Desktop and create your project folder by running these commands:
cd ~/Desktop
mkdir guessing-game
- Move into your new folder by running:
cd guessing-game
- Confirm you are in the right place by running:
pwd
You should see a path ending in \Desktop\guessing-game.
Seeing an error on mkdir?
If you see "an item with that name already exists", the folder was already created. Run cd guessing-game to move into it and continue.
Help me fix my folder creation issue.
Now create the Python file that will hold your game code.
- Create a new file called game.py by running:
New-Item game.py
- Confirm the file exists by running:
ls
You should see game.py listed in the output.
Now open the file in your text editor and add your first line of code.
- Press the Windows key to open your search bar.
- Type the name of your text editor (such as VS Code) and press Enter to open it.
- Open the guessing-game folder from your Desktop in the editor.
- Open game.py and replace any content with the following code:
print("Game starting...")
What does this code do?
print() is a built-in Python function that displays text in your terminal. The text inside the quotes is called a string. When you run this file, Python reads the instruction and prints Game starting... to your screen.
- Save game.py in your editor.
Before you run this, what do you expect to see printed in the terminal?
- Switch back to your terminal and run your script:
python game.py
You should see Game starting... printed in your terminal. That confirms your full workflow works: you edited a file, saved it, and ran it with Python.
Don't see Game starting... printed?
Make sure you saved the file in your editor before running the command.
Confirm your terminal is inside the guessing-game folder by running pwd. If you are in a different folder, run cd ~/Desktop/guessing-game to get back.
If you see a syntax error, double-check that your file contains exactly print("Game starting...") with matching parentheses and quotes.
Help me figure out why my Python script is not running.
✔️ Awesome, I've got everything!
Great job. Make sure you have saved game.py and move on to the next step.
ⓧ I'd like to double check the full code
Your game.py file should contain exactly this:
print("Game starting...")
Your environment is ready. You have Python installed, a project folder set up, and a working edit-save-run cycle. Next up, you will turn this empty script into a playable number guessing game.
Build the Bare Minimum Game
Your Python environment is ready and your edit-save-run workflow is confirmed. Now it's time to write actual game logic.
The fastest way to learn is to get something running immediately. In this step, you'll write the simplest possible version of the guessing game. No functions, no polish. Just Python's core building blocks in action: a variable, user input, a loop, and conditionals.
In this step, get ready to:
- Write a guessing game that picks a random number and gives feedback on each guess.
- Play the game and verify it works end to end.
- Discover what happens when the game receives unexpected input.
Write the guessing game logic
Your game needs to do three things: pick a random number, ask the player for guesses in a loop, and tell them whether each guess is too high, too low, or correct.
- Open game.py in your text editor.
- Select all the existing code and delete it.
- Replace it with the following code:
import random
# Pick a random number between 1 and 100
secret = random.randint(1, 100)
# Keep asking until the player guesses correctly
while True:
guess = int(input("Your guess: "))
# Give a hint based on the guess
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("Correct!")
break
What does this code do?
- import random brings in Python's built-in random module so you can generate random numbers.
- random.randint(1, 100) picks a random integer between 1 and 100 (inclusive on both ends) and stores it in secret.
- while True creates an infinite loop that keeps running until you explicitly break out of it.
- input("Your guess: ") pauses the program and waits for the player to type something. int() converts that text into a number.
- The if/elif/else chain compares the guess to the secret and prints the matching hint.
Before you run this, think for a moment. What do you expect to see when you run the game and guess a number?
- Save game.py.
- Run the game by entering this command in your terminal:
python game.py
- The game prompts you with Your guess: and waits for input.
- Type a number and press Enter.
- You should see Too low!, Too high!, or Correct! after each guess.
- Keep guessing until you see Correct! and the program exits.
Game not responding or showing errors?
- Make sure you saved game.py before running the command.
- Check that you're running the command from inside the guessing-game folder. Run cd guessing-game if you're not sure.
- If you see SyntaxError, double-check that your colons, parentheses, and indentation match the code above exactly.
- Still stuck? Why isn't my Python game running?
✔️ Awesome, I've got everything!
Great. Make sure you've saved game.py and played at least one full round to see Correct! printed.
ⓧ I'd like to double check the full code
Here's what your game.py should look like:
import random
secret = random.randint(1, 100)
while True:
guess = int(input("Your guess: "))
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("Correct!")
break
Try breaking the game with bad input
Your game works perfectly when the player types a number. But what happens if someone types something that isn't a number?
Before you try it, predict: what do you think Python will do if you type abc instead of a number?
- Run the game again:
python game.py
- When it asks for your guess, type abc and press Enter.
The game crashes with an error that looks like this:
ValueError: invalid literal for int() with base 10: 'abc'
This is expected. Python's int() function cannot convert the text abc into a number, so it raises a ValueError and the program stops immediately.
Why leave it broken?
This crash is intentional. Real programs need to handle unexpected input gracefully, and that's exactly what you'll fix in the next step. Experiencing the problem first makes the solution click.
Your game works and you've seen exactly where it breaks. In the next step, you'll add error handling so bad input gets caught gracefully, and you'll add attempt tracking so the game has a score.
Handle Errors and Count Attempts
In the previous step, you built a working guessing game. But you also discovered its first flaw: type "abc" instead of a number and the game crashes instantly.
The crash happens because int("abc") raises a ValueError. Python cannot convert letters into an integer, so it gives up. In this step, you will add error handling so bad input gets a friendly message instead of a crash. You will also track how many guesses the player takes and report their score.
In this step, get ready to:
- Handle invalid input with try/except so the game never crashes.
- Track attempts and report the player's score when they win.
Wrap input in a try/except block
Python's try/except lets you attempt code that might fail and respond gracefully when it does. The risky line in your game is int(input(...)) because it blows up on anything that is not a number.
- In game.py, find this line inside your while True loop:
guess = int(input("Your guess: "))
- Replace that entire line with this code:
# Get raw input as a string first
raw = input("Your guess: ")
# Try converting to integer - crashes if input isn't a number
try:
guess = int(raw)
except ValueError:
print("Please enter a valid number.")
continue
What does this code do?
- raw = input("Your guess: ") captures whatever the player types as a plain string. No conversion happens yet, so it cannot crash.
- try tells Python "attempt the next line, but be ready for it to fail."
- except ValueError catches the specific error that int() throws on non-numeric input.
- continue skips back to the top of the loop, so the bad input is never counted as a guess.
Before you run this, what do you think will happen if you type "abc" now?
- Save game.py.
- Run your game by running this command:
python game.py
- When the game asks for your guess, type abc and press Enter.
You should see Please enter a valid number. printed, and the game keeps running. No crash.
Still seeing a crash?
- Make sure you deleted the original guess = int(input("Your guess: ")) line entirely. If both the old line and the new block exist, Python hits the old one first.
- Check that continue is indented inside the except block (8 spaces from the left edge). If it sits outside, the loop does not skip back correctly.
- help me fix my try/except block
Add an attempt counter
Your game handles bad input gracefully now. But it has no score. Let's track how many valid guesses the player makes and display that count when they win.
- In game.py, find the line secret = random.randint(1, 100). Add this line directly below it:
attempts = 0
- Find the continue line at the end of your except block. After a blank line below it, add this (at the same indentation level as the try keyword):
attempts += 1
- In the else block at the bottom of the loop, find this line:
print("Correct!")
- Replace it with this line:
print(f"You got it in {attempts} attempts!")
What do these changes do?
- attempts = 0 creates a counter before the loop starts.
- attempts += 1 increments the counter only after a valid guess passes the try block. Invalid input hits continue before reaching this line, so it never inflates the score.
- The f-string (f"...{attempts}...") lets you embed a variable directly inside a string. Python evaluates the expression inside the curly braces and inserts the result.
Before you run this, predict: if you guess correctly on your third try, what will the game print?
- Save game.py.
- Run your game again:
python game.py
- Play the game and guess correctly.
You should see a message like You got it in 5 attempts! (with your actual number of guesses). Try typing abc partway through to confirm it still handles bad input without crashing or inflating your score.
Seeing a NameError for attempts?
- Make sure attempts = 0 is above the while True line, not inside the loop. If it is inside, it resets to 0 every iteration.
- Check that attempts += 1 sits after the except block, not inside it. It should be at the same indent level as the try keyword.
- help me debug my attempts counter
✔️ Awesome, I've got everything!
Great. Double check you have saved game.py before moving on.
ⓧ I'd like to double check the full code
Here is the complete game.py at this point:
import random
secret = random.randint(1, 100)
attempts = 0
while True:
raw = input("Your guess: ")
try:
guess = int(raw)
except ValueError:
print("Please enter a valid number.")
continue
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"You got it in {attempts} attempts!")
break
Your game is now crash-proof and keeps score. Next up, you will refactor this code into clean, reusable functions so you can add features without rewriting everything.
Refactor into Functions
Your game works, but all the code sits in one flat block. If you wanted to add features like replay or difficulty levels, you would have to rewrite large sections from scratch.
Functions solve this by letting you wrap reusable pieces of logic behind a name. In this step, you will reorganize your working code into named functions without changing how the game plays. This is the "write it ugly first, then make it clean" pattern you will use in every project going forward.
In this step, get ready to:
- Extract the game loop into a reusable function called play_round().
- Add a replay feature so the player can keep guessing without restarting the script.
- Simplify your code with an early return pattern that replaces a multi-line if/else block.
Extract the game loop into a function
A function groups related lines under a single name. Once your game logic lives inside a function, you can call it as many times as you want without duplicating code.
- Open game.py in your editor.
- Select all the existing code and delete it.
- Replace the file contents with this play_round() function:
import random
def play_round():
secret = random.randint(1, 100)
attempts = 0
print("\nI'm thinking of a number between 1 and 100.")
while True:
raw = input("Your guess: ")
try:
guess = int(raw)
except ValueError:
print("Please enter a valid number.")
continue
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! You got it in {attempts} attempts!")
return
What does this code do?
This is the same game logic you already wrote, wrapped inside a function called play_round().
- def play_round(): defines the function. Everything indented below it belongs to that function.
- return replaces break. When the player guesses correctly, return exits the function entirely.
- The welcome print tells the player what range to guess within each round.
- Below the play_round() function, add this main guard block:
if __name__ == "__main__":
print("=== Number Guessing Game ===")
play_round()
What is __name__ == "__main__"?
When you run a Python file directly (like python game.py), Python sets a special variable __name__ to the string "__main__".
This guard means "only run this code when the file is executed directly, not when it is imported as a module." It keeps your functions cleanly reusable in other scripts.
- Save game.py.
- Run the game to confirm it still works:
python game.py
You should see === Number Guessing Game === followed by the intro message, and the game plays as before.
Seeing an IndentationError?
Every line inside play_round() must be indented by exactly 4 spaces relative to the def line. Check that your editor is using spaces, not tabs.
help me fix an IndentationError in my play_round function
Add a replay feature
Right now the game ends after one round. A play_again() function will ask the player if they want another go, and a loop in the main block will keep calling play_round() until they say no.
- In game.py, add the following function between play_round() and the if __name__ block:
def play_again():
answer = input("\nPlay again? (y/n): ").lower()
if answer == "y":
return True
else:
return False
What does this function do?
play_again() asks the player a yes/no question and returns True or False. The calling code uses that boolean to decide whether to loop or stop.
- Now replace your existing if __name__ block with this updated version that loops:
if __name__ == "__main__":
print("=== Number Guessing Game ===")
while True:
play_round()
if not play_again():
print("Thanks for playing!")
break
How does the replay loop work?
- while True: creates an infinite loop that keeps running rounds.
- After each round, play_again() returns True or False.
- if not play_again(): means "if the player said no." When that happens, the loop breaks and the game ends.
- Save game.py and run it again:
python game.py
Play through a round, then type y when asked to play again. A new round starts with a fresh secret number. Type n to see Thanks for playing! and exit.
Game not replaying?
Make sure the while True: loop wraps both play_round() and the if not play_again(): check. If play_round() is outside the loop, the game only runs once.
help me debug my replay loop in game.py
Simplify with an early return
Your play_again() function works, but it takes 5 lines to do something that fits on one. An early return skips the if/else ceremony and expresses the logic directly.
- In game.py, find the play_again() function. It currently looks like this:
def play_again():
answer = input("\nPlay again? (y/n): ").lower()
if answer == "y":
return True
else:
return False
- Replace the entire function with this single-line version:
def play_again():
return input("\nPlay again? (y/n): ").lower() == "y"
Why does one line replace five?
The expression input(...).lower() == "y" already evaluates to True or False on its own. Wrapping it in an if/else that returns True or False is redundant. Returning the comparison directly is called an early return. It is shorter, clearer, and a pattern you will see everywhere in Python.
- Save game.py.
Before you run the game, predict: will it behave any differently from the version you just tested?
- Run the game one more time:
python game.py
The game plays identically. The refactoring changed how the code is organized, not what it does. You now have three named functions you could explain to someone: play_round() runs one game, play_again() asks to continue, and the main block ties them together.
Game crashes when you type n?
Make sure the if not play_again(): line in your main block has the correct indentation (8 spaces, inside while True:). Also check that play_again() uses .lower() so both n and N are handled.
help me fix my play_again function
✔️ Awesome, I've got everything!
Great. Double check you have saved game.py and the game replays correctly when you type y.
ⓧ I'd like to double check the full code
Your game.py should contain these three sections in order. Scroll up and confirm each is present:
- import random at the top, followed by the play_round() function (the full game loop with try/except, attempt counter, and return at the end).
- The one-line play_again() function: return input("\nPlay again? (y/n): ").lower() == "y".
- The if __name__ == "__main__": block that prints the banner, loops play_round(), checks play_again(), and breaks with Thanks for playing!.
Your game is now organized into clean, named functions. Next up: you will push these skills further in the Secret Mission by adding difficulty levels and an attempt limit.
Secret mission
Add Difficulty Levels and an Attempt Limit
Your game always picks a number between 1 and 100 with unlimited guesses. What if you could choose Easy, Medium, or Hard mode? In this mission, you'll design a difficulty system using dictionaries and tuples, then enforce an attempt limit that ends the game if you guess too many times.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely locally, so there are no ongoing costs. Decide whether to keep your resources running, pause them to come back later, or delete them entirely.
Resources you used:
- Python 3.14 installation on your system.
- The guessing-game project folder containing game.py.
Keep everything running
No action needed. Choose this if you plan to keep learning Python or want to revisit this game later.
- Python stays installed and available from your terminal for future projects.
- Your guessing-game folder stays on your Desktop, ready to run anytime with python game.py.
Pause - I'll come back to this later
Since this project is just a single file on your Desktop, there is nothing to pause. Your files stay where they are until you decide to delete them.
- Python uses no background resources when you are not running a script.
- The guessing-game folder takes up a negligible amount of disk space.
Delete - I don't want to use this again
Remove all project resources and uninstall Python if you no longer need it.
- Delete the project folder by opening PowerShell and running:
cd ~/Desktop
rmdir /s /q guessing-game
- To uninstall Python, open Settings.
- Select Apps, then Installed apps.
- Search for Python in the search bar.
- Click the three-dot menu next to Python 3.14.6 and select Uninstall.
- Follow the prompts to complete the removal.
Nice Work!
Nice Work!
You just built a complete Python game from scratch. Starting from a blank terminal with no Python installed, you now have a fully playable number guessing game that handles errors, tracks scores, and replays on demand.
You've learned how to:
- Build a playable command-line game using variables, loops, conditionals, and user input that gives instant feedback after every guess.
- Handle unexpected input with try/except so your program never crashes, and refactor messy code into clean functions with f-strings and early returns.
- Import and use the random standard library module to generate secret numbers, giving you the pattern for using any Python library.
- Secret Mission: Design a difficulty system using dictionaries and tuples, enforce an attempt limit, and build a multi-function program architecture.
Ready to quiz yourself?