如果其他功能无法正常工作

时间:2019-09-28 09:47:08

标签: python python-3.x if-statement exit

当我对输入说“ n”或“否”时,如果工作正常,但当我对输入说“ y”或“是”时,它的作用与对“否”相同。程序中的所有其他内容都可以完美运行。我绝对不知道为什么会这样。

def restart():
    replay = input("Do you want to restart? (Y/N): ")
    if replay.lower() == "n" or "no":
        print("exiting")
        sys.exit()
    if replay.lower() == "y" or "yes":
        calc()
    else:
        print("Unknown Command")
        restart()
restart()

2 个答案:

答案 0 :(得分:2)

if语句中的条件并未评估您的想法。当您使用像or那样的逻辑运算符时,它将首先对or之前的部分求值,然后对or之后的部分求值,如果其中一个为真,则整个语句为true。

所以不是

if replay.lower() == "n" or "no": #always runs because just "no" evaluates as being true

使用

if replay.lower() == "n" or replay.lower == "no":

并对您的if语句进行类似的更改,以测试是。

答案 1 :(得分:0)

替换此:

    if replay.lower() == "n" or "no":
        print("exiting")
        sys.exit()
    if replay.lower() == "y" or "yes":
        calc()

与此:

    if replay.lower() == "n" or replay.lower() == "no":
        print("exiting")
        sys.exit()
    if replay.lower() == "y" or replay.lower() == "yes":
        calc()