Python奇怪的UnboundLocalE

2024-09-25 00:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行以下函数时:

def checkChange():
    for user in userLinks:
        url = userLinks[user]
        response = urllib2.urlopen(url)  
        html = response.read()

我明白了

^{pr2}$

这对我来说毫无意义。我没有全局var响应。我希望它正常工作如下。在

>>> url="http://google.com"
>>> response = urllib2.urlopen(url)  
>>> html = response.read()
>>> html
'<!doctype html>

有人知道我为什么会犯这个错误吗?在


Tags: 函数inurlforreadresponsedefhtml
2条回答

你的代码没有正确缩进。把它改成这个,它就会起作用(可能不是预期的那样,但它会起作用):

for user in userLinks:
    url = userLinks[user]
    response = urllib2.urlopen(url)  
    html = response.read()

    if userSources[user] != html:
        del userSources[user]
        del userLinks[user]
        api.PostDirectMessage(user,'It appears the page has updated! Your item may be back in stock!')

发生此错误是因为您在for循环中定义了response,但是如果循环没有运行(即userLinks == []),则永远不会设置该变量。在

你在混合制表符和空格。看看你粘贴的原始代码:

'    def checkChange():'
'    \tfor user in userLinks:'
'    \t\turl = userLinks[user]'
'    \t\tresponse = urllib2.urlopen(url)  '
'            html = response.read()'

你可以在最后一行看到开关。实际上,这意味着html = response.read()行的缩进程度没有想象中的那么大,这意味着如果userLinks为空,您将得到:

^{pr2}$

使用python -tt yourprogramname.py运行代码以确认这一点,并切换到始终使用四个空格制表符。在

相关问题 更多 >