Skip to main content

Command Palette

Search for a command to run...

2024-07-27: Guess the Number

Updated
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.")

More from this blog

达客宁

171 posts

江南有佳丽 生于帝王州 繁花未曾见 王谢纸上闻

茕茕影孑立 烟雨两凄迷 凭栏望楼台 四百寺安在