Use a global statement, like so:

COUNT = 0

def increment():
    global COUNT
    COUNT = COUNT+1

increment()

Global variables can be accessed without using global, but the statement is required in order to change the value of the global variable.

Answer from cobie on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › python doesn't allow to increment global variable inside function?
r/learnpython on Reddit: Python doesn't allow to increment global variable inside function?
April 4, 2024 -

So going thorough scoping rules I learned that inside a function if you used a global variable and then assign it a value it will raise UnboundLocalError.

x = 7
def f():
    x = 7       #I will now create new variable x inside f's local scope

Correct above one is fine.

x = 7
def f():
    print(x)   #x is not defined already, okay I will use global x now

Okay this is also fine.

But,

x = 7
def f():
    print(x)     #x is not defined already, okay I will use global x now
    x = 7        #I will now create new variable x inside f's local scope (OHH, scope clash raise UnboudLocalError)

Fine, might is right.

But why you are not allowing me to do this.

x = 7
def f():
    x += 1

In above I am just incrementing x, why don't it uses x from global scope?

So, from my understanding I think it due to += used here the statement can be broken into:

x = x + 1

#  which in turn is
#  x = x.__add__(1)

Why didn't they implemented it like:

1. Evaluate expression after =, i.e., x.__add__(1)
2. Now we encountered x, take it from global.
3. In function scope we have x from global so when evaluating left expression
x = [...] we assign it value from RHS.

🌐
PythonHello
pythonhello.com › problems › variable › how-to-use-global-variables-in-a-function
How to Use Global Variables in a Function in Python
In this case, you will need to use the global keyword to explicitly tell Python that you are working with the global variable and not a local variable with the same name. Here is an example of how to use the global keyword to access and modify ...
🌐
Reddit
reddit.com › r/learnpython › how to increment a global variable when a particular function is called?
r/learnpython on Reddit: How to increment a global variable when a particular function is called?
April 28, 2014 -

So, I'm trying to code a simple dice-throw based text game. It's kind of like choose-your-own-adventure with random choices.

I want to keep track of how many times the die have been thrown, but I can't seem to figure out how to do so.

Here is the code for the function:

def winner():
    roll1 = throw()
    print P1," rolls a ",roll1
    roll2 = throw()
    print P2," rolls a ",roll2
    if roll1 > roll2:
        print P1," wins with a ",roll1,"!"
        return P1
    elif roll2 > roll2:
        print P2," wins with a ",roll2,"!"
        return P2
    else:
        print "It's a tie, throw again."
        winner()
    global turn
    turn = 0
    turn += 1    

I know that the last three lines are not right, but I don't know what the right way to have turn as a global variable in the script that increments each time winner() completes is. Especially because I don't want to count ties as extra turns.

🌐
Pychallenger
pychallenger.com › intermediate-python › functions-ii › exercise-modify-global-variable-python
Modify a Global Variable Inside a Function | Pychallenger
Pychallenger. Adjust the increment function so that it modifies the global variable counter. Every time you call increment, it should increment counter by 1.
🌐
Medium
medium.com › @python-javascript-php-html-css › using-global-variables-in-python-functions-1719bdca0609
Global Variable Utilization in Python Functions | by Denis Bélanger 💎⚡✨ | Medium
August 24, 2024 - Without this keyword, Python would treat counter as a local variable, leading to an UnboundLocalError when trying to modify it. The counter += 1 line increments the value of counter by one.
Find elsewhere
🌐
iO Flood
ioflood.com › blog › python-global-variables
Python Global Variables | Usage Guide (With Examples)
December 4, 2023 - While global variables are a straightforward way to share data across functions or modules, Python provides other methods that can be more effective in certain scenarios. Let’s explore some of these alternatives and understand their pros and cons. One method is to use classes, which can encapsulate related data and functions. Here’s an example: # Using a class to share data class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 def decrement(self): self.count -= 1 my_counter = Counter() my_counter.increment() my_counter.increment() my_counter.decrement() print(my_counter.count) # Output: # 1
🌐
Sentry
sentry.io › sentry answers › python › use global variables in python functions
Use global variables in Python functions | Sentry
def create_counter(): global counter counter = 1 def increment_counter(): global counter counter += 1 def print_counter(): global counter print(counter) create_counter() print_counter() increment_counter() print_counter() increment_counter() print_counter() When executed, this code will produce the following output: 1 2 3 · From this, we can tell that all three functions use the same variable. Note that using global variables in this way can make your code difficult to reason about and debug beyond a certain scale. Global variables are generally considered bad programming practice and should
🌐
Real Python
realpython.com › python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions – Real Python
December 8, 2024 - As an example, here’s a new implementation of your old friend increment() without using a global variable inside the function. In this case, the function just takes a value as an argument and returns it incremented by one: ... >>> def increment(value=0): ... return value + 1 ...
Top answer
1 of 2
4

You need:

counter = 0

def addCounter():
     global counter
     counter = counter + 1
     return counter

Explanation: in Python, the declaration of inner variables is implicit, an assignment automatically declares the values on the left-hand side, however that declaration is always in the local scope. That's why if you write this:

counter = 0
def addCounter():
    return counter

it will work fine but as soon as you add an assignment

counter = 0
def addCounter():
    counter += 1
    return counter

it breaks: the assigment adds an implicit local declaration. global overrides this, although it requires that the global exist beforehand, it does not create a global, it just tells the function that this is a global variable it can reassign to.

I've tried passing the counter variable in as a parameter as well, but that doesn't work either.

Indeed not. Python's evaluation strategy is sometimes called "pass by sharing" (or "pass reference by value") which is technically "pass by value" but that term gets a bit confusing as the values in this case are references, the references are copied but the objects referred to are not, and thus the end-behaviour diverges from the normal expectations of "pass by value" expectations.

2 of 2
2

Using a class rather than global:

Another way to handle (not use) global variables is to wrap the functions and variables you wish to be global in a class.

While this is a little heavy for this specific case - classes add a host of functionality and flexability to the project. (Personally) highly recommended.

For example:

class Processor():
    """Class container for processing stuff."""

    _counter = 0

    def addcounter(self):
        """Increment the counter."""
        # Some code here ...
        self._counter += 1

# See the counter incrementing.
proc = Processor()
proc.addcounter()
print(proc._counter)
proc.addcounter()
print(proc._counter)

Output:

1
2
🌐
AskPython
askpython.com › home › python increment by 1
Python increment by 1 - AskPython
December 7, 2022 - To increment a variable by 1 in Python, you can use the augmented assignment operator +=. This operator adds the right operand to the left operand and assigns the result to the left operand.
🌐
Reddit
reddit.com › r/learnprogramming › how would i get my variable to increment python?
r/learnprogramming on Reddit: How would i get my variable to increment python?
June 17, 2022 -

I have a counter set up to notify me how many times I write to a file: amount_of_times = 1. However every-time I write to the file it is not incrementing, is there a way for me to get it to increment, so I know how many times I ran the program?

with open ('TextInfo.txt','w') as filer:
    amount_of_times = 1
    filer.write('I wrote one time')
    filer.write('Again')
    print('Executed amont of times: {}'.format(amount_of_times))
    amount_of_times = amount_of_times + 1
🌐
Reeborg
reeborg.ca › docs › en › variables › increment.html
6. Increment — Learn Python with Reeborg
We’ve already instructed Python that we want n to refer to 1. Thus n + 3 should be thought of as 1 + 3. Python knows how to add integers, and it can replace this sum of two integers by a single one: 4. Thus, n + 3 refers to the object 4, and the line of code: ... And this line can be thought of as telling Python whatever n meant before, forget about it, and think of it as meaning 4 from now on. What about a = a + 3? Python first looks at the right hand side a + 3, finds a variable a which has not been assigned to any object before, so it doesn’t know what to do with it, and lets us know by giving an error message.
🌐
Sololearn
sololearn.com › en › Discuss › 1535787 › i-want-to-increment-the-global-variable-when-i-call-a-function-but-its-giving-me-an-error-can-some-body-help-me-out
I want to increment the global variable when i call a function but its giving me an error can some body help me out | Sololearn: Learn to code for FREE!
x=0 def main(): print(x) x+=1 def check(): for I in range(10): main() check() expected output: 0 1 2 3 4 5 6 7 8 9 10 actual outpu: UnboundError: Local variable referenced before assignment · python3 · 7th Oct 2018, 4:46 PM · Velivela Sai Chinna Madhu Babu · 3 Answers · Answer · + 6 · add 'global x' after 'def main():' 7th Oct 2018, 5:50 PM ·
🌐
Script Everything
scripteverything.com › posts › python increment by 1
Python Increment By 1 | Script Everything
October 24, 2021 - Does i++ work in Python? No, it doesn’t. It will return a SyntaxError. Therefore, to achieve the same purpose of incrementing a variable, i, by 1 using the syntax i += 1 or its longer form syntactical representation i = i + 1.