Home >Backend Development >Python Tutorial >Why Does `c = 1` Cause an `UnboundLocalError` in Python Functions?

Why Does `c = 1` Cause an `UnboundLocalError` in Python Functions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 01:11:14267browse

Why Does `c  = 1` Cause an `UnboundLocalError` in Python Functions?

UnboundLocalError: Variable Scope in Functions with Assignments

The UnboundLocalError arises when a variable is used within a function without being properly defined or imported. Understanding the concept of scope is crucial to resolve this issue.

Python distinguishes between local and global variables within functions. When a variable is assigned a value inside a function, it becomes a local variable. This local variable takes precedence over any global variable with the same name.

In the example provided, when c = 1 is executed, a local variable c is created. This local variable overrides the global variable c with the value 3. However, the print(c) statement is attempting to access the global c, which is undefined at that point, causing the UnboundLocalError.

To remedy this issue, Python provides two options:

  • global: Declaring a variable as global within a function ensures that it references the global variable of the same name. By placing global c as the first line of the test() function, the print(c) statement would refer to the global c, eliminating the error.
  • nonlocal (Python 3): Use nonlocal c to access the c variable defined in the nearest enclosing function scope. This option is particularly useful for closures.

The above is the detailed content of Why Does `c = 1` Cause an `UnboundLocalError` in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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