Mini-Project: The Number-Guessing Game

Python for Absolute Beginners · Lesson 16

What you’ll learn

1 / 13

The game, in plain words

2 / 13

A new tool: random

3 / 13

Reading a guess

guess_text = input("Guess a number from 1 to 10: ")
guess = int(guess_text)
print(guess)

7

If the player types 7, this prints 7 — as a number now, ready for comparison.

4 / 13

The whole game — part 1: setup and loop

import random

secret = random.randint(1, 10)
tries = 0

print("I am thinking of a number from 1 to 10.")
print("Can you guess it?")

while True:
    guess_text = input("Your guess: ")
    guess = int(guess_text)
    tries = tries + 1

The secret is picked once, the counter starts at zero, and the loop repeats until the player wins.

5 / 13

The whole game — part 2: hints and win

    if guess == secret:
        print("You got it!")
        print("It took you " + str(tries) + " tries.")
        break
    elif guess < secret:
        print("Too low — try higher.")
    else:
        print("Too high — try lower.")

Exactly one response per guess: equal, too low, or too high. Break exits the loop the moment the player wins.

6 / 13

A sample run

I am thinking of a number from 1 to 10.
Can you guess it?
Your guess: 3
Too low — try higher.
Your guess: 8
Too high — try lower.
Your guess: 5
You got it!
It took you 3 tries.

The secret is different every time, so your run will differ — that is why the game stays fun.

7 / 13

How the pieces fit together

8 / 13

Make it yours

9 / 13

Hands-on exercise

10 / 13

Key takeaways

11 / 13

Take the quiz

Take the Lesson 16 quiz — 5 quick questions to check what you learned.

12 / 13

Next lesson

What's Next: Stepping into Python 3 Programming

13 / 13

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.