Getting a name error when trying to input a string [duplicate]

拜拜、爱过 提交于 2019-12-13 15:42:17

问题


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]

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

ERROR: If I try to add a name to the database I get a nameerror. NameError: name 'alan' is not defined. What's weird is that strings won't work but numbers will. Sorry if my question is unclear.

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
>>> 

回答1:


It seems like you're using Python 2.x.

Use raw_input instead of input to get string from user.

If you're reading book/material that assume the reader is using Python 3.x, it's better to use Python 3.x instead of Python 2.x.

BTW, dictionary keys are case-sensitive.

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


来源:https://stackoverflow.com/questions/19887358/getting-a-name-error-when-trying-to-input-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!