Project: Guess the number
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
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: count the guesses
- Keep a counter variable. It starts at
1for the first guess. - Add
1every time the loop reads another guess. 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
- Three steps. The checks use the secret
7, so the result is always the same.
Step 1: secret is 7. Read one guess with int(input()). Print Too low, Too high or Correct!. For the input 3, print Too low.
Click Run to see the output here.
Step 2: keep asking until the guess is correct. After each wrong guess print Too low or Too high; at the end print Correct!. For the guesses 3, 9 and 7, the output is Too low, Too high, Correct!.
Click Run to see the output here.
Step 3: count the guesses. Instead of Correct!, print Correct! You needed 3 guesses. (with the real number). For the guesses 3, 9 and 7, the last line is Correct! You needed 3 guesses.
Click Run to see the output here.