🎓 A1Learner
🔍

Python Project: Guessing Game

A guessing game is a game where a player guesses a secret number.

Pick a secret number

The seed fixes the order of the picks. With seed 7, the first pick is always 42.

import random
random.seed(7)
secret = random.randint(1, 100)
print(secret)

Give a hint

You compare the guess with the secret. The words Too high or Too low guide the player.

secret = 42
guess = 50
if guess < secret:
    print("Too low.")
elif guess > secret:
    print("Too high.")
else:
    print("Correct!")

Count the guesses

This small loop plays with a ready list of guesses. It counts each try until the right one.

secret = 42
guesses = 0
for guess in [50, 30, 42]:
    guesses += 1
    if guess == secret:
        print("Found in", guesses, "guesses.")

Ask to play again

After a game, the player types y or n. The answer picks what happens next.

answers = ["y", "n"]
for answer in answers:
    if answer == "y":
        print("New game.")
    else:
        print("Stop.")

Example

import random


def play_game():
    secret = random.randint(1, 100)
    guesses = 0
    while True:
        guess = int(input("Guess a number 1-100: "))
        guesses += 1
        if guess < secret:
            print("Too low.")
        elif guess > secret:
            print("Too high.")
        else:
            print(f"Correct! Total guesses: {guesses}.")
            break


random.seed(7)
while True:
    play_game()
    again = input("Play again? (y/n): ")
    if again != "y":
        print("Thanks for playing.")
        break

Key points

  • import random loads the random module, as in the Modules section
  • random.seed() fixes the pick order, as the Random lesson showed
  • random.randint(1, 100) picks the secret whole number
  • Use a while loop to keep asking until the guess is right
  • Use a counter to count how many guesses were used
  • In the game, the player keeps guessing until the guess matches the secret number.

In this example, the full game runs on scripted input. With this input, one value per line: 50, 30, 42, y, 20, n. The seed 7 makes the first secret 42. The guess 50 is too high, and 30 is too low. The guess 42 is right, and the counter shows 3 guesses. The answer y starts a new game, and the next secret is 20. One guess wins it, and the answer n ends the game with a thank-you line.

Note

The seed is only for this demo.

A real game skips the seed, so each new game feels fresh.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does random.seed(7) do in this lesson?