嘿,我的while循环在将值添加到字典中时遇到问题
contacts = {}
addContact = 'yes'
while addContact == 'yes':
name1 = input('Please enter the name of the contact: ')
num = int(input('Please enter the phone number of the contact: '))
email1 = input('Please enter the email of the conact: ')
contacts[name1] = num, email1
addContact = input('Would you like to add another Contact? (yes or no): ')
if addContact == 'no':
break
print(contacts)
循环只会添加用户最后输入的值,如何获取所有值呢?
在Python 2.7中使用它并将输入更改为raw_input时,我收到以下输出:
C:\Python27\Doc\Python Programs\Book>test.py
Please enter the name of the contact: test1
Please enter the phone number of the contact: 123456789
Please enter the email of the conact: [email protected]
Would you like to add another Contact? (yes or no): yes
Please enter the name of the contact: test2
Please enter the phone number of the contact: 234567891
Please enter the email of the conact: [email protected]
Would you like to add another Contact? (yes or no): no
{'test1': (123456789, '[email protected]'), 'test2': (234567891, '[email protected]')}
使用您的确切代码。
您的代码运行良好。但是,如果您要输入多个值,请说一个相同的名称,号码或电子邮件。您将要更改值。例如,从我的输出中,如果我输入test1作为名称,其数字为123456789,然后输入另一个test1,其数字为987654321,它将用第二个替换第一个。您需要一组代码来检查是否有多个相同的输入,然后将它们输入为新联系人,而不是替换前一个联系人。
我会尝试添加添加功能的方法,该功能会进行扫描以查看字典联系人中是否已存在输入。如果确实如此,则将其添加到词典中的其他位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句