TypeError:无法隐式地将'NoneType'对象转换为str。这是我尝试使用函数将条目硬编码到字典时得到的错误。让用户输入工作,并将其放入字典中,但这不起作用。我已经搜索了其他错误,比如这个(意思是TypeError。),但我什么都没想出来。发生此错误的其他两个(This和this)条目与我无关。
因此。我试图让AweInspiring和BeingAwesome成为一个打印函数,认为它可以正确地打印到Achievements字典中,因为只需将AweInspiring和BeingAwesome放在那里就会导致它说它需要定义。然后它出现了这个错误。我认为它应该有用,但它没有,我不知道为什么。有人能帮助我吗?
achievements = {}
AweInspiring = print()
BeingAwesome = print()
def dovar():
global achievements
print('Type in either \'achievement get\' or \'view achievements.\'')
achieve = input()
if achieve == 'view achievements':
print('Achievements')
for x in achievements.keys():
print('Achievement Name: ' + x + '\tFor: ' + achievements[x])
elif achieve == 'achievement get':
achieveget()
elif achieve == 'achieve':
hardachieve()
def achieveget():
print('Add Achievement')
achievename = input('Name of achievement earned: ')
achievedesc = input('How was the achievement earned: ')
achievements[achievename] = achievedesc
dovarloop()
def hardachieve():
achievename = AweInspiring
achievedesc = BeingAwesome
achievements[achievename] = achievedesc
dovar()
def dovarloop():
dovar()
dovar()
答案 0 :(得分:1)
print()
不返回任何内容(默认情况下,它返回None
)。那么当你做achievements[achievename] = achievedesc
时,python实际上是这样做的:
{None:None}
然后你正在做:
print('Achievement Name: ' + x + '\tFor: ' + achievements[x])
其中x
为关键None
,achievements[x]
为值(也为None
)
但是你不能连接字符串和NoneType(因此错误)。
所以,你的代码是最简单的形式(例如),你试图这样做:
print('Hello' + None)
要解决此问题,您可以将AweInspiring
和BeingAwesome
设为空字符串:
AweInspiring = ''
BeingAwesome = ''
答案 1 :(得分:0)
在我的闲置中编辑它,添加了一些成就,并最终为自己感到骄傲,因为它适用于我:
achievements = {}
def dovar():
global achievements
print('Type in either \'achievement get\' or \'view achievements.\'')
achieve = raw_input()
if achieve == 'view achievements':
print('Achievements')
for x in achievements.keys():
print('Achievement Name: ' + x + '\tFor: ' + achievements[x])
elif achieve == 'achievement get':
achieveget()
elif achieve == 'achieve':
hardachieve()
def achieveget():
print('Add Achievement')
achievename = raw_input('Name of achievement earned: ')
achievedesc = raw_input('How was the achievement earned: ')
achievements[achievename] = achievedesc
dovarloop()
def hardachieve():
global achievments
achievename = "got a cat"
achievedesc = "found one"
achievements[achievename] = achievedesc
#dovar()
def dovarloop():
dovar()
dovar()
我的谈话:
================================ RESTART ============== ==================
>>>
Type in either 'achievement get' or 'view achievements.'
achievement get
Add Achievement
Name of achievement earned: got a cat
How was the achievement earned: found one
Type in either 'achievement get' or 'view achievements.'
view achievements
Achievements
Achievement Name: got a cat For: found one
>>>
>>> ================================ RESTART ================================
>>> hardachieve()
>>> achievements
{'got a cat': 'found one'}