0

I am new to Python. I declared a variable named 'total' outside the function and then I called it inside my function called 'my_function'. But it is giving me an error because my variable 'total' is not global. Why is that? I thought variables declared outside were already considered global.

total = 1

def my_function(list):
    for i in list:
        total = total + 1
        print (total)

my_function([1,2,3])

This is the error I am getting

hershey10
  • 77
  • 4
  • 3
    Since you're assigning to `total` in your function, Python considers it a local variable. But since you're also using `total` to compute the new value, Python correctly determines that it will not have a value at that point and you get this error. In most cases where you think you need a global variable, there's a better solution - but if you must use it here, add the line `global total` to the beginning of the function. – Grismar Feb 13 '22 at 22:42
  • does https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs-closure answer your question? – JL Peyret Feb 13 '22 at 22:42

1 Answers1

2

You need to use the global keyword in your function

total = 1

def my_function(list):
    global total
    for i in list:
        total = total + 1
        print(total)

my_function([1, 2, 3])

Output:

2
3
4
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29