我有一段烦人的代码,我想让它发生一些变化……
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作为答案时,才能停止否则无限循环。
发布于 2013-11-30 04:40:11
现在,你的代码是这样解释的:
if (ANSWER == "STOP") or ("stop"):此外,因为在Python语言中非空字符串的计算结果为True,所以此if语句将始终通过,因为"stop"的计算结果始终为True。
要解决此问题,请使用in
if ANSWER in ("STOP", "stop"):或str.lower*
if ANSWER.lower() == "stop":*注意:正如@gnibbler下面评论的那样,如果你使用的是Python3.x,你应该使用str.casefold而不是str.lower。它与unicode更兼容。
发布于 2013-11-30 04:51:17
在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"]:https://stackoverflow.com/questions/20293054
复制相似问题