0

I'm trying to access the counter variable in my function, why doesn't it work and how do I resolve it?

Relevant code:

sum = 0
counter = 0

def newFibo(a, b) :
    if(counter > 4000000) :
        return

    c = a + b

    sum += c
    counter +=1
    newFibo(b,c)

newFibo(1,2)
print(sum)

error: "local variable 'counter' referenced before assignment"

Arcthor
  • 53
  • 4
  • 8
  • Simple solution is to add a `global counter, sum` at the start of your function. The better solution is to change your function so it does not depend on *and modify* a global variable. – poke Sep 04 '15 at 21:00
  • Psst - I can sense this is for that one Project Euler question. As a quick hint: *every third* Fibonacci number is even - do you see why? Can you prove it? – Karl Knechtel Sep 09 '22 at 14:41

2 Answers2

1

In Python, if you want to modify a global variable inside a function, you have to declare it as global inside the function:

 def newFibo(a, b) :
    global counter, sum
    ..............

Note that you don't need it if the variable is only read inside the function but not modified.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
0

You need to use the keyword global to tell python that a variable is outside the current function.

So, basically, add global sum, counter right after def newFibo(a, b):.

spalac24
  • 1,076
  • 1
  • 7
  • 16