在python3中发生错误时询问输入

时间:2014-04-28 14:04:39

标签: python python-3.x error-handling

在这段代码中,我正在寻找输入:

mode = input("Generate S1(0) or S2(1)?\n")
if mode == "0":
    mode = "S1"
elif mode == "1":
    mode = "S2"
else:
    print("Mode not recogised!")

为了能够更好地处理错误(模式> 1),即如果遇到else条件,我希望代码再次询问输入。

知道我该怎么做或我正在寻找哪种功能?

2 个答案:

答案 0 :(得分:1)

mode = None
while not mode:
    answer = input("Generate S1(0) or S2(1)?\n")
    if answer == "0":
        mode = "S1"
    elif answer == "1":
        mode = "S2"
    else:
        print("Mode not recogised!")

答案 1 :(得分:0)

这有点棘手。但你可以这样做。

while 1:
    mode = input("Generate S1(0) or S2(1)?\n")
    if mode == "0":
        mode = "S1"
    elif mode == "1":
        mode = "S2"
    else:
        print("Mode not recogised!")
        continue
    break