python - Printing out the fibonacci series -
i trying write simple python program. it's supposed homecoming a closure returns successive fibonacci numbers:
def fibgen(): n_1 = 0 n_2 = 0 n = 1 def fib(): if n_1 ==0 , n_2 ==0: n_1 = 1 homecoming n else: n = n_1 + n_2 n_2 = n_1 n_1 = n homecoming n homecoming fib f = fibgen() in range(0,10): print(f()) i error @ run time: unboundlocalerror: local variable 'n_1' referenced before assignment
edit: in original post, had not included n = 1 in definition of fibgen typo. still same error anyway.
python determines scope of variables @ compile time, based on binding behaviour. if assign name, or utilize import target (and few other ways) binding name in scope.
you binding n_1 , n_2 in fib() function; both beingness assigned to. makes 2 names local in fib(), , python won't @ surrounding scope.
you'll need override behaviour, , can using nonlocal statement:
def fibgen(): n_1 = 0 n_2 = 0 def fib(): nonlocal n_1, n_2 if n_1 ==0 , n_2 ==0: n_1 = 1 homecoming n else: n = n_1 + n_2 n_2 = n_1 n_1 = n homecoming n homecoming fib nonlocal tells compiler explicitly don't want @ binding behaviour instead treat names closures.
next, using n in first branch of if test, haven't defined anywhere outside of else branch. should homecoming 1 there anyway:
def fibgen(): n_1 = 0 n_2 = 0 def fib(): nonlocal n_1, n_2 if n_1 ==0 , n_2 ==0: n_1 = 1 homecoming n_1 else: n = n_1 + n_2 n_2 = n_1 n_1 = n homecoming n homecoming fib last not least, can swap 2 variables 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 , n_2 ==0: n_1 = 1 else: n_1, n_2 = n_1 + n_2, n_1 homecoming n_1 homecoming fib python python-3.x closures fibonacci
No comments:
Post a Comment