为什么我的python循环不断触及我的异常子句?

时间:2016-01-19 20:52:34

标签: python

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子句。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您需要获取代码才能再次询问输入...试试这个:

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\") ")

编辑:

  

最后一个优点是什么? - 贾斯珀

什么也没有!谢谢你的帮助!

答案 1 :(得分:1)

你还有一个冗余的elif / else语句。

classname = ""
while classname == "":
    classpick = input("Enter class name (\"A,B,C\") ")
    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  This and the else below it are redundant.
        else:
            raise ValueError
    except ValueError:
        print("Invalid value. Please enter a letter A,B or C.")

更清洁的解决方案可能是:

classname = ""

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