Project: Guess the number
Project: Guess the number
- The computer thinks of a number. You guess until you find it.
- After every wrong guess, it says Too low or Too high.
- You use
input(),if/elif/else, and awhileloop.
What you will build
3
Too low
9
Too high
7
Correct! You needed 3 guesses.
Step 1: one guess
int(input())turns the typed text into a number, so you can compare it.<means smaller than,>means bigger than.- Use
if/elif/elseto choose one of the three messages.
Step 2: keep guessing
- A
whileloop repeats while its condition is true. !=means is not equal to. Sowhile guess != secret:repeats until the guess is right.- Read the next guess inside the loop, or it will never end.

count = 3
while count != 0:
print(count)
count = count - 1
print("Go!")
Step 3: print the count
- Keep a counter variable. It starts at
1for the first guess. - Add
1every time the loop reads another guess. - When the guess is right, print the counter on its own line. Just the number, nothing else.
Step 4: the sentence
- Now print
Correct! You needed 3 guesses.instead of the bare number. str(guesses)turns the number into text, so you can join it with+.
Play for real
- A real game picks a secret number at random. Run this and play: type your guesses in the box.
import random
secret = random.randint(1, 10)
guess = int(input("Guess a number from 1 to 10: "))
while guess != secret:
if guess < secret:
print("Too low")
else:
print("Too high")
guess = int(input("Try again: "))
print("Correct!")
Now build it
- Four steps. The checks use the secret
7, so the result is always the same.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Step 1: secret הוא 7. Read one guess with int(input()). Print Too low, Too high או Correct!. For the input 3, print Too low.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Step 2: keep asking until the guess is correct. After each wrong guess print Too low או Too high; at the end print Correct!. For the guesses 3, 9 וגם 7, the output is Too low, Too high, Correct!.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Step 3: count the guesses. The loop already adds 1 for each new guess. After the last guess, print only the number, on its own line. For the guesses 3, 9 וגם 7, the output ends with 3.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Step 4: turn the last line into a sentence. Instead of printing the bare number, print Correct! You needed 3 guesses. with the real count. str(guesses) makes the number into text you can join with +. For the guesses 3, 9 וגם 7, the last line is Correct! You needed 3 guesses.
לחץ על הרץ כדי לראות את התוצא כאן.