-2

The following script produces a "local variable 'var' referenced before assignment" error:

def func1():
    var = var + 1

var = 1

func1()

How would you suggest to correct the code? Why does this error occur when the variable is declared in the script before the function is called?

brr
  • 11
  • 1
  • Because var inside func1 is a different var than the one outside it. It's local to func1. The error is saying you can't do var = var + 1 because var doesn't have a value to add 1 to. Da boyz have given you a couple of alternatives below. – Tony Hopkinson May 11 '12 at 11:24

2 Answers2

4

You can use a global variable in other functions by declaring it as global in each function that modifies it:

>>> var = 2
>>> def func():
...     global var
...     var = var+1
...     return var
... 
>>> func()
3

After OP edited question: If you are moving the variable after you define the function you will need to pass it to the function as a parameter.

>>> def func(var):
...     var = var+1
...     return var
... 
>>> var = 2
>>> func(var)
3
garnertb
  • 9,454
  • 36
  • 38
0

Functions have their own scope, separate from the main program. So although you've defined var in your main program it's not known to func1() and func2(). To fix your error you'll need to pass through a parameter to both functions like, and then return the new value like so:

def func1(var):
    var = var + 1
    return var

var = 1

var = func1(var)
Wipqozn
  • 1,282
  • 2
  • 17
  • 30