我不知道为什么我的 try 和 except 无法正常工作。我希望它在用户输入字符串“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)
在 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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句