我有一个基于文件输入制作字典的函数。然后是另一个基于字典进行计算的函数。这两个函数嵌套在一个主函数中。即:
def make_dic():
data=dict()
code...
return data
def make_calculation():
for x,y in data.items()
code....
def main():
data=make_dic()
make_calculation()
我的问题是我得到了一个错误: NameError: name 'data‘没有定义
当make_calculation()嵌套在make_dic()中时,如何使它们识别在make_dic()中创建的字典?
谢谢。
发布于 2021-07-17 11:58:58
将"data“作为参数传递给您的make_calculation函数:
def make_dic():
data=dict()
code...
return data
def make_calculation(data):
for x,y in data.items()
code....
def main():
data=make_dic()
make_calculation(data)
您需要这样做的原因是Python的作用域规则(即程序中的位置,或者参数是否定义的“作用域”)。
参数"data“不是全局变量(很少推荐使用全局变量的,应该是最后的),因此make_calculation(data)需要接收元素作为参数,该参数是在其他地方定义的,-ultimately是在make_dic()中创建的参数。
@chepner在他们的评论中更正式地说了同样多的话(即Python在词汇上的作用域)。有关Python作用域规则的更多信息,请参见下面这个古老但仍然有用的答案:Short description of the scoping rules?
发布于 2021-07-17 12:13:14
在第一个函数中尝试放置全局数据,希望它有所帮助。
https://stackoverflow.com/questions/68423851
复制相似问题