如果输入==“ quit”且有许多if语句,如何结束程序?

时间:2018-11-12 22:34:38

标签: python loops if-statement break

我希望用户可以通过键入“退出”随时退出该程序。

是否可以使用break语句的一个实例来执行此操作,还是需要在代码中的每个“ if y ==”语句中添加一个break?

fruits = []
notfruits = []
print(fruits)
print(notfruits)

while len(fruits) < 3 or len(notfruits) < 3:   # replaced `and` with `or`
    print("Please enter fruits or notfruits:") #
    y = str(input(": "))                       # moved the input here
    if y == "fruits":
        while len(fruits) < 3:
            x = str(input(": "))
            x = x.strip()
            if x in notfruits:
                print(x + " is not a fruit!")
            elif x in fruits:
                print(x + " is already in the list!")
            else:
                fruits.append(x)
                print(fruits)
    elif y == "notfruits":
         while len(notfruits) < 3:
            x = str(input(": "))
            x = x.strip()
            if x in fruits:
                print(x + " is a fruit!")
            elif x in notfruits:
                print(x + " is already in the list!")
            else:
                notfruits.append(x)
                print(notfruits)
    elif y == "clearfruits":
        del fruits[:]
    elif y == "clearnotfruits":
        del notfruits[:]
    elif y == "quit":
        break
    else:
        print("Not a valid option!")

3 个答案:

答案 0 :(得分:1)

您可以使用

import sys
sys.exit(0)

立即停止执行其他程序语句,例如

elif y == "quit":
    import sys
    sys.exit(0)

应该工作。

文档:https://docs.python.org/3.5/library/sys.html#sys.exit

答案 1 :(得分:1)

创建一个函数,每次接受输入时都使用它,调用“ exit()”退出

例如

import sys

def check_quit(inp):
    if inp == 'quit':
        sys.exit(0)

答案 2 :(得分:0)

我认为编写函数和使用sys.exit对于OP的要求都是过大的,取决于您是要打破循环还是完全退出程序

具体针对您的问题,您可以在break之后input()进行操作,它将退出循环而无需执行其余的运行。 (顺便说一句,您不需要将输入强制转换为字符串,默认情况下,输入是字符串)

y = input(": ")
if y.lower() == "quit":
    break    
if y == "fruits":