48. Guess the number
Write a program that judges a number-guessing game. It reads whole numbers, one per line:
- The first line is the secret number.
- Every line after it is a guess. For each guess, print
Too lowif it is smaller than the secret,Too highif it is bigger. - For the right guess, print
Correct! You took N guesses., where N counts every guess, the right one included. When the first guess is right, printCorrect! You took 1 guess.(one guess, not "guesses"). - Stop after the right guess: there may be more lines, and they must not be read.
Compare the guesses as numbers: as text, "99" would count as bigger than "100".
Example 1
Input
42
50
25
42Output
Too high
Too low
Correct! You took 3 guesses.Explanation50 is too high, 25 too low, then 42.
Example 2
Input
7
7
3Output
Correct! You took 1 guess.ExplanationRight first time; the 3 is never read.
Constraints
- Every number is a whole number from 1 to 100, alone on its line.
- One of the guesses is right, so the game always ends.
- Print nothing else. A prompt inside
input()is fine: the tests leave it out of the output.
Submit also runs 5 more tests you can't see.
Practises User Input (lesson 6).
int(input())reads one line as a whole number. Read the secret once, before the loop, and one guess each time round the loop.while True:loops until something stops it:breakleaves the loop once the guess is right, so no more lines are read.- Count with a number that goes up by one each guess, and choose the word with
"guess" if count == 1 else "guesses".
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
# Read the secret number from the first line. # Then read guesses one at a time, saying "Too low" or # "Too high", until the right one; count the guesses.
Run your code to see how it does on the test cases, or Submit to check every test.