gpt4 book ai didi

python - 为什么我的 python 循环不断地遇到异常子句?

转载 作者:行者123 更新时间:2023-11-30 23:01:35 24 4
gpt4 key购买 nike

classname = ""
classpick = input("Enter class name (\"A,B,C\") ")
while classname == "":
try:
if classpick.upper() == "A":
classname = "classA.txt"
elif classpick.upper() == "B":
classname = "classB.txt"
elif classpick.upper() == "C":
classname = "classC.txt"
elif classpick.upper() not in ["A","B","C"]:
raise ValueError
else:
raise ValueError
except ValueError:
print("Invalid value. Please enter a letter A,B or C.")

这段代码对吗?由于某种原因,如果输入了无效的输入,代码将继续循环 except 子句。有什么想法吗?

最佳答案

您需要获取代码才能再次请求输入...尝试以下操作:

classname = ""
classpick = input("Enter class name (\"A,B,C\") ")
while classname == "":
try:
if classpick.upper() == "A":
classname = "classA.txt"
elif classpick.upper() == "B":
classname = "classB.txt"
elif classpick.upper() == "C":
classname = "classC.txt"
elif classpick.upper() not in ["A","B","C"]:
raise ValueError
except ValueError:
print("Invalid value. Please enter a letter A,B or C.")
classpick = input("Enter class name (\"A,B,C\") ")

编辑:

What is the last elif good for? – Jasper

没什么!感谢您的帮助!

关于python - 为什么我的 python 循环不断地遇到异常子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34886727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com