0

I am now stepping into python and wrote a little piece of code. I declare a variable as global and then call it inside a function to increment it. However, I get an error "local variable 'iTime' referenced before assignment"

import time, threading

global iTime

def init():
    iTime=0

def foo():

    iTime+=1
    threading.Timer(1, foo).start()

init()
foo()

2 Answers2

0

The Global keyword is used to declare a variable as outside the scope where it is defined. In addition to that, you also have to declare it explicitly as a global variable inside each scope that you are using it before changing the value. This is because using global variables are bad programming practice and hence python wants to make sure you want to use a global variable inside the function. To make your code work, you can change it like this.

import time, threading

def init():
    global iTime
    iTime = 1

def foo():

    global iTime
    iTime+=1
    threading.Timer(1, foo).start()

init()
foo()
Sashi
  • 2,659
  • 5
  • 26
  • 38
0

The reason you are getting that error is because iTime is defined in the global scope but not within the function where it is being called. I was taught to avoid global variables, but you can accomplish what you are trying to by using the global keyword inside the function inside the function instead of outside:

iTime = 0
def foo():

    global iTime
    iTime +=1
    threading.Timer(1, foo).start()

init()
foo()
dsb4k8
  • 61
  • 3