Free video project · Beginner
Build a number guessing game 🎯
The computer picks a secret number from 1 to 100 and you guess until you get it, with a seven guess limit and a check that the player typed a number.
The code from the video
import random
secret = random.randint(1, 100)
tries = 0
while True:
answer = input("Guess a number from 1 to 100: ")
if not answer.isdigit():
print("Numbers only, please")
continue
guess = int(answer)
tries += 1
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
else:
print(f"You got it in {tries} tries!")
break
if tries == 7:
print(f"Out of guesses! It was {secret}")
break
Run it in your browser with nothing to install, right here on this page.
Make it your own
- Let the player choose easy (1 to 50), medium (1 to 100) or hard (1 to 1000) at the start.
- Swap the roles: you think of a number and Python guesses it using too high or too low.
- Keep a best score and print "New record!" when the player beats it.
Skills: while loops, input, if and elif, random