0

I am starting on a Twitter bot and having a stupid problem declaring a variable, the code is very simple and stripped everything and it still does not work. When I run the code I get the following error message:

UnboundLocalError: local variable 'Counter' referenced before assignment

I have declared the variable as a global and in different location but still having the same problem.

global Counter

import tweepy, time

def search():
    Counter += 1
    print("Counter = " + Counter + "\n")
    time.sleep(60)

def run():
   search()

if __name__ == '__main__':
   print "Running"f
   while True:
       run()
Steve Piercy
  • 13,693
  • 1
  • 44
  • 57
Brendon Shaw
  • 141
  • 13

2 Answers2

1

global should be used only within limited scopes (like a function) to indicate that you want Counter to reference the global object and not the local one.

Also, you need to initialize Counter with some value:

import tweepy, time

Counter = 0

def search():
    global Counter
    Counter += 1
    print("Counter = " + Counter + "\n")
    time.sleep(60)

def run():
   search()

if __name__ == '__main__':
   print "Running"
   while True:
       run()
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

global statement tells the code inside the block, to use a global variable context and not local one.

You still need to initialize this variable before addressing it.

Chen A.
  • 10,140
  • 3
  • 42
  • 61