打印出斐波纳契系列 [英] Printing out the fibonacci series
问题描述
我想写一个简单的Python程序。它应该返回一个返回连续斐波纳契数字的闭包:
I am trying to write a simple Python program. It's supposed to return a a closure that returns successive fibonacci numbers:
def fibGen():
n_1 = 0
n_2 = 0
n = 1
def fib():
if n_1 ==0 and n_2 ==0:
n_1 = 1
return n
else:
n = n_1 + n_2
n_2 = n_1
n_1 = n
return n
return fib
f = fibGen()
for i in range(0,10):
print(f())
我在运行时遇到此错误:
UnboundLocalError:在赋值之前引用的局部变量'n_1'
I get this error at run time:
UnboundLocalError: local variable 'n_1' referenced before assignment
编辑:在我原来的帖子中,我没有在 fibGen
的定义中包含 n = 1
实际上是一个错字。我仍然会得到相同的错误。
In my original post, I had not included n = 1
in the definition of fibGen
but it was actually a typo. I would still get the same error anyway.
推荐答案
Python在编译时确定变量的范围,基于<行为。如果您指定一个名称,或者使用它作为 import
目标(以及其他几种方式),您将绑定范围中的名称。
Python determines the scope of variables at compile time, based on binding behaviour. If you assign to a name, or use it as an import
target (and a few other ways) you are binding the name in a scope.
您在 fib中绑定到
function;两者都被分配到。这使得 n_1
和 n_2
() fib()
中的两个名称 local ,Python甚至不会查看周围的范围。
You are binding to n_1
and n_2
in the fib()
function; both are being assigned to. This makes those two names local in fib()
, and Python won't even look at the surrounding scope.
您需要覆盖此行为,您可以使用 nonlocal
语句:
You'll need to override this behaviour, and you can do this by using the nonlocal
statement:
def fibGen():
n_1 = 0
n_2 = 0
def fib():
nonlocal n_1, n_2
if n_1 ==0 and n_2 ==0:
n_1 = 1
return n
else:
n = n_1 + n_2
n_2 = n_1
n_1 = n
return n
return fib
非本地
告诉编译器明确地,您不希望它查看绑定行为,而是将名称作为闭包。
nonlocal
tells the compiler explicitly that you don't want it to look at binding behaviour but instead treat the names as closures.
接下来,您使用<$ c在测试的
第一个分支中的$ c> n
,但是没有在 else
分支。您应该只传回 1
:
Next, you are using n
in the first branch of the if
test, but you haven't defined it anywhere outside of the else
branch. You should just return 1
there anyway:
def fibGen():
n_1 = 0
n_2 = 0
def fib():
nonlocal n_1, n_2
if n_1 ==0 and n_2 ==0:
n_1 = 1
return n_1
else:
n = n_1 + n_2
n_2 = n_1
n_1 = n
return n
return fib
最后但并非最不重要的是,你可以通过使用元组赋值来交换两个变量,不需要中介:
Last but not least, you can swap two variables by using tuple assignment, no intermediaries needed:
def fibGen():
n_1 = 0
n_2 = 0
def fib():
nonlocal n_1, n_2
if n_1 ==0 and n_2 ==0:
n_1 = 1
else:
n_1, n_2 = n_1 + n_2, n_1
return n_1
return fib
这篇关于打印出斐波纳契系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!