[英]python name error name not defined
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?你能帮我解决这个问题吗?
Your variable D
is local to the function main
, and, naturally, the code outside does not see it (you even try to access it before running main
). 您的变量
D
是main
函数的局部变量,自然,外部代码看不到它(您甚至在运行main
之前尝试访问它)。 Do something like 做类似的事情
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.