内联代码停止

2024-04-25 03:35:04 发布

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

我有一个恼人的代码,我想有一些事情发生。。。你知道吗

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或STOP作为答案时,才能停止本来无限的循环。你知道吗


Tags: answerinputiftimedefwhatelseint
2条回答

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

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

此外,由于在Python中非空字符串的计算结果是True,因此if语句将始终传递,因为"stop"的计算结果始终是True。你知道吗

要解决此问题,请使用^{}

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

^{}*:

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

*注意:正如@gnibbler在下面评论的那样,如果您使用的是python3.x,那么应该使用^{}而不是str.lower。它更兼容unicode。你知道吗

在python中是oroperator 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"]:

相关问题 更多 >