Guess the Number: Random Edition
Build a number-guessing game that chooses a new secret whole number from 1 to 20 each time it runs. Give the player six attempts, with a higher-or-lower hint after every valid wrong guess.
Reveal a hint (from the printed book)
Store secret = random.randint(1, 20). Compare the player’s number against it on each turn. Break or return after a correct guess.
Reveal a worked Python solution
One possible implementation. Check the book's tests and try an extension after comparing.
# Challenge 81 - Guess the Number: Random Edition
import random
def feedback(guess, secret):
if guess < secret:
return "Higher!"
if guess > secret:
return "Lower!"
return "Correct!"
def play():
secret = random.randint(1, 20)
for turn in range(1, 7):
try:
guess = int(input(f"Guess {turn}/6 (1-20): "))
except ValueError:
print("Enter a whole number. This guess is used.")
continue
if not 1 <= guess <= 20:
print("Outside 1-20. This guess is used.")
continue
result = feedback(guess, secret)
print(result)
if result == "Correct!":
return
print(f"Out of guesses. The number was {secret}.")
if __name__ == "__main__":
play()Save this Python file ↓