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?
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
vto 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
globalif you want to use the global variable and change it.However, passing the variable in as a parameter is strongly recommended.