尝试输入字符串时出现名称错误

use*_*703 2 python addressbook nameerror python-3.x

import pickle
import os
import time

class Person():
    def __init__(self, number, address):
        self.number = number
        self.address = address


def save():
    with open('mydict.pickle', 'wb') as f:
        pickle.dump(mydict, f)        

mydict = {}
mydict['Avi'] = ['347-000-0000', 'Oceanview']
mydict['Alan'] = ['347-000-0000', 'Brighton']
mydict['Frank'] = ['718-000-0000', 'Brighton']

print('add a name to the database.')
name = input('Name:')
number = input('Digits:')
address = input('Address:')
mydict[name] = [number, address]

-------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

错误:如果我尝试向数据库添加名称,我会得到一个名称错误.NameError:未定义名称'alan'.奇怪的是,字符串不起作用,但数字会起作用.对不起,如果我的问题不清楚.

Traceback (most recent call last):
  File "C:/Python33/ss", line 21, in <module>
    name = input('Name:')
  File "<string>", line 1, in <module>
NameError: name 'alan' is not defined
>>> 
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 11

看起来你正在使用Python 2.x.

使用raw_input而不是input从用户获取字符串.

如果您正在阅读本书/材料,假设读者使用的是Python 3.x,那么最好使用Python 3.x而不是Python 2.x.

顺便说一下,字典键区分大小写.

>>> d = {'Avi': 1, 'Alan': 2}
>>> d['alan']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'alan'
>>> d['Alan']
2
Run Code Online (Sandbox Code Playgroud)