[英]Problems with boolean statement and if statement in python
def test():
boo = True
enter = int(raw_input("Enter something: "))
if enter > 0:
boo = False
print "Did it work?!"
else:
print "Still working..."
while boo == True:
test()
test()
因此,这段代码似乎只有在首先尝试满足if语句的第一部分时才起作用。 也就是如果您输入-1,则1会继续遍历该函数。 我究竟做错了什么?
boo
是一个局部变量。 每次您递归调用test()
,该递归调用都会获得一个新的局部变量boo
,该变量独立于所有调用它的父函数。 因此,在函数开始时将其设置为True
。
您的通话如下所示:
test()
, boo = True
, enter
= 1,因此while boo == True
为true:
test()
, boo = True
, enter
= -1,因此while boo == True
为false时,返回 在此级别上, boo == True
仍然为true ,因此我们再次调用test()
。
test()
, boo = True
, enter
= -1,因此while boo == True
为false时,返回 等等。
您想返回 boo
:
def test():
boo = True
enter = int(raw_input("Enter something: "))
if enter > 0:
boo = False
print "Did it work?!"
else:
print "Still working..."
while boo:
boo = test()
return boo
现在,当test()
返回时, 将调用函数中的 boo
设置为False
。
注意== True
是多余的,只需在while boo
测试boo
本身。
使用递归进行用户输入确实不是一个好主意。 只需使用while
循环:
while True:
enter = int(raw_input("Enter something: "))
if enter < 0:
print "Did it work?!"
break
print "Still working..."
将可能无限的while
循环与递归函数结合在一起是非常危险的游戏。 当您到达随后的test()
调用时,即使它们正常工作并立即退出,您对test()
原始调用仍将永远循环。 boo
永远不会在原始函数调用中更改,只是因为它在以后的函数中已更改。
您的代码可以通过以下方式修复:
def test():
boo = True
enter = int(raw_input("Enter something: "))
if enter > 0:
boo = False
print "Did it work?!"
else:
print "Still working..."
if boo == True:
test()
但是这样会更好:
def test():
enter = int(raw_input("Enter something: "))
while enter <= 0:
print "Still working..."
enter = int(raw_input("Enter something: "))
print "Did it work?!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.