gpt4 book ai didi

Python:递归函数中的变量绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:53 24 4
gpt4 key购买 nike

我在 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”的绑定(bind)是怎么回事?

最佳答案

让我们看看!

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

或者让每个递归返回新函数的结果

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

关于Python:递归函数中的变量绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com