0

I hope the title is clear enough, I don't know how to phrase this.

This code segment work as expected (7 lines with 1 in the output)

v=1
def test():
    print v
    for i in range (5):
        print v
v=1
test() 
print v

However, when I try to add max command to the function

v=1
def test():
    print v
    for i in range (5):
        v = max(i,v)
        print v
v=1
test() 
print v

I get an error:

UnboundLocalError: local variable 'v' referenced before assignment

This has always puzzled me. Why do I need to send v to the function at this case?

Yotam
  • 10,295
  • 30
  • 88
  • 128
  • possible duplicate of [use of "global" keyword in python](http://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – ecatmur Feb 11 '13 at 08:49

1 Answers1

2

Firstly, you should always pass a variable into a function if the function uses it.

The problem you have is that you are trying to assign a local variable v to what Python thinks is that same variable, not the global one. The first function works because you aren't assigning to anything.

Alternatively you can use global if you want to use the global variable and change it.

def test():
    global v
    # rest of code

However, passing the variable in as a parameter is strongly recommended.

Volatility
  • 31,232
  • 10
  • 80
  • 89