内联代码停止

时间:2013-11-29 20:39:02

标签: python loops

我有一些恼人的代码,我想要发生一些事情......

import time
global END
END = 0
def bacteria():
b = int(input("Bacteria number? "))
l = int(input("Limit? "))
i = (float(input("Increase by what % each time? ")))/100+1
h = 0
d = 0
w = 0
while b < l:
    b = b*i
    h = h+1
else:
    while h > 24:
        h = h-24
        d = d+1
    else:
        while d > 7:
            d = d-7
            w = w+1
print("The bacteria took " + str(w) + " weeks, " + str(d) + " days and " + str(h) + " hours.")
def runscript():
    ANSWER = 0
    ANSWER = input("Run what Program? ")
    if ANSWER == "bacteria":
        print(bacteria())
        ANSWER = 0
    if ANSWER == "jimmy":
        print(jimmy())
        ANSWER = 0
    if ANSWER == "STOP" or "stop":
        quit()
while True:
    print(runscript())

所以,在行“if ANSWER ==”STOP“或”stop“之后:”我希望脚本结束;但只有当我进入STOP或停止作为答案时,才能停止无限循环。

2 个答案:

答案 0 :(得分:2)

现在,您的代码被解释为:

if (ANSWER == "STOP") or ("stop"):

此外,由于非空字符串在Python中评估为True,因此{em>总是传递此if语句,因为"stop"将始终评估为True

要解决此问题,请使用in

if ANSWER in ("STOP", "stop"):

str.lower *:

if ANSWER.lower() == "stop":

*注意:正如@gnibbler在下面评论过的,如果您使用的是Python 3.x,则应使用str.casefold而不是str.lower。它更兼容unicode。

答案 1 :(得分:0)

在python中or operator returns true if any of the two operands are non zero

在这种情况下,添加括号有助于明确说明您当前的逻辑:

if((ANSWER == "STOP") or ("stop")):

在python中if("stop")将始终返回True。因为如果这样,整个条件始终为真,quite()将始终执行。

为了解决这个问题,您可以将逻辑更改为:

if(ANSWER == "STOP") or (ANSWER == "stop"):

if ANSWER in ["STOP","stop"]: