Editor

Number Guessing Game in Python

Beginner · Games · about 30 minutes to build · 88 lines

The computer picks a secret number from 1 to 100, and you have seven tries to find it with a hint after every guess.

The program

Press Run and answer its questions in the box that appears under the code.

number_guessing_game.py
"""Number guessing game: find the secret number in as few tries as you can."""
import random
LOW = 1
HIGH = 100
MAX_TRIES = 7
def tries_text(count):
"""Return "1 try" or "3 tries" so the messages read naturally."""
return f"{count} try" if count == 1 else f"{count} tries"
def ask_guess(low, high):
"""Ask until the player types a whole number from low to high."""
while True:
text = input(f"Your guess ({low}-{high}): ").strip()
try:
guess = int(text)
except ValueError:
print(" Please type a whole number.")
continue
if low <= guess <= high:
return guess
print(f" The number is between {low} and {high}.")
def play_round():
"""Play one game and return the tries used, or None if the player lost."""
secret = random.randint(LOW, HIGH)
low, high = LOW, HIGH
print(f"I'm thinking of a number from {LOW} to {HIGH}. You have {tries_text(MAX_TRIES)}.")
for attempt in range(1, MAX_TRIES + 1):
guess = ask_guess(low, high)
if guess == secret:
print(f" Correct. You found it in {tries_text(attempt)}.")
return attempt
# Narrow the range so the next prompt shows what is still possible.
if guess < secret:
low = guess + 1
hint = "Too low."
else:
high = guess - 1
hint = "Too high."
left = MAX_TRIES - attempt
if left:
print(f" {hint} {tries_text(left)} left.")
print(f" {hint} Out of tries. The number was {secret}.")
return None
def ask_yes_no(prompt):
"""Ask a yes/no question and return True for yes."""
while True:
answer = input(prompt).strip().lower()
if answer in ("y", "yes"):
return True
if answer in ("n", "no"):
return False
print(" Please type y or n.")
def main():
"""Play rounds until the player wants to stop, tracking the best score."""
print("=== Number Guessing Game ===\n")
best = None
while True:
tries = play_round()
if tries is not None and (best is None or tries < best):
best = tries
print(f" New best score: {tries_text(best)}.")
print()
if not ask_yes_no("Play again? (y/n) "):
break
print()
if best is None:
print("Thanks for playing.")
else:
print(f"Thanks for playing. Your best was {tries_text(best)}.")
if __name__ == "__main__":
main()

Open it in the full editor to save it, share it and keep building.

Sample run

What the program printed, and what was typed (in yellow).

=== Number Guessing Game ===

I'm thinking of a number from 1 to 100. You have 7 tries.
Your guess (1-100): 50
  Too high. 6 tries left.
Your guess (1-49): 60
  The number is between 1 and 49.
Your guess (1-49): fifty
  Please type a whole number.
Your guess (1-49): 25
  Too low. 5 tries left.
Your guess (26-49): 37
  Too low. 4 tries left.
Your guess (38-49): 43
  Too high. 3 tries left.
Your guess (38-42): 42
  Correct. You found it in 5 tries.
  New best score: 5 tries.

Play again? (y/n) maybe
  Please type y or n.
Play again? (y/n) y

I'm thinking of a number from 1 to 100. You have 7 tries.
Your guess (1-100): 50
  Too high. 6 tries left.
Your guess (1-49): 25
  Too high. 5 tries left.
Your guess (1-24): 15
  Too low. 4 tries left.
Your guess (16-24): 20
  Correct. You found it in 4 tries.
  New best score: 4 tries.

Play again? (y/n) n
Thanks for playing. Your best was 4 tries.

How it is built

1. The settings at the top

LOW, HIGH and MAX_TRIES are constants. Change them in one place to make the game easier or harder.

LOW = 1
HIGH = 100
MAX_TRIES = 7

2. Reading a guess safely

int(text) raises ValueError when the player types letters, so the try/except catches it and asks again. A number outside the range is refused too, so the function only returns a guess the game can use.

def ask_guess(low, high):
    """Ask until the player types a whole number from low to high."""
    while True:
        text = input(f"Your guess ({low}-{high}): ").strip()
        try:
            guess = int(text)
        except ValueError:
            print("  Please type a whole number.")
            continue
        if low <= guess <= high:
            return guess
        print(f"  The number is between {low} and {high}.")

3. One round of the game

random.randint(LOW, HIGH) picks the secret, and the for loop gives the player MAX_TRIES attempts. After each wrong guess low or high moves, so the next prompt shows only the numbers still possible. The function returns the tries used, or None when the player runs out.

def play_round():
    """Play one game and return the tries used, or None if the player lost."""
    secret = random.randint(LOW, HIGH)
    low, high = LOW, HIGH
    print(f"I'm thinking of a number from {LOW} to {HIGH}. You have {tries_text(MAX_TRIES)}.")

    for attempt in range(1, MAX_TRIES + 1):
        guess = ask_guess(low, high)
        if guess == secret:
            print(f"  Correct. You found it in {tries_text(attempt)}.")
            return attempt

        # Narrow the range so the next prompt shows what is still possible.
        if guess < secret:
            low = guess + 1
            hint = "Too low."
        else:
            high = guess - 1
            hint = "Too high."
        left = MAX_TRIES - attempt
        if left:
            print(f"  {hint} {tries_text(left)} left.")

    print(f"  {hint} Out of tries. The number was {secret}.")
    return None

4. Playing again and the best score

main() keeps playing rounds while ask_yes_no returns True. It remembers the fewest tries in best, which starts as None because no game has been won yet.

def main():
    """Play rounds until the player wants to stop, tracking the best score."""
    print("=== Number Guessing Game ===\n")
    best = None
    while True:
        tries = play_round()
        if tries is not None and (best is None or tries < best):
            best = tries
            print(f"  New best score: {tries_text(best)}.")
        print()
        if not ask_yes_no("Play again? (y/n) "):
            break
        print()

    if best is None:
        print("Thanks for playing.")
    else:
        print(f"Thanks for playing. Your best was {tries_text(best)}.")

Make it bigger

  • Add a difficulty menu that sets HIGH and MAX_TRIES, such as 1 to 50 with 8 tries or 1 to 1000 with 10.
  • Save the best score to a text file so it is still there the next time you play.
  • Let two players take turns and see who finds the number in fewer tries.
  • Turn the game around: you think of a number and the computer finds it by halving the range each time.

What it practises