2013-11-10 100 views
1
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] 

------------------------------------------------------- 

错误: 如果我尝试向数据库添加名称,则会出现名称错误。 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 
>>> 
+0

是的,我刚刚做到了。 – user2975703

+0

python 2.7或3? – samrap

回答

4

看起来好像你在使用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 
+0

啊。谢谢。由于某些原因,python 2.7 shell打开而不是3.3 shell。我都安装了。感谢您解决这个问题! – user2975703

+0

@ user2975703,如果这有帮助,[**接受答案**](http://meta.stackexchange.com/a/5235)。 – falsetru