尝试输入字符串时出现名称错误 [英] Getting a name error when trying to input a string
本文介绍了尝试输入字符串时出现名称错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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".奇怪的是字符串不起作用,但是数字会起作用.对不起,如果我的问题不清楚.
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
>>>
推荐答案
似乎您正在使用Python 2.x.
It seems like you're using Python 2.x.
使用 raw_input
代替
Use raw_input
instead of input
to get string from user.
如果您在阅读本书/材料时假设读者使用的是Python 3.x,则最好使用Python 3.x而不是Python 2.x.
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
这篇关于尝试输入字符串时出现名称错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文