1

I am trying to write a script updating a global variable every 10 seconds. For simplicity let's just increment q once teach time

import time, threading

q = 0
def f(q):
    # get asset position every 10 seconds:
    q += 1
    print q

    # call f() again in 10 seconds
    threading.Timer(10, f).start()


# start calling f now and every 10 sec thereafter
f(q)

Instead python says:

UnboundLocalError: local variable 'q' referenced before assignment

What is the correct way to change the variable q?


this example uses threading, doesn't update any values. Run certain code every n seconds

Community
  • 1
  • 1
john mangual
  • 7,718
  • 13
  • 56
  • 95

1 Answers1

4

You need to explicitly declare q as a global. q += 1 confuses the interpreter otherwise.

import threading

q = 0
def f():
    global q
    q += 1
    print q
    threading.Timer(10, f).start()

f()
Andrew Johnson
  • 3,078
  • 1
  • 18
  • 24