【发布时间】:2021-09-29 22:55:13
【问题描述】:
contacts = {'John Smith': '1-123-123-123',
'Jane Smith': '1-102-555-5678',
'John Doe': '1-103-555-9012'}
def add_contact(contacts, name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in contacts:
print(name, "is already in contacts list!")
else:
contacts[name] = number
print(add_contact(contacts, 'new_guy', '1234'))
当我打印这个时,我得到none
但如果我添加另一行 print(contacts)
它会给我一个none 和带有'new_guy' :'1234'. 的新字典在不打印none 的情况下打印出新字典的正确方法是什么?
【问题讨论】:
-
您正确地添加到字典中。你打印错了。您的 print 语句打印函数的结果。您的函数不返回任何内容。
-
对。由于您的功能已就地修改,请不要打印它。只需拨打
add_contact(contacts, 'new_guy', '1234'),然后拨打print(contacts)。 -
如果你只是在
add_contact函数的末尾添加return contacts,它就可以正常工作。
标签: python python-3.x dictionary