Number-guessing game
Instead of typing guesses one at a time, you'll give the game a list of guesses and let it judge each one. Once the rules work, you'll write a computer player that never needs more than seven guesses to find a number from 1 to 100.
Skills you'll practise
- Functions
- Conditionals
- Loops
- random
Steps
Step 1: Judge one guess
Finish
check_guess(guess, secret)so it returns"Too low","Too high"or"Correct!".Show a hintHide the hint
Two
ifchecks are enough. If the guess is neither too low nor too high, it must be correct.Step 2: Play through a list of guesses
Loop over the
guesseslist and print each guess with its result.Show a hintHide the hint
enumerate(guesses, start=1)gives you the attempt number and the guess together.Step 3: Stop when it's right
As soon as a guess is correct, print how many tries it took and leave the loop.
Show a hintHide the hint
returninside a function ends the loop and the function in one go.Step 4: Limit the tries
Give the player at most seven guesses. If they run out, reveal the secret number.
Step 5: Let the computer play
Write a player that always guesses the middle of the range that's left, then narrows the range using the hint. Pick the secret with
random.randint(1, 100).Show a hintHide the hint
Keep
lowandhigh. On "Too low", setlow = guess + 1; on "Too high", sethigh = guess - 1.
Starter code
It already runs. The TODO comments mark where to start.
import random
def check_guess(guess, secret):
# TODO: return "Too low", "Too high" or "Correct!"
return "?"
def play(secret, guesses):
# TODO: loop over the guesses, print each result,
# and stop as soon as one is correct.
for guess in guesses:
print(guess, check_guess(guess, secret))
play(42, [50, 25, 37, 43, 40, 42])
Example solution
One way to finish it. Have a go first; yours doesn't need to match.
Reveal the solutionHide the solution
import random
MAX_TRIES = 7
def check_guess(guess, secret):
if guess < secret:
return "Too low"
if guess > secret:
return "Too high"
return "Correct!"
def play(secret, guesses):
for attempt, guess in enumerate(guesses, start=1):
if attempt > MAX_TRIES:
break
result = check_guess(guess, secret)
print(f"Guess {attempt}: {guess} -> {result}")
if result == "Correct!":
print(f"Got it in {attempt} tries.")
return attempt
print(f"Out of guesses. The number was {secret}.")
return None
def computer_guesses(secret, low=1, high=100):
"""Always guess the middle of what's left."""
guesses = []
while low <= high:
guess = (low + high) // 2
guesses.append(guess)
result = check_guess(guess, secret)
if result == "Too low":
low = guess + 1
elif result == "Too high":
high = guess - 1
else:
break
return guesses
print("You:")
play(42, [50, 25, 37, 43, 40, 42])
print()
print("The computer:")
secret = random.randint(1, 100)
play(secret, computer_guesses(secret))
Stretch goal
Run the computer player against every number from 1 to 100 and find which secret numbers take the most guesses. Can you explain why it never needs more than seven?