1

I am new to python, so this may be a silly question...

Why does the function fetchsamples not see the variable smilies? Strangely, the variable frownyDict and smileyDict are accessible, while smilies is not.

The error I get is:

Traceback (most recent call last):
  File "simple.py", line 41, in <module>
    fetchsamples()
  File "simple.py", line 18, in fetchsamples
    print smilies
UnboundLocalError: local variable 'smilies' referenced before assignment

Below is the python code:

##my global vars

frownyDict={}
smileyDict={}
frownyDict['_counter_']=0
smileyDict['_counter_']=0
frownies = 0
smilies = 0



def fetchsamples():
    print frownyDict;
    response = [":) happy",":( sad","sad","dunno"]
    counter=0
    print smilies
    for tweet in response:
        if (tweet):
            tweet=tweet.encode("iso-8859-1", "ignore")
            if ":)" in tweet:
                parse(smileyDict,tweet)
                counter+=1
                smilies+=1
            if ":(" in tweet:
                parse(frownyDict,tweet)
                counter+=1
                #frownies+=1
                frownyDict['_counter_']+=1;
            if ":)" in tweet or ":)" in tweet:
                guess(tweet)
                # let's predict!

            if (counter % 50==10):
                print frownyDict;
                print smileyDict


if __name__ == '__main__':
  fetchsamples()
Kevin
  • 74,910
  • 12
  • 133
  • 166
Chris
  • 1,219
  • 2
  • 11
  • 21
  • Your code contains `if ":)" in tweet or ":)" in tweet`, and I think it's a mistake. Should the second face be `:(`? Also, you may want to use `elif` instead of just stringing multiple `if`s together... – mbomb007 Sep 01 '15 at 18:44
  • Good catch!! I've since rearranged the code but I will check to make sure that bug isn't there! – Chris Sep 02 '15 at 17:38

1 Answers1

1

You modify smilies in the code. You can access a reference from the next scope level up, but you cannot modify it. Because you try to, the interpreter assumes you cannot possibly be referring to THAT variable, so prevents you from modifying it accidentally.

You have to declare it global or use a mutable datatype and mutate it in place.

Paul Becotte
  • 9,767
  • 3
  • 34
  • 42