Python Program for a Number Guessing Game
Beginner · Games and random numbers
In the number guessing game the computer picks a secret number from 1 to 100, and the player keeps guessing while the computer answers "too high" or "too low" until the guess is right. Here the program plays the player too, using the smartest strategy of always guessing the middle of the numbers that are still possible, so it runs without anyone typing.
Program
I am thinking of a number from 1 to 100. Guess 1: 50 is too high Guess 2: 25 is too low Guess 3: 37 is too low Guess 4: 43 is correct! Found the number 43 in 4 guesses
How it works
random.randint(1, 100)picks the secret number, so it is different on every run, and so is the output.- Each guess is the middle of the range from
lowtohigh, worked out with whole number division//. - When the guess is too low, every number up to it is ruled out, so
lowmoves toguess + 1; when it is too high,highmoves toguess - 1. - Halving the range every time means the number is always found in at most 7 guesses, which is why the loop is sure to end with
break. - To play the game yourself, replace the line that works out
guesswith theinput()line from the comment.
Another way to write it
With a limited number of chances
50 is too high. Chances left: 4 25 is too low. Chances left: 3 37 is too low. Chances left: 2 43 is too high. Chances left: 1 40 is too low. Chances left: 0 Out of chances! The number was 42
Here the secret and the guesses are fixed, so the output is the same on every run and shows the losing case. The else after the for loop runs only when the loop ends without break, that is, when no guess was right.
Try it yourself
Change the range to 1 to 1000 and check that the program still finds the number in at most 10 guesses.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises