2

1st case:

x = 5
def add(n):
    x += n
    return x

print(add(5))

local variable 'x' referenced before assignment

2nd case:

fi = [0,1,1,2,3,5,8,13,21,34]
def fibonacci(n):
    while len(fi) <= n:
        fi.append(fi[-1]+fi[-2])
    return fi[n]

print(fibonacci(10),fi)

55 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

both 'x' and 'fi' are outside the functions, why 'x' raise error but 'fi' not?

  • 1
    add `global x` inside the function and it will work too. – Mahrkeenerh Oct 07 '21 at 13:50
  • 2
    In the first case, you're writing to `x`, while in the second case you're only using the reference to `fi`. i.e. you never call something like `fi = whatever`. – CerebralFart Oct 07 '21 at 13:51
  • @CerebralFart: Can you explain *why* `fi.append` is OK but `fi = `... is not? That is, if `fi` can be found to invoke one of its methods, why can't it be assigned to? – Scott Hunter Oct 07 '21 at 13:53
  • @Mahrkeenerh: The question isn't how to make it work, but *why*, when something similar, works without the need for `global`. – Scott Hunter Oct 07 '21 at 13:54
  • 2
    Instead of calling a method `fi.append(blah)` try to compare apples to apples by doing `fi += [blah]`. Assignments make things local by default – Mad Physicist Oct 07 '21 at 13:54
  • 1
    The keyword in the error is `assignment`. `x` is being reassigned, `fi` isn’t. Global variables can only be reassigned if declared global. – Mark Tolonen Oct 07 '21 at 13:59

0 Answers0