我希望用户能够退出这个程序在任何时候输入“退出”。在
有没有一种方法可以用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!")
我认为写一个函数和使用
sys.exit
对于OP所问的都是过火了,这取决于你是想跳出循环还是完全退出程序特别是关于您的问题,您可以在
input()
之后break
,它将退出循环而不执行其余的运行。(顺便说一句,您不需要将输入转换为字符串,默认情况下输入是字符串)创建一个函数,每次接受输入时使用它,调用“exit()”离开
例如
你可以使用
立即停止执行进一步的程序语句,所以
^{pr2}$应该行得通。在
文档:https://docs.python.org/3.5/library/sys.html#sys.exit
相关问题 更多 >
编程相关推荐