[英]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.