Book a free demo

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 - 1
50 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

  1. 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.
  2. This is called binary search. With 100 numbers it never needs more than 7 guesses, because 2 to the power of 7 is 128.
  3. while True loops forever, and break is the way out.
See the Python path โ†’

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

All 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

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

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.

All free games โ†’
Chat on WhatsApp
Esc

Try