🐍 Python for Teens & Beginners · Lesson 7 of 7
Project: a guessing game
The computer picks a number, and you guess.
The plan
- The computer picks a secret number from 1 to 100
- The player guesses
- The computer says “too high” or “too low”
- 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 tries | Lose after 7 guesses (a while with and) |
|---|---|
| Play again | Wrap everything in another loop that asks “Play again?” |
| Difficulty | Easy 1–10, hard 1–1000 |
| Bad input | Use 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
- Type and run the guessing game
- Add a limit of 7 tries
- Add “Play again?”
- Show it to someone and let them play
🧠 Quick quiz
Answer all 4 questions correctly to mark this lesson as done.
0 of 4 correct
All lessons in Python for Teens & Beginners
- 👋 1. Your first programprint, quotation marks, and error messages
- 📦 2. Variables and inputStore information and ask the user
- 🧮 3. Math in PythonOperators, division, remainder and powers
- 🔀 4. Conditions: if and elseThe program decides by itself
- 🔁 5. Loops: for and whileRepeat code without copying it
- 📋 6. ListsMany values in one variable
- 🎲 7. Project: a guessing gameThe computer picks a number, and you guess