Confident ยท ages 11+ ยท while loop ยท binary search ยท functions
Number guessing game (the computer plays) in Python.
Find a secret number between 1 and 100 by always guessing the middle. See that it takes at most 7 guesses.
The program
Press Run to see what it prints. Change anything you like, then run it again.
secret = 73
low, high = 1, 100
guesses = 0
while True:
guess = (low + high) // 2
guesses = guesses + 1
if guess == secret:
print("Found", guess, "in", guesses, "guesses")
break
elif guess < secret:
print(guess, "is too low")
low = guess + 1
else:
print(guess, "is too high")
high = guess - 150 is too low 75 is too high 62 is too low 68 is too low 71 is too low Found 73 in 6 guesses
How it works
- Instead of asking a person, the program plays by itself. Each guess is the middle of the numbers that are still possible, so the number of possibilities halves every time.
- This is called binary search. With 100 numbers it never needs more than 7 guesses, because 2 to the power of 7 is 128.
while Trueloops forever, andbreakis the way out.
Try this
- Change the secret number and see how many guesses it takes.
- Find the largest number of guesses for any secret from 1 to 100.
- Make it work for numbers up to 1000.
Stuck on an error? Read how to debug Python.
Similar ideas
More programs
FAQ
Number guessing game (the computer plays): questions
What does the number guessing game (the computer plays) program do?
Find a secret number between 1 and 100 by always guessing the middle. See that it takes at most 7 guesses. It prints: 50 is too low / 75 is too high / 62 is too low โฆ
Which Python ideas does it use?
while loop, binary search, functions. Confident level, suitable from about age 11.
How do I run it?
Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.
What should I try next?
Change the secret number and see how many guesses it takes. Find the largest number of guesses for any secret from 1 to 100. Make it work for numbers up to 1000.
Start a conversation
Want a teacher to guide the learning?
Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.
- Tell us the learnerโs age or grade and goals
- Weโll suggest a suitable class or learning path
- Weโll confirm format, timing and fees with a parent or guardian
Play it, don't just read it
Write some code right now
Free games that need no sign-up. Pick one and play for five minutes.
Pick a game
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay