Skip to content

ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ

Project: Number guessing game

5 min readፕሮጀክት

Time to build a real game, using nearly everything from Modules 1 to 3. The computer picks a secret number from 1 to 100. You guess, and it tells you "Too high" or "Too low" until you find it, then says how many attempts you took. Here's a finished game:

Output
Guess: 50
Too high
Guess: 25
Too high
Guess: 12
Too low
Guess: 18
Too low
Guess: 21
Too high
Guess: 20
You got it in 6 attempts!

You'll build it in five milestones, running it after each one. In the browser your guesses come from the Input box, which already holds a full game for each milestone.

Milestone 1: one guess

Start with a secret number you choose yourself, and a single guess. Don't forget lesson 1.5: input() gives you text.

መልመጃ

Check one guess

Ask for a guess and print Too high, Too low, or You got it!.

Your code

secret = 42
# Ask for a guess, then print Too high, Too low, or You got it!

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

secret = 42
guess = int(input("Guess: "))
if guess > secret:
    print("Too high")
elif guess < secret:
    print("Too low")
else:
    print("You got it!")

Milestone 2: keep guessing

Now repeat until the guess is right, and count the attempts. That's two plans you know: guess is a latest value, and attempts is a counter. Where the counter goes up matters. Predict what this version says at the end:

ውጤቱን ገምቱ

Decide before you look. Guessing wrong is how this sticks.

secret = 42
attempts = 0
while True:
    guess = int(input("Guess: "))
    if guess > secret:
        print("Too high")
    elif guess < secret:
        print("Too low")
    else:
        attempts = attempts + 1
        print(f"You got it in {attempts} attempts!")
        break

When it asks, the user types 50, 25, then 42።

Python prints

Guess: 50
Too high
Guess: 25
Too low
Guess: 42
You got it in 1 attempts!

The counter only goes up in the winning branch, so the two wrong guesses were never counted. Every guess is an attempt, so count it right after reading it, before the if.

መልመጃ

Loop until it's right

Put your guess in a loop, count every guess, and print the number of attempts when it's right.

Your code

secret = 42
guess = int(input("Guess: "))
if guess > secret:
    print("Too high")
elif guess < secret:
    print("Too low")
else:
    print("You got it!")

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

secret = 42
attempts = 0
while True:
    guess = int(input("Guess: "))
    attempts = attempts + 1
    if guess > secret:
        print("Too high")
    elif guess < secret:
        print("Too low")
    else:
        print(f"You got it in {attempts} attempts!")
        break

Milestone 3: a random secret

A game where you know the answer isn't much of a game. Python's random module picks numbers for you. import random makes it available (lesson 8.5 explains imports), and random.randint(1, 100) picks a whole number from 1 to 100.

randint includes both ends: it can pick 1, and it can pick 100. That's different from range(1, 100), which stops before 100. Mixing the two up is a classic bug.

ጥያቄ

Which numbers can random.randint(1, 10) give?

A random secret makes the output different every time, which makes it hard to check. random.seed(2019) fixes that: after it, the "random" numbers come out the same on every run, so this lesson can show you exactly what to expect. With this seed, the secret is 20. When your game works, delete the seed line and play for real.

መልመጃ

Pick the secret at random

Replace secret = 42 with a random number from 1 to 100, and seed it with 2019. The Input box plays a game that finds 20 by halving.

Your code

secret = 42
attempts = 0
while True:
    guess = int(input("Guess: "))
    attempts = attempts + 1
    if guess > secret:
        print("Too high")
    elif guess < secret:
        print("Too low")
    else:
        print(f"You got it in {attempts} attempts!")
        break

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

import random

random.seed(2019)
secret = random.randint(1, 100)
attempts = 0
while True:
    guess = int(input("Guess: "))
    attempts = attempts + 1
    if guess > secret:
        print("Too high")
    elif guess < secret:
        print("Too low")
    else:
        print(f"You got it in {attempts} attempts!")
        break

Milestone 4: bad guesses don't count

Players mistype. A guess that isn't a number shouldn't crash the game, and a guess outside 1 to 100 shouldn't cost an attempt. Read the guess as text first. Then text.isdigit() tells you whether the text is all digits (True or False); you'll meet more tools like it in Module 6. Skip bad guesses with continue, before the counter goes up.

መልመጃ

Handle bad guesses

If the text isn't all digits, print Please type a whole number. If the number is outside 1 to 100, print Guess from 1 to 100. Neither counts as an attempt. The Input box has a word, a number that's too big, and then the same game as before, so it should still take 6 attempts.

Your code

import random

random.seed(2019)
secret = random.randint(1, 100)
attempts = 0
while True:
    guess = int(input("Guess: "))
    attempts = attempts + 1
    if guess > secret:
        print("Too high")
    elif guess < secret:
        print("Too low")
    else:
        print(f"You got it in {attempts} attempts!")
        break

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

import random

random.seed(2019)
secret = random.randint(1, 100)
attempts = 0
while True:
    text = input("Guess: ")
    if not text.isdigit():
        print("Please type a whole number.")
        continue
    guess = int(text)
    if guess < 1 or guess > 100:
        print("Guess from 1 to 100.")
        continue
    attempts = attempts + 1
    if guess > secret:
        print("Too high")
    elif guess < secret:
        print("Too low")
    else:
        print(f"You got it in {attempts} attempts!")
        break

That's the complete game. Test it with the three kinds of game a player can have: one you win, one full of typos, and, after the stretch, one you lose. (isdigit() isn't a perfect test: it turns away -5, which int() accepts, and lets through a few characters int() can't convert, like ፩. Lesson 7.2 shows the better way: try int() and handle the error.)

Milestone 5: seven tries, and play again (stretch)

With halving (guess the middle, then the middle of what's left), you never need more than 7 guesses for 1 to 100: each guess cuts the possibilities in half, and 100 halves to 1 in seven steps. So a limit of 7 attempts is fair. That idea, halving, is one of the most important in computing, and it comes back later in the course.

Add the limit with a constant, MAX_ATTEMPTS = 7, and a flag, won: it starts False and becomes True when the player wins, so after the loop you know which way it ended. Then wrap the whole game in an outer loop that asks to play again.

መልመጃ

Limit and replay (stretch)

Stop after 7 counted attempts and reveal the number. After each game, ask Play again? (y/n) and start a new game on y. The Input box plays a losing game (always 10 too high), then answers n.

Your code

import random

random.seed(2019)
MAX_ATTEMPTS = 7
# One game per round of an outer loop; inside it, your game from milestone 4,
# stopping after MAX_ATTEMPTS attempts

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

import random

random.seed(2019)
MAX_ATTEMPTS = 7
while True:
    secret = random.randint(1, 100)
    attempts = 0
    won = False
    while attempts < MAX_ATTEMPTS:
        text = input("Guess: ")
        if not text.isdigit():
            print("Please type a whole number.")
            continue
        guess = int(text)
        if guess < 1 or guess > 100:
            print("Guess from 1 to 100.")
            continue
        attempts = attempts + 1
        if guess > secret:
            print("Too high")
        elif guess < secret:
            print("Too low")
        else:
            print(f"You got it in {attempts} attempts!")
            won = True
            break
    if not won:
        print(f"Out of attempts! The number was {secret}.")
    again = input("Play again? (y/n) ")
    if again != "y":
        break

Change the last n in the Input box to y, then add guesses for a second game. The seed makes the second secret 32: can you find it in 7?

ዋና ዋና ነጥቦች

  • Build a game in milestones: a fixed secret, the loop, randomness, validation, then extras.
  • Convert input before comparing it with a number, and count every attempt right after reading it.
  • random.randint(1, 100) includes both 1 and 100; range(1, 100) stops before 100.
  • random.seed(...) makes random numbers repeat, which makes a program testable.
  • Plans combine: a latest value, a counter, a constant, a flag, and "skip bad input" with continue.