2024-07-27: Guess the Number
Yonny
1 min read
import random
# randomly select a number in 1 ~ 100
number = random.randint(1, 100)
# print(number)
print("Welcome to the Number Guessing Game! \nI am thinking a number between 1 to 100.")
level = input("Choose a difficulty level. Type 'easy' or 'hard'.\n")
# set attempts number based on difficulty level
if level == "easy":
attempts = 10
elif level == "hard":
attempts = 5
print(f"You have {attempts} attempts remaining to guess the number.")
# define funtion to verify if the guess number match chosen number
def verify_guess(guess_number):
if int(guess_number) > number:
return("Too high.")
elif int(guess_number) < number:
return("Too low.")
else:
return("You got it!")
# loop the verify function in attempts
while attempts != 0:
guess_number = input("Make a guess:\n")
result = verify_guess(guess_number)
if result != "You got it!":
print(result)
attempts -= 1
print(f"You have {attempts} attempts remaining to guess the number.")
else:
attempts = 0
print (f"You got it! The number was {number}.")
# announce the lose when attempts run out
if result != "You got it!":
print("You've run out of guesses, you lose.")
0
Subscribe to my newsletter
Read articles from Yonny directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by