The computer picks a random number. The player keeps guessing, and after each guess the program says "too low" or "too high". A while True loop repeats until the guess is right, and break ends it.
The program
python
import random random.seed(7) # fixed seed so the output matches this page; remove it for real use secret = random.randint(1, 100) tries = 0 print("I am thinking of a number from 1 to 100.") while True: text = input("Your guess: ") try: guess = int(text) except ValueError: print("Please type a whole number.") continue if guess < 1 or guess > 100: print("The number is between 1 and 100.") continue tries += 1 if guess < secret: print("Too low.") elif guess > secret: print("Too high.") else: print(f"Correct! You found it in {tries} tries.") break
Typed in this example: 50, twenty, 25, 37, 150, 43, 40, 42. Press Run to type your own.
output
I am thinking of a number from 1 to 100. Your guess: 50 Too high. Your guess: twenty Please type a whole number. Your guess: 25 Too low. Your guess: 37 Too low. Your guess: 150 The number is between 1 and 100. Your guess: 43 Too high. Your guess: 40 Too low. Your guess: 42 Correct! You found it in 6 tries.
How it works
random.randint(1, 100)picks a whole number from 1 to 100. Both ends are included.while Truerepeats for ever. The only way out is thebreakafter a correct guess.int(text)raises aValueErrorif the player types something liketwenty. Thetry/exceptcatches it, prints a message, andcontinuegoes straight back to the top of the loop for a new guess.- Bad input and out-of-range numbers do not count as tries, because
tries += 1comes after those checks. - Halving the range each time (50, 25, 37, ...) always finds the number in 7 guesses or fewer. This is the idea behind binary search.
The number guessing project builds a longer version of this game step by step.