我正在為 Number Guessing Game Objectives 撰寫代碼。我有一個問題,因為我的代碼中沒有列印分數。您還有其他改進我的代碼的線索嗎?
任務描述:允許玩家對 1 到 100 之間的數字進行猜測。將用戶的猜測與實際答案核對。列印“太高”。或“太低了”。取決于用戶的回答。如果他們的答案正確,請向玩家展示實際答案。跟蹤剩余的匝數。如果他們用完了回合,請向玩家提供反饋。包括兩個不同的難度級別(例如,簡單模式中的 10 次猜測,困難模式中只有 5 次猜測)。
import random
number = random.randint(0,100)
print ("Psst, secret number is: ", number )
print("\nHello. It is guesss number game where you have gueass number between 0 and 100.\n\n")
level = input("Which level do you want to choose 'easy' or 'hard'? ")
number_of_attempts = 0
if level == "easy":
number_of_attempts = 10
if level == "hard":
number_of_attempts = 5
while number_of_attempts > 0:
guess = int(input("Guess a number = "))
if number_of_attempts == 0: # this line is not printed.
print (f"You lost, poor sod. Correct number was {number}.")
elif guess > number:
print("Number is smaller.")
number_of_attempts =number_of_attempts - 1
elif guess < number:
print("Number is bigger")
number_of_attempts =number_of_attempts - 1
elif guess == number: #This line is not printed too.
print ("You are right")
uj5u.com熱心網友回復:
num = random.randint(1,10)
def num_guess():
attempts = 3 #create a variable that will count the number of attempts
while attempts > 0: #while loops continues as long as attempts is greater than 0
attempts -= 1 #with each iteration, the loop subtracts 1
try:
userGuess = int(input("Enter a number between 1 and 10: "))
except ValueError:
print("Invalid input. Try again.") # a try/except block raises an exception for any value that's not an integer
continue
if attempts > 0: # this condition will allow the player to continue to play as long as the attempts is greater than 0
if userGuess == num:
print("You guessed the number!!")
break
elif userGuess < num:
print(f"The number is too low.\nYou have {attempts} attempts left.")
elif userGuess > num:
print(f"The number is too high.\nYou have {attempts} attempts left.")
else:
print("You did not guess the number.\Thanks for playing!")
num_guess()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416347.html
標籤:
