Python Unbound LocalError

Asked 1 years ago, Updated 1 years ago, 104 views

If you run the code below, you will receive UnboundLocalError. What's wrong?

counter = 0

def increment():
  counter += 1

increment()

scope python global-variable

2022-09-21 18:26

1 Answers

The concept of variable declaration does not exist in Python. Therefore, Python determines the range of use of a variable with the following rules: If a variable is used in a function, it is considered a local variable. [1] Accordingly, the following

counter += 1

treats counter as a regional variable for the function increment(). Therefore, running this syntax will attempt to read the value of the local variable before it is assigned counter, which will cause UnboundLocalError.

If you want to use counter as a global variable, you can use the global keyword. Also, for Python 3.x, use if the function increment() is used as the built-in function and counter is the regional variable (including increment() function).


2022-09-21 18:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.