python名称错误名称未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19285014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:20:20 来源:igfitidea点击:
python name error name not defined
提问by user2405840
I get the error name not defined on running this code in python3:
我在 python3 中运行此代码时得到未定义的错误名称:
def main():
D = {} #create empty dictionary
for x in open('wvtc_data.txt'):
key, name, email, record = x.strip().split(':')
key = int(key) #convert key from string to integer
D[key] = {} #initialize key value with empty dictionary
D[key]['name'] = name
D[key]['email'] = email
D[key]['record'] = record
print(D[106]['name'])
print(D[110]['email'])
main()
Could you please help me fix this?
你能帮我解决这个问题吗?
采纳答案by fjarri
Your variable D
is local to the function main
, and, naturally, the code outside does not see it (you even try to access it beforerunning main
). Do something like
您的变量D
是函数的局部变量main
,自然而然,外部代码看不到它(您甚至尝试在运行之前访问它main
)。做类似的事情
def main():
D = {} #create empty dictionary
for x in open('wvtc_data.txt'):
key, name, email, record = x.strip().split(':')
key = int(key) #convert key from string to integer
D[key] = {} #initialize key value with empty dictionary
D[key]['name'] = name
D[key]['email'] = email
D[key]['record'] = record
return D
D = main()
print(D[106]['name'])
print(D[110]['email'])