【问题标题】:Getting a name error when trying to input a string [duplicate]尝试输入字符串时出现名称错误[重复]
【发布时间】:2013-11-22 03:12:14
【问题描述】:
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
>>> 

【问题讨论】:

    标签: python python-3.x addressbook nameerror


    【解决方案1】:

    您似乎使用的是 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
    

    【讨论】:

    • 啊。谢谢。出于某种原因,打开了 python 2.7 shell 而不是 3.3 shell。我都安装了。感谢您清除它!
    猜你喜欢
    • 2011-09-03
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多