Home > Backend Development > Python Tutorial > How Does Python's `nonlocal` Keyword Differ from `global` in Scope Management?

How Does Python's `nonlocal` Keyword Differ from `global` in Scope Management?

Mary-Kate Olsen
Release: 2024-12-11 19:05:11
Original
889 people have browsed it

How Does Python's `nonlocal` Keyword Differ from `global` in Scope Management?

Understanding the Role of "nonlocal" in Python 3

In Python 3, "nonlocal" plays a crucial role in accessing variables defined in an enclosing scope, but outside the current one. Unlike "global," which references variables in the global scope, "nonlocal" allows you to interact with variables in a parent function's scope.

Consider this example without using "nonlocal":

x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)
Copy after login

Output:

inner: 2
outer: 1
global: 0
Copy after login

As we can see, the variable "x" in the inner function is assigned a local value of 2, while the variable "x" in the outer function remains at 1. The global variable "x" retains its initial value of 0.

Now, let's rewrite this code using "nonlocal":

x = 0
def outer():
    x = 1
    def inner():
        nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)
Copy after login

Output:

inner: 2
outer: 2
global: 0
Copy after login

With "nonlocal," the variable "x" in the inner function is now bound to the variable "x" in the outer function. As a result, when "x" is modified within the inner function, it also affects its value in the outer function. The global variable "x" remains unchanged.

In contrast, "global" would bind the variable "x" in the inner function to the one in the global scope:

x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)
        
    inner()
    print("outer:", x)

outer()
print("global:", x)
Copy after login

Output:

inner: 2
outer: 1
global: 2
Copy after login

Understanding the subtle differences between "nonlocal" and "global" is crucial for effectively managing variables in Python code.

The above is the detailed content of How Does Python's `nonlocal` Keyword Differ from `global` in Scope Management?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template