Contents

Python Interactive Guide - Step 3 Functions (5) - Scope

Series - Python Interactive Guide
Info
  • This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
  • The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
  • You can run and experiment with every code example.
    Feel free to try things out - reloading the page will reset everything.

This is a continuation of “Step 3 Functions.”

In Python, the accessibility of variables, functions, and other identifiers is determined by where they are defined in your code. This accessible range is called a scope.

When an identifier appears in the code, Python searches for its definition in the following order, and uses the first match it finds.
This rule is called the LEGB rule, named after the initials of the four scopes it searches.

LEGB Rule
  • Local: The immediate scope within the current function
  • Enclosing: The scope of any containing functions (for nested functions)
  • Global: The scope of the current file
  • Built-in: The scope containing Python’s built-in objects, such as the print function, len function, and constants like True
Built-in Scope
Built-in functions and constants in Python (e.g., print, len, True)
Global Scope
Identifiers defined in the current file
Enclosing Scope
Identifiers such as local variables of the outer function
Local Scope
Identifiers such as variables defined within the current function
→ The search begins in this scope and extends outward to broader scopes

Variables and other identifiers defined within a function have a “local scope” that exists only within that function:

When a function is defined inside another function, the local scope of the outer function becomes the “enclosing scope” for the inner function.
Python checks the enclosing scope after checking the local scope.

Variables and other identifiers defined at the file level have a “global scope” and can be accessed from anywhere within that file.
Python checks the global scope after the local and enclosing scopes.

Python has a “built-in scope” containing built-in functions like len(), print(), min(),
and built-in constants such as True, False, and None.

This is the last scope Python checks when looking for an identifier.

📚Exercise

Try to predict the output of the following code before running it:

Example Answer

As we’ve seen, it’s possible to reference global variables from inside a function.
However, by default, you cannot modify the values of global variables inside functions.

By default, when you perform an assignment operation inside a function, you create and assign to a local variable:

You can use the global keyword to declare that a variable is an identifier from the global scope:

global declaration
global variable_name
  • By declaring a variable as global, you explicitly indicate that it’s a global variable and can modify its value
  • You can declare multiple variables at once by separating them with commas
📚Exercise

There are missing parts in the following code.
Modify the program by using the global keyword appropriately.

Example Answer
Style Guide: Minimize the Use of Global Variables

As programs become more complex, using global variables can cause unexpected problems.
Keep the following in mind:

  1. Avoid global variables when possible - Use function arguments and return values instead
  2. Use them as read-only - Only use them for configuration values and other data that doesn’t change
  3. Use descriptive names - Use names that clearly indicate the purpose of the variable

You can use the nonlocal keyword to declare that a variable is an identifier from the enclosing scope:

nonlocal declaration
nonlocal variable_name
  • By declaring a variable as nonlocal, you explicitly indicate that it’s a variable from the enclosing scope and can modify its value
  • You can declare multiple variables at once by separating them with commas

In this section, we learned about “scope” which indicates the accessible range of identifiers:

  1. LEGB Rule: The order of reference for identifiers (Local → Enclosing → Global → Built-in)
  2. global Declaration: How to modify global variables from inside functions using the global keyword
  3. nonlocal Declaration: How to modify variables of outer functions from inner functions using the nonlocal keyword

Understanding scope is very important when creating complex programs in Python.
By minimizing the use of global variables and utilizing function parameters and return values as much as possible, you can create more maintainable code.

Related Content