[英]Name error while trying to generate some report
def state_from_record(state_name):
state_split = state_name.split(",")
return state_split
def cases_from_record(covid_cases):
covid_split = covid_cases.split(",")
return covid_split
def deaths_from_record(covid_deaths):
death_split = covid_deaths.split(",")
return death_split
result1 = state_from_record(result[0])
print(result1)
This is the second part of the code which continues on:这是代码的第二部分,继续:
import random
def state_report(state, data_list):
if state_split is random:
states = choice(state_split)
for s in states:
if states == state_split:
return states + "\n" + "Total Confirmed Cases: " + covid_split + "Total Deaths: " + death_split
else:
return "No record found for " + states
result2 = state_report(states, state_split)
print(result2)
I am trying to use a previous code and it keeps on coming as a name error saying that "states" doesn't exist.我正在尝试使用以前的代码,但它一直以名称错误的形式出现,说“状态”不存在。
here is my output:这是我的 output:
NameError Traceback (most recent call last)
<ipython-input-20-8fee8f642c90> in <module>()
10 return "No record found for " + states
11
---> 12 result2 = state_report(states, state_split)
13 print(result2)
NameError: name 'states' is not defined
What you are bumping into is a programming concept called the scope您遇到的是一个名为scope的编程概念
Imagine these two functions:想象一下这两个函数:
def first_func():
foo = "abc"
print(foo)
def second_func():
print(foo)
second_func()
Running this code will raise NameError
, because variable foo
is out of the scope of the second_func
, since it is defined within the boundaries of the first_func
.运行此代码将引发NameError
,因为变量foo
不在second_func的second_func
范围内,因为它是在first_func
的边界内定义的。
If you move the variable foo
out of the first function, like so:如果将变量foo
移出第一个 function,如下所示:
foo = "abc"
def first_func():
print(foo)
def second_func():
print(foo)
second_func()
Both functions will run fine.这两个功能都可以正常运行。 Because variable foo
is now defined in a broader scope and accessible from within both functions.因为变量foo
现在在更广泛的 scope 中定义,并且可以从两个函数中访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.