Course Outline (Part 25)

A variable is only available from inside the region it is created. This is called scope.


1. Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

def myfunc():
    x = 300
    print(x)

myfunc()
# print(x) # Error! x is not defined outside

Function Inside Function: The local variable can be accessed from a function within the function:

def myfunc():
    x = 300
    def myinnerfunc():
        print(x)
    myinnerfunc()

myfunc()

2. Global Scope

A variable created in the main body of the Python code is a global variable and belongs to the global scope.

Global variables are available from within any scope, global and local.

x = 300

def myfunc():
    print(x) # Accessing global variable inside function

myfunc()
print(x)

Naming Variables: If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside) and one available in the local scope (inside).

x = 300

def myfunc():
    x = 200 # Creates a local variable x
    print(x) # Prints 200

myfunc()
print(x) # Prints 300 (Global variable remains unchanged)

3. The global Keyword

If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.

def myfunc():
    global x
    x = 300

myfunc()
print(x) # Prints 300, even though x was created inside a function

Also, use the global keyword if you want to make a change to a global variable inside a function.

x = 300

def myfunc():
    global x
    x = 200

myfunc()
print(x) # Prints 200

4. The nonlocal Keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function, but also not to the global scope. It belongs to the enclosing (outer) function.

def myfunc1():
    x = "Jane"
    def myfunc2():
        nonlocal x
        x = "hello"
    myfunc2()
    return x

print(myfunc1()) # Returns "hello"

5. The LEGB Rule

Scope resolution in Python is based on the LEGB rule. When you access a variable, Python looks for it in this order:

  1. Local: Defined within a function.
  2. Enclosing: Defined in an enclosing (nested) function.
  3. Global: Defined at the uppermost level of a module.
  4. Built-in: Reserved names in Python’s built-in module (like print, len).

If the variable is not found in any of these scopes, Python throws a NameError.

Discussion

Loading comments...