🐍 Python for Teens & Beginners · Lesson 7 of 7

Project: a guessing game

Google Classroom

The computer picks a number, and you guess.

The plan

  1. The computer picks a secret number from 1 to 100
  2. The player guesses
  3. The computer says “too high” or “too low”
  4. Repeat until the guess is right, then show how many tries it took

The code

import random

secret = random.randint(1, 100)
tries = 0
guess = 0

print("I picked a number from 1 to 100.")
while guess != secret:
    guess = int(input("Your guess: "))
    tries += 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")

print(f"You got it in {tries} tries!")

import random brings in Python’s random module. randint(1, 100) includes both 1 and 100.

Upgrades

Limited triesLose after 7 guesses (a while with and)
Play againWrap everything in another loop that asks “Play again?”
DifficultyEasy 1–10, hard 1–1000
Bad inputUse try/except so typing “abc” doesn’t crash the game

Tip

💡 Smart strategy: always guess the middle (50, then 25 or 75…). You can always win in 7 guesses or fewer — that is binary search, a famous computer-science idea.

✏️ Practice: your turn

  1. Type and run the guessing game
  2. Add a limit of 7 tries
  3. Add “Play again?”
  4. Show it to someone and let them play

✏️ Run Python in your browser, no install ↗

🧠 Quick quiz

Answer all 4 questions correctly to mark this lesson as done.

1. What does random.randint(1, 100) do?
2. Why use a while loop here?
3. What does import random do?
4. How many guesses does binary search need for 1–100 at most?

0 of 4 correct