I am trying to understand scopes in Python and am confused in the examples below (I am using Python 3.12.2) -
1.
a = 10
def myfunc():
a = 2
print(a)
print(a)
myfunc()
This gives the output -
10
2
a = 10
def myfunc():
print(a)
print(a)
myfunc()
This gives the output -
10
10
- However, when I do this -
a = 10
def myfunc():
print(a)
a = 2
print(a)
myfunc()
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
I am not sure how this is different from code example 1. Why is my output not-
10
10