是否有一种方法,我可以修改这段代码有如果猜==退出部分的工作?



我希望有人能帮我弄清楚为什么"if guess == 'exit'破裂"Line在my中被忽略代码。如果输入的值是exit,则应该中断。下面是我的代码:

import random
#initializing random class
number = random.randint(1, 9)
print("Welcome to the Guessing Game!")
#asking user to write there preferred username
name = input("What is your name? ")
# asking the player to decide if they want to play the game or not by choosing yes/no
play = input("{}, Would you like to play the guessing game? (Enter Yes/No) ".format(name))

循环从这里开始。如果用户选择yes,则循环运行

while play.lower() != "no":
try:
guess = 0
count = 0
while guess != number and guess != "exit":
guess = input("{}, What is your guess? ".format(name))
# this block is supposed to run if the user enters exit as the guessed number
if guess == "exit":
break
# Converting user input to an integer and incrementing count
guess = int(guess)
count += 1
# this section evaluates the number guessed to either greater than, less than or equal to the 
number
if guess < number:
print("Your guess is too Low {}, please try again".format(name))
elif guess > number:
print("Your guess is too High {}, please try again".format(name))
else:
print("Congrats {}! You guessed the correct number".format(name))
print("And it took you ", count, " tries")
# captures value errors
except ValueError as err:
print("Oh no! The value you entered is out of range")
print("({})".format(err))
# runs if the user selects no
else:
print("Please try again later")

如果guessexit,则可以使用外循环中的另一个break,因为对象guess可用于外循环。

while play.lower() != "no":
try:
guess = 0
count = 0
while guess != number and guess != "exit":
# remove content of while loop for brevity 
# another exit in the outer loop
if guess == "exit":
break
except ValueError as err:
print("Oh no! The value you entered is out of range")
print("({})".format(err))
# runs if the user selects no
else:
print("Please try again later")

理想情况下,你应该尝试重构你的代码,使其在函数中编写代码,并使用返回语句。

相关内容

最新更新