0

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
Aravinth
  • 254
  • 3
  • 14
  • 2
    You do realize that `a` inside the function is local variable, right? It is not the `a` from global scope, because you do assignment in the body of the function. Depending on whether the condition is True `a` may be defined or not when you try to print it. – buran Dec 11 '21 at 10:04
  • 2
    The simple rule is: if you assign to `a` anywhere in a function (your `a = 5`), Python considers it local in this function. It will never, in this case, try to use a global variable with the same name if it happens not to be defined at some point. – Thierry Lathuille Dec 11 '21 at 10:05
  • 1
    Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) That said, note that using `global` is considered bad practice and better make your function take arguments and return values. – buran Dec 11 '21 at 10:06
  • @buran. Understood, Unless the same named variable is assigned/modified in a function it is global, Else its local. – Aravinth Dec 11 '21 at 10:23
  • Also, my previous understanding was, local scope is the minimal code chunk limit, But it is actually the the entire function itself seems - Right? – Aravinth Dec 11 '21 at 10:24
  • Not entirely true, e.g. there may be nested functions. There is so called _LEGB rule - **L**ocal, **E**nclosing, **G**lobal, **B**uilt-n"_ Check https://docs.python.org/3/reference/executionmodel.html#naming-and-binding and https://stackoverflow.com/q/291978/4046632 – buran Dec 11 '21 at 10:29

1 Answers1

0

you declare a=10 outside the function scope, and then here:

print(f'Outside if a is: {a}')

you use a within the function, but only when the randomly generated number is 0.

For the code to work, you need to add this to the function

def f():
    global a
    if(random.randint(0,1) == 1):
    # and so on
    
Valentino
  • 465
  • 6
  • 17