[英]Try Except Block not passing after correct input
我是 Python 和一般编码的新手,并且在我的代码中遇到了一些错误。 每当我在 Try/Except 代码块中输入错误的输入时,控制台都会打印“无效输入”但是,每当我在控制台中输入正确的短语时,它仍会显示“无效输入”。 我在网上查看以尝试使用这些代码行解决此问题(用## 表示),但我仍然遇到相同的问题。
例如,我会用正确的大小写和所有内容输入“Mad Libs”,但仍然从我的 != 命令中得到“无效输入”。 这可以通过以不同的方式格式化来轻松解决吗? 所有 3 场比赛都会发生这种情况。
如何解决这个问题? 提前致谢!
def game_selection(): ##
pass ##
while True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
game_selection() ##
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")
因为您在此代码中要求它无论如何回答无效输入
While True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
问题是,此代码将不起作用,因为如果我输入“Mad Libs”,第一个 if 将不会通过,因此它将传递给所有其他 elif。 所以你不能采取这种方法。 我建议你做的是检查 playerChoice 字符串是否在数组中
from time import sleep
while True:
playerChoice = input("So, which game would you like to play?:")
allowedGames = ["Mad Libs", "Guessing Game", "Language Maker"]
if playerChoice not in allowedGames:
print('Invalid input!')
else:
break
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.