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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19887358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:53:58  来源:igfitidea点击:

Getting a name error when trying to input a string

pythonpython-3.xaddressbooknameerror

提问by user2975703

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.

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

回答by falsetru

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

您似乎在使用 Python 2.x。

Use raw_inputinstead of inputto get string from user.

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

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.

如果您正在阅读假定读者使用 Python 3.x 的书籍/材料,则最好使用 Python 3.x 而不是 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