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
  • 12,031
  • 1
  • 36
  • 51
Brendon Shaw
  • 119
  • 12

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
  • 10,166
  • 4
  • 29
  • 58
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.
  • 8,778
  • 3
  • 33
  • 51