Python - ELIF 语句不会继续 WHILE 循环



在课堂上,我们从一个基本程序开始,并将继续构建它。我卡住了,不确定为什么当程序到达 ELIF 语句时,它不会像第一个 IF 语句那样返回到 WHILE 循环的开头

print("Great Scott! Marty we need to go back to the future!")
print("Marty, lets do a checklist!")
engine = None
circuit = None
while (engine !=1 and circuit != 1):
    engine = int(input("Engine on or off? Enter 1 for ON or 0 for OFFn"))
    circuit = int(input("Circuit on or off? Enter 1 for ON or 0 for OFFn"))
    if (engine == 0 and circuit == 0):
         print("Marty! we have to turn everything on before we can time travel!")
         print("Lets check again!")
    elif (engine == 1 and circuit == 0):
        print("Lets turn on the time cicruit")
        print("Lets check again!")
    elif (engine == 0 and circuit == 1):
        print("Turn on the engine!")
        print("Lets check again!")
    else:
        print("Great! lets start driving")
        speed = 0
        while speed < 88:
            speed = int(input("Whats our current speed?n"))
            if speed < 88:
                print("We need to go faster!")
            else:
                print("Flux Capacitor Fully Charged")
                print("Marty, where we're going, we dont need roads!")

实际上只是更改to or

while (engine !=1 or circuit != 1):

您应该重新启动变量engine并将circuit为 0。循环要求变量不同于 1 才能继续运行。

立即尝试:

print("Great Scott! Marty we need to go back to the future!")
print("Marty, lets do a checklist!")
engine = None
circuit = None
    while (engine !=1 and circuit != 1):
        engine = int(input("Engine on or off? Enter 1 for ON or 0 for OFFn"))
        circuit = int(input("Circuit on or off? Enter 1 for ON or 0 for OFFn"))
        if (engine == 0 and circuit == 0):
             print("Marty! we have to turn everything on before we can time travel!")
             print("Lets check again!")
        elif (engine == 1 and circuit == 0):
            print("Lets turn on the time cicruit")
            print("Lets check again!")
            engine = 0
            circuit = 0
        elif (engine == 0 and circuit == 1):
            print("Turn on the engine!")
            print("Lets check again!")
            engine = 0
            circuit = 0
        else:
            print("Great! lets start driving")
            speed = 0
            while speed < 88:
                speed = int(input("Whats our current speed?n"))
                if speed < 88:
                    print("We need to go faster!")
                else:
                    print("Flux Capacitor Fully Charged")
                    print("Marty, where we're going, we dont need roads!")
while (engine !=1 and circuit != 1):

上述语句意味着发动机和电路都不应等于 1。如果其中任何一个为 1,则条件计算结果为 False 和循环结束。

现在,在您的elif情况下,发动机或回路为 1,因此循环条件的计算结果为 False 和循环停止。

while (engine !=1 and circuit != 1):

应改为:

while (engine !=1 or circuit != 1):

在第一种情况下(带有 and 的那个)只有在引擎和电路都不等于 1 时才将继续循环。(一些伪代码:do something while condition 1 is true AND while condition 2 is true而使用or它将是do something while condition 1 is true OR if condition 2 is true)。

最新更新