Mini-Project: Number Guessing Game
Before you start
#What you'll build
secret = 37 instead of picking a random number).Sample interaction
I picked a number between 1 and 100. Can you guess it?
Your guess: 50
Too high! Try again.
Your guess: 25
Too low! Try again.
Your guess: 37
Too high! Try again.
Your guess: 31
You got it in 4 tries!
#What you'll learn
After this lesson, you will be able to:
- Generate a random integer with random.randint
- Keep asking for input with a while loop until a condition is met
- Compare two values and give different feedback with if/elif/else
#Step 1: Pick a secret number
random module ships with Python, with no install needed. random.randint(1, 100) returns a random integer between 1 and 100, inclusive.import random
secret = random.randint(1, 100)
print(f"(Debug: the secret is {secret})")Print the secret for now so you can verify the rest of the logic. We'll remove that line at the end.
How is random.randint(1, 6) different from range(1, 6)?
What's the range of `random.randint(1, 100)`?
#Step 2: Ask for a guess
input() always returns a string, so you have to call int() if you want to compare it to a number.This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
guess = int(input("Your guess: "))
print(f"You guessed {guess}")int() will crash with a ValueError. We'll ignore that for now and add validation in a later lesson on error handling.What happens at runtime? secret = 42 guess = input("Guess: ") # user types 42 print(guess == secret)
#Step 3: Compare guess to secret
if/elif/else.if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print("You got it!")guess = secret to make sure the "got it" branch works, then with a wrong guess to make sure the high/low branches work.Why use `elif` instead of two separate `if` statements?
#Step 4: Loop until correct
while True loop runs forever — unless you break out of it. Combine that with the comparison from Step 3 so the program keeps asking until the user wins.while True:
guess = int(input("Your guess: "))
if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print("You got it!")
breakbreak immediately exits the closest loop. Without it, your game would run forever even after the user won.What does this print? for i in range(5): if i == 2: break print(i) print("done")
#Step 5: Count the tries
Track how many guesses the user took with a counter. Increment it on every guess. Display it when they win.
This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
import random
secret = random.randint(1, 100)
tries = 0
print("I picked a number between 1 and 100. Can you guess it?")
while True:
guess = int(input("Your guess: "))
tries += 1
if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print(f"You got it in {tries} tries!")
breakThat's the full game. Optimal play with binary search wins in 7 tries or fewer for any number between 1 and 100 — see if you can spot why.
#Now build it yourself
Number Guessing Game with try counter
Build a game where the computer picks a number from 1 to 100. The user keeps guessing, and you tell them higher or lower after each guess. When they win, print how many tries it took. Put the game in a function `play(secret, next_guess)` that returns the number of tries (the starter shows how it is called). Bonus: rate them ('Lucky!' for under 7, 'Solid!' for 7-10, 'Keep trying!' for 11+). In this browser, type your guesses, one per line, in the Input box above Run; to test, replace `random.randint(1, 100)` with 37.
I picked a number between 1 and 100. Can you guess it?
Your guess: 50
Too high! Try again.
Your guess: 25
Too low! Try again.
Your guess: 37
Too high! Try again.
Your guess: 31
You got it in 4 tries! Lucky!This code calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
#Now make it your own
Try one of these variations:
- Reverse it — YOU pick the secret, the computer guesses. Use binary search: it should win every time in 7 tries or fewer.
- Hard mode — limit the player to 7 guesses. If they run out, print "Game over — the number was X".
- Hot/cold hints. After each guess, also say "getting warmer" or "getting colder" based on whether they're closer or further than last time.