Input和if-else语句正在做一些奇怪的事情

  • 本文关键字:if-else 语句 Input python
  • 更新时间 :
  • 英文 :


我用Python做了一个数字猜谜游戏,它要求一个介于1到100之间的数字。你可以在简单级别和难级别之间进行选择。轻松级别有10次,艰难级别有5次机会。问题是,如果你给级别输入的不是简单的或硬的(包括大写变体(,它会做一些奇怪的事情。我需要一个解决方案。这是代码。

import random
print("Welcome to the number guessing game.")
random_number: int = random.randint(0, 101)
print("I'm thinking of a number between 1 and 100.")
total_chances = 0
game_level = input("Type a difficulty. Type 'easy' or 'hard': ").lower()
if game_level == 'easy':
total_chances = 10
elif game_level == 'hard':
total_chances = 5
else:
print("Please make sure that you typed the correct command")
is_game_over = False
while not is_game_over:
print(f"You have {total_chances} chances remaining to guess the number.")
guess_a_number = int(input("Guess a number: "))
if guess_a_number == random_number:
is_game_over = True
print(f"You got it!! The answer was {random_number}. nYou win.")
elif guess_a_number > random_number:
total_chances -= 1
print("Too high.nGuess again.")
elif guess_a_number < random_number:
total_chances -= 1
print("Too low.nGuess again.")
else:
print("Guess a number. Please make a correct numerical input.")
if total_chances <= 0:
is_game_over = True
print("You ran out of chances. You lose!!")
print(f"The answer was {random_number}")

代码中的问题是,当用户输入错误的游戏级别时,它只打印警告消息,然后继续total_chances为0,is_game_overFalse。由于后者是Falsewhile循环,即猜测阶段无论如何都会运行,即使total_chances为零

尝试

is_game_over = False
if game_level == 'easy':
total_chances = 10
elif game_level == 'hard':
total_chances = 5
else:
print("Please make sure that you typed the correct command")
is_game_over = True

当用户输入错误的难度等级时,这将结束游戏;由于is_game_overTrue,所以跳过while循环。

您只需添加while循环即可获得输入,直到输入正确的难度级别,如下所示:

total_chances = 0
while(total_chances==0):
game_level = input("Type a difficulty. Type 'easy' or 'hard': ").lower()

if game_level == 'easy':
total_chances = 10
elif game_level == 'hard':
total_chances = 5
else:
print("Please make sure that you typed the correct command")

最新更新