我不知道为什么我的尝试和除外无法正常工作。我希望它在用户输入字符串“ y”或“ n”时继续执行,但是如果用户没有输入任何字符串,则输出错误。
输出:
userInput = input("Are both players ready to start? (y/n): ")
k (userInput)
Here we go!
预期输出:
userInput = input("Are both players ready to start? (y/n): ")
k (userInput)
Wrong Input, Try Again
try:
if userInput == "y":
print("Here we go! ")
print()
elif userInput == "n":
print("Too bad we're starting anyways")
except:
print("Wrong Input Try Again)
答案 0 :(得分:2)
代码中没有引发错误,因此永远不会调用except
。如果要引发自己的异常,请使用raise
关键字。此处的详细信息:https://docs.python.org/2/tutorial/errors.html#raising-exceptions
答案 1 :(得分:1)
在try块中,您没有引发错误,因此没有任何问题。加薪应该可以解决问题。
userInput = input("Are both players ready to start? (y/n): ")
try:
if userInput == "y":
print("Here we go! ")
print()
elif userInput == "n":
print("Too bad we're starting anyways")
else:
raise ValueError("What's up with that?")
except:
print("Wrong Input Try Again")
如@ ctrl-alt-delor所建议,您也可以跳过try/except
块,而仅使用if/else
块。此代码段应执行以下操作:
if userInput == "y":
print("Here we go! ")
print()
elif userInput == "n":
print("Too bad we're starting anyways")
else:
print("Wrong Input Try Again")