如何以多个if语句结束程序,如果输入等于“quit”?

2024-09-28 17:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户能够退出这个程序在任何时候输入“退出”。在

有没有一种方法可以用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!")

Tags: ortheininputlenifiselse
3条回答

我认为写一个函数和使用sys.exit对于OP所问的都是过火了,这取决于你是想跳出循环还是完全退出程序

特别是关于您的问题,您可以在input()之后break,它将退出循环而不执行其余的运行。(顺便说一句,您不需要将输入转换为字符串,默认情况下输入是字符串)

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

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

例如

import sys

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

你可以使用

import sys
sys.exit(0)

立即停止执行进一步的程序语句,所以

^{pr2}$

应该行得通。在

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

相关问题 更多 >