Skip to content
Advertisement

Referring to variables of a function outside the function

#!/usr/bin/python3
def func():
    a = 1
    print(a+12)

print(a)

The result is:

NameError: name ‘a’ is not defined

Is it possible to use a outside the function?

Advertisement

Answer

In python the scope is a function, or class body, or module; whenever you have the assignment statement foo = bar, it creates a new variable (name) in the scope where the assignment statement is located (by default).

A variable that is set in an outer scope is readable within an inner scope:

a = 5
def do_print():
    print(a)

do_print()

A variable that is set in an inner scope cannot be seen in outer scope. Notice that your code does not even ever set the variable as that line is not ever run.

def func():
    a = 1 # this line is not ever run, unless the function is called
    print(a + 12)

print(a)

To make something like you wanted, a variable set within a function, you can try this:

a = 0
print(a)

def func():
    global a # when we use a, we mean the variable
               # defined 4 lines above
    a = 1
    print(a + 12)

func() # call the function
print(a)
Advertisement