Python Variable Scope

Question Click to View Answer

What does the following code print?

x = 55
def hi():
    return x

print(hi())

55 is printed.

The variable x is defined in the global scope. Global variables are accessible anywhere in the program, including the local function scope.

What does the following code print?

def pointless():
    z = 77
    return z

print(pointless())

77 is printed.

The variable z is defined in a local scope for the pointless function. The variable z is accessible anywhere within the pointless function.

What does the following code print?

def chair():
    pp = 99
    return pp

chair()

print(pp)

This code raises a NameError exception with the following message: name 'pp' is not defined.

The pp variable is defined in the chair() function, so it has a local scope can can only be accessed in the chair() function. pp cannot be accessed outside of the chair() function.

What does the following code print?

ii = 50

def fan():
    ii = 100
    return ii

print(fan())

100 is printed.

The ii variable is initially defined in the global scope and then redefined in the local scope of the fan() function.

The local scope is used when there is a collision with a variable of the same name in the global scope.

What does the following code print?

qq = 3

def bike():
    qq = 7

bike()

print(qq)

3 is printed.

When a global variable is reassigned in the local scope of a function, the reassignment only holds within the local scope. The variable goes back to the global value when the code returns the global scope.

What does the following code print?

nn = 9

if True:
  nn = 16

print(nn)

16 is printed.

nn is initially assigned to 9 in the global scope. nn is then reassigned to 16 in the code block associated with an if statement. if statements don't convert the code to local scope like function definitions. if statements keep the existing scope.

What does the following code print?

cc = 2

if False:
    cc = 66

def helmet():
    if True:
        cc = 40

helmet()

print(cc)

2 is printed.

cc is initially assigned to 2. The if False statement evaluates to False, so the cc = 66 reassignment never takes place. The reassignment inside the helmet() function does take place, but in the local scope, not the global scope. When the cc variable is accessed in the global scope, the value remains unchanged at 2.