Table of Contents
Local vs Global Scope
Scope in nested functions: the use of nonlocal
Use global to modify global variables
A few common precautions
Home Backend Development Python Tutorial Python variable scope in functions

Python variable scope in functions

Jul 12, 2025 am 02:49 AM
python variable scope

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, the nonlocal keyword is required; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise an UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

Python variable scope in functions

In Python, variables defined inside a function are local variables by default, while variables defined outside a function are global variables. Understanding the scope of variables is very important for writing good functions and avoiding bugs.

Python variable scope in functions

Local vs Global Scope

When you define a variable inside a function, like this:

 def my_func():
    x = 10

Here x is a local variable and can only be accessed inside my_func() . Once the function execution is finished, this variable will be destroyed.

Python variable scope in functions

And if you define a variable outside the function, it is a global variable that can be read anywhere (but cannot be modified directly unless the global keyword is used).

For example:

Python variable scope in functions
 y = 5

def show_y():
    print(y) # can print 5 normally

show_y()

This means that the function can access global variables, but if you want to modify it in the function, you have to declare it with global y .


Scope in nested functions: the use of nonlocal

Sometimes you will define another function in the function, and this time it involves nested scope. for example:

 def outer():
    a = "outer"

    def inner():
        a = "inner"
        print(a)

    inner()
    print(a)

The above code will output:

 inner
outer

Because a in inner() is its own local variable and will not affect a in outer() .

But if you want to modify the variables of the outer function in inner() , you need to use nonlocal :

 def outer():
    a = "outer"

    def inner():
        nonlocal a
        a = "modified"

    inner()
    print(a) # output modified

Remember: nonlocal can only be used in nested functions, and it is bound to the outer layer variable closest to it.


Use global to modify global variables

If you want to modify global variables in a function, you must add global , otherwise Python will think you are defining a new local variable.

Look at this example:

 count = 0

def increment():
    Global count
    count = 1

Increment()
print(count) # output 1

If global count is not added, an error will be reported during runtime: UnboundLocalError: local variable 'count' referenced before assignment .

So as long as you want to change the global variable, don't forget to declare it global .


A few common precautions

  • Functions can read global variables, but cannot be modified directly unless global
  • Local variables are only valid in the function that defines it
  • In nested functions, nonlocal must be used to modify variables of outer functions.
  • Variables with the same name do not affect each other in different scopes (for example, there is an x ​​globally, and there is also an x ​​in the function, and they are not the same)

Basically that's it. The scope does not seem complicated, but it is easy to make mistakes if you are not careful, especially when multiple layers of nesting or multiple functions operate the same variables.

The above is the detailed content of Python variable scope in functions. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python shutil rmtree example python shutil rmtree example Aug 01, 2025 am 05:47 AM

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? Jul 30, 2025 pm 09:12 PM

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

python psycopg2 connection pool example python psycopg2 connection pool example Jul 28, 2025 am 03:01 AM

Use psycopg2.pool.SimpleConnectionPool to effectively manage database connections and avoid the performance overhead caused by frequent connection creation and destruction. 1. When creating a connection pool, specify the minimum and maximum number of connections and database connection parameters to ensure that the connection pool is initialized successfully; 2. Get the connection through getconn(), and use putconn() to return the connection to the pool after executing the database operation. Constantly call conn.close() is prohibited; 3. SimpleConnectionPool is thread-safe and is suitable for multi-threaded environments; 4. It is recommended to implement a context manager in combination with context manager to ensure that the connection can be returned correctly when exceptions are noted;

python iter and next example python iter and next example Jul 29, 2025 am 02:20 AM

iter() is used to obtain the iterator object, and next() is used to obtain the next element; 1. Use iterator() to convert iterable objects such as lists into iterators; 2. Call next() to obtain elements one by one, and trigger StopIteration exception when the elements are exhausted; 3. Use next(iterator, default) to avoid exceptions; 4. Custom iterators need to implement the __iter__() and __next__() methods to control iteration logic; using default values is a common way to safe traversal, and the entire mechanism is concise and practical.

How to execute SQL queries in Python? How to execute SQL queries in Python? Aug 02, 2025 am 01:56 AM

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

python threading timer example python threading timer example Jul 29, 2025 am 03:05 AM

threading.Timer executes functions asynchronously after a specified delay without blocking the main thread, and is suitable for handling lightweight delays or periodic tasks. ①Basic usage: Create Timer object and call start() method to delay execution of the specified function; ② Cancel task: Calling cancel() method before the task is executed can prevent execution; ③ Repeating execution: Enable periodic operation by encapsulating the RepeatingTimer class; ④ Note: Each Timer starts a new thread, and resources should be managed reasonably. If necessary, call cancel() to avoid memory waste. When the main program exits, you need to pay attention to the influence of non-daemon threads. It is suitable for delayed operations, timeout processing, and simple polling. It is simple but very practical.

See all articles