Number Guessing Game
What you'll build
A Python script that picks a random number between 1 and 100, reads guesses in a loop, prints "Higher!" or "Lower!" after each wrong guess, and congratulates the player when they win.
Goals
- Generate a random integer with random.randint
- Read user input with input() and convert it to int
- Use a while loop that repeats until the guess is correct
- Track the number of attempts and print it at the end
Prerequisites
- Variables and assignment
- if/else statements
- while loops
Steps
- 1
Import random and pick a target
Import the random module and pick a secret number with random.randint(1, 100). Print a welcome message so the player knows the range.
Codeimport random target = random.randint(1, 100) print("I picked a number between 1 and 100.")Expected result
Running the script prints the welcome message; target holds a hidden number.
- 2
Read the first guess
Use input() to read a guess and int() to convert it to a number. Reading input is what lets the loop make progress.
Codeguess = int(input("Enter your guess: "))Expected result
The script waits for the player to type a number and stores it in guess.
Hint
If the player types non-numeric input, int() raises ValueError. For now, assume valid input.
- 3
Loop until correct with hints
Wrap the comparison in a while guess != target loop. Inside, print "Higher!" if guess is too low, "Lower!" if too high, then read a new guess. The loop exits when the guess matches.
Codewhile guess != target: if guess < target: print("Higher!") else: print("Lower!") guess = int(input("Enter your guess: ")) print("You got it!")Expected result
Wrong guesses print a hint and ask again; a correct guess prints the win message.
- 4
Count the attempts
Add an attempts counter that starts at 1 and increments inside the loop. Print it at the end so the player sees their score.
Codeattempts = 1 while guess != target: if guess < target: print("Higher!") else: print("Lower!") guess = int(input("Enter your guess: ")) attempts += 1 print(f"You got it in {attempts} tries!")Expected result
After winning, the script shows how many guesses the player used.
- 5
Add input validation & exception handling
Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.
Codedef safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)Expected result
Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.
Try it yourself
import random
target = random.randint(1, 100)
print("I picked a number between 1 and 100.")
# TODO: read guess, loop with hints, count attemptsimport random
target = random.randint(1, 100)
print("I picked a number between 1 and 100.")
guess = int(input("Enter your guess: "))
attempts = 1
while guess != target:
if guess < target:
print("Higher!")
else:
print("Lower!")
guess = int(input("Enter your guess: "))
attempts += 1
print(f"You got it in {attempts} tries!")What you learned
You combined random.randint, a while loop, conditional branches, and input reading into a complete interactive game — the same control-flow shape used by many CLI programs.
Related Resources
Related Lessons
- Loops
The while loop that drives the guessing loop.
- Conditions
if/else branches that compare the guess to the target.
Related Practice
- Loops Predict
Predict how many times a loop runs.
- Variables MCQ
Quiz on variable assignment and reassignment in the loop.
Related Tools
- Password Generator
See how secure random values are produced in a browser tool.
Related Cheatsheets
- Python Cheatsheet
Syntax reference for loops, conditionals, and input.
Related Reference
- Python List Methods
Complete list method reference.
Related Errors
- Syntax Error
Common Python syntax mistakes.
- Name Error
Using undefined variables.
- Indentation Error
Inconsistent indentation.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Related Errors
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
- Syntax Error
Common Python syntax mistakes.
- Name Error
Using undefined variables.
- Indentation Error
Inconsistent indentation.