-1

In this below code, why the variable 'a' is not defined if I call the function fun() but works if I use the if "True" condition and disable the function and its call.


print ("Hello world! ")
def fun():
#if True:
    a = 20
    print ("Inside this function")
    print ("a is ", a)
print ("This is outside ")

fun()

print ("new val of a is ", a)

helloWorld.py", line 13, in print ("new val of a is ", a) NameError: name 'a' is not defined

girishlc
  • 9
  • 3

2 Answers2

1

The variable 'a' is declared and assigned within the function 'fun()' and the last print statement is executed outside the function. So, python is unable to get the value of the variable since 'a' is still undefined. There are many ways to fix this. You can return the variable and then print its value. Look at the below snippet:

print ("Hello world! ")
def fun():
    # if True:
    a = 20
    print ("Inside this function")
    print ("a is ", a)
    return a
print ("This is outside ")

a = fun()

print ("new val of a is ", a)
Harshil
  • 11
  • 2
0

It has to do with the scope of the variable a that you have defined. Having it inside the function makes its scoped to that function and not available to the outside code. With if, it is essentially a global variable.

See more information here https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime

Bishal
  • 807
  • 1
  • 5
  • 20