Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python name error name not defined

I get the error name not defined on running this code in 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?

like image 664
user2405840 Avatar asked Oct 25 '25 12:10

user2405840


1 Answers

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). 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'])
like image 134
fjarri Avatar answered Oct 27 '25 01:10

fjarri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!