PythonMastery

Number guessing game in Python

The computer picks a number from 1 to 100 and the player guesses until they find it, with too high and too low hints, a guess counter and input checks.

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

The number guessing project builds a longer version of this game step by step.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Control Flow: Conditionals, Errors & Exceptions: When Things Go Wrong

A longer explanation: Project: Number Guessing Game