Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在线代码停止_Python_Loops - Fatal编程技术网

Python 在线代码停止

Python 在线代码停止,python,loops,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 els

我有一个恼人的代码,我想有一些事情发生在

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())
导入时间
全球终端
结束=0
定义细菌():
b=int(输入(“细菌数量?”)
l=int(输入(“限制”)
i=(浮动(输入(“每次增加多少%))/100+1
h=0
d=0
w=0
而b24时:
h=h-24
d=d+1
其他:
当d>7时:
d=d-7
w=w+1
打印(“细菌需要”+str(w)+“周”、+str(d)+“天”、“+str(h)+”小时。”)
def runscript():
答案=0
回答=输入(“运行什么程序?”)
如果答案==“细菌”:
打印(细菌())
答案=0
如果答案==“吉米”:
打印(jimmy())
答案=0
如果答案==“停止”或“停止”:
退出
尽管如此:
打印(runscript())

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

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

if (ANSWER == "STOP") or ("stop"):
此外,由于Python中非空字符串的计算结果为
True
,因此此if语句将始终通过,因为
“stop”
的计算结果将始终为
True

要解决此问题,请使用:

或*:



*注意:正如@gnibbler在下面评论的那样,如果您使用的是Python 3.x,那么应该使用而不是
str.lower
。它与unicode更加兼容。

在python中是

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

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

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

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


在Python3中,您可以使用
str.casefold
来获得更好的unicodecompatibility@gnibbler-说得好。让我提一下。
if((ANSWER == "STOP") or ("stop")):
if(ANSWER == "STOP") or (ANSWER == "stop"):
if ANSWER in ["STOP","stop"]: