This question already has answers here:
UnboundLocalError on local variable when reassigned after first use
                                
                                    (12个答案)
                                
                        
                                4年前关闭。
            
                    
我是python的新手,所以这可能是一个愚蠢的问题...

为什么函数fetchsamples无法看到变量表情符号?
奇怪的是,可以访问变量frownyDict和smileyDict,而不能访问smilies。

我得到的错误是:

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


以下是python代码:

##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()

最佳答案

您在代码中修改表情符号。您可以从下一个合并范围级别访问引用,但不能对其进行修改。因为您尝试这样做,解释器假设您不可能引用THAT变量,因此可以防止您意外修改它。

您必须将其声明为global或使用可变数据类型并对其进行适当的突变。

10-05 23:01
查看更多