[英]Python: variable bindings in recursive functions
我使用類似於以下的函數在Python中遇到了一些奇怪的事情:
def foo(x):
if int(x)!=4:
x = raw_input("Wrong guess, please enter new value: " )
foo(x)
else:
print "Good Job! %s was right"%x
return x
value = foo(x=raw_input("Guess a Number between 1 and 10: "))
print value
如果我輸入,例如:“1”然后“2”然后“3”然后“4”,我打印出以下內容:
Good Job! 4 was right
2
這很令人困惑,因為看起來該函數似乎成功識別了正確的答案,但在這樣做之后,它返回的值是給定的第二個響應,而不是最近的響應。
任何人都可以解釋這個遞歸函數中綁定“x”的情況嗎?
讓我們來看看!
value = foo(raw_input())
# foo is the same as in the question, I won't repeat it here
print value
在你的foo中,你得到這個:
# foo(1) calls foo(2) and sets x to 2
# foo(2) calls foo(3) and sets x to 3
# foo(3) calls foo(4) and sets x to 4
# foo(4) does:
print "Good Job! 4 was right"
return 4 # to foo(3)
# foo(3) does:
return 4 # to foo(2)
# foo(2) does:
return 3 # to foo(1)
# foo(1) does:
return 2 # to main
由於main(從最外面的遞歸)的返回值是2
,這就是剩下的value
。
要解決這個問題,你可以讓它迭代:
def iter_foo(x):
while int(x) != 4:
x = raw_input("Wrong guess. Try again! ")
print "Good Job! %s was right" % x
return x
或者使EACH遞歸返回新函數的結果
def recurse_foo(x):
if int(x) != 4:
return foo(raw_input("Wrong guess. Try again! "))
else:
print "Good Job! %s was right!" % x
return x
所以這主要是因為你錯過了return
def foo(x):
if int(x)!=4:
x = raw_input("Wrong guess, please enter new value: " )
foo(x) # <-- need return
else:
print "Good Job! %s was right"%x
return x
value = foo(x=raw_input("Guess a Number between 1 and 10: "))
print value
發生的事情是調用foo(1)
,它不等於4,將x
賦值為2,這是x
被賦值的最后一個值,所以
foo(x)
返回一個值,但它沒有分配給任何東西或從遞歸調用返回。 x
接收為2,所以這就是初始foo(1)
返回 所以要么
x = foo(x)
要么
return foo(x)
在線上我突出顯示
請嘗試以下代碼:
def foo(x):
if int(x)!=4:
x = raw_input("Wrong guess, please enter new value: " )
return foo(x)
else:
print "Good Job! %s was right"%x
return x
value = foo(x=raw_input("Guess a Number between 1 and 10: "))
print value
你可以認為每次調用函數foo,都會創建一個新的變量x。 因此,遞歸調用產生一系列變量x1,x2,x3等。因此,當函數調用返回時,您的局部變量x不變。 這就是為什么你仍然得到2而不是最后一次遞歸調用的賦值(4)。 如果要更改傳遞給函數的變量,則需要通過引用(或對象)而不是值傳遞它。 [有關詳細信息,請參閱此文章: http : //uvesway.wordpress.com/2013/02/18/passing-arguments-to-a-function-by-value-by-reference-by-object/]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.