【问题标题】:I am getting LocalUnboundError我收到 LocalUnboundError
【发布时间】:2021-03-30 14:24:41
【问题描述】:

这是我的views.py文件:

url = "https://covid-193.p.rapidapi.com/statistics"
headers = {
    'x-rapidapi-key': "c5e4f10fa8msh519e24367741e55p1dcabajsn27df4eda14e0",
    'x-rapidapi-host': "covid-193.p.rapidapi.com"
    }
response = requests.request("GET", url, headers=headers).json()
def home(request):
    noofresults = int(response['results'])
    mylist = []
    for x in range(0,noofresults):
        mylist.append(response['response'][x]['country'])    
    if request.method=='POST':
        selectedcountry= request.POST['selectedcountry']
        # noofresults = int(response['results'])
        for x in range(0,noofresults):
            if selectedcountry==response['response'][x]['country']:
                new = response['response'][x]['cases']['new']
                active = response['response'][x]['cases']['active']
                critical = response['response'][x]['cases']['critical']
                recoverd = response['response'][x]['cases']['recovered']
                total = response['response'][x]['cases']['total']
                deaths = int(total)-int(active) - int(recoverd)    
        context = {'selectedcountry':selectedcountry,'mylist':mylist, 'new':new, 'active':active, 'critical':critical, 'recoverd':recoverd, 'total':total, 'deaths':deaths}
        return render(request,'home.html',context)                
    context = {'mylist': mylist}
    return render(request, 'home.html',context)

选择国家后出现的错误是:

UnboundLocalError at / local variable 'new' 在赋值前引用

【问题讨论】:

  • 在for循环之前初始化new, active, critical, recoverd, total, deaths

标签: python python-3.x django django-views


【解决方案1】:

我不太喜欢 Python,但在这里可以提供帮助。

您在声明时使用了new 变量,我相信这会导致错误“UnboundLocalError at / local variable 'new' referenced before assignment。”

new = response['response'][x]['cases']['new']

【讨论】:

  • 不完全是。问题是如果if selectedcountry ... 语句没有被执行,就没有new 值。
猜你喜欢
  • 2020-11-05
  • 2022-11-21
  • 2017-10-15
  • 1970-01-01
  • 2013-06-30
  • 2021-04-23
  • 2018-12-21
  • 2015-09-13
  • 1970-01-01
相关资源
最近更新 更多