0

I have 2 Python files:

functions.py

global counter
counter = 0

def printC():
    print(counter)

def increaseC():
    counter += 1

and a main.py

from functions import printC
from functions import increaseC

printC()
increaseC()

The first function prints the 0 with no problem but then i get that error message:

counter += 1
UnboundLocalError: local variable 'counter' referenced before assignment

My question is: How can i increase that global variable that way than i can print the same way like this:

from functions import printC
from functions import increaseC

printC()
increaseC()
printC()

To get the second print with 1 value?

  • 2
    Use global keyword inside a function if you want to change the variable. – Valentin Briukhanov Dec 29 '19 at 14:11
  • 3
    Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Dinesh Dec 29 '19 at 14:13
  • 1
    `global counter` inside `increaseC` since because you do `counter += 1`, counter is looked into the local namespace of `increaseC`, but it's not there. `global counter` tells it to look in the global scope – Devesh Kumar Singh Dec 29 '19 at 14:14

1 Answers1

0

Use global keyword inside a function if you want to change the variable.

def increaseC():
    global counter
    counter += 1
Valentin Briukhanov
  • 1,263
  • 9
  • 13