Based on the different conditions used in a if conditional check, the variable's global & local scopes are affected.
I tried running the below code in multiple online IDEs as well, Almost all throws the error message in most runs & not all runs
Can someone clarify the reason for the behaviour?
#Code Sample 1:
Within the function definition, Outside of if condition the variable holds no value !!!, And throws error but not in all runs
import random
a = 10
def f():
if(random.randint(0,1) == 1):
#if(True):
a = 5
print(f'Under if a is: {a}')
print(f'Outside if a is: {a}')
print(f'Before & Outside f() a is: {a}')
f()
print(f'After & Outside f() a is: {a}')
And the output is:
Before & Outside f() a is: 10
Traceback (most recent call last):
File "main.py", line 13, in <module>
f()
File "main.py", line 10, in f
print(f'Outside if a is: {a}')
UnboundLocalError: local variable 'a' referenced before assignment
#Code Sample 2:
Within the function definition, Outside of if condition the variable holds the local value instead of the globally assigned value
import random
a = 10
def f():
#if(random.randint(0,1) == 1):
if(True):
a = 5
print(f'Under if a is: {a}')
print(f'Outside if a is: {a}')
print(f'Before & Outside f() a is: {a}')
f()
print(f'After & Outside f() a is: {a}')
And the output is:
Before & Outside f() a is: 10
Under if a is: 5
Outside if a is: 5
After & Outside f() a is: 10