嘿我的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)
循环只会添加用户最后输入的值,如何才能添加所有值?
答案 0 :(得分:-2)
在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: test1@yahoo.com
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: test2@yahoo.com
Would you like to add another Contact? (yes or no): no
{'test1': (123456789, 'test1@yahoo.com'), 'test2': (234567891, 'test2@yahoo.com')}
使用您的确切代码。
您的代码运行正常。但是,如果您输入多个值,请说明相同的名称,编号或电子邮件。您将要更改该值。例如,从我的输出中,如果我输入test1作为名称,编号为123456789,然后输入另一个test1,编号为987654321,它将用第二个替换第一个。您需要有一组代码来检查多个相同的输入,然后将它们作为新的联系人输入,而不是替换之前的联系人。
我会尝试添加一个函数来扫描以查看输入是否已存在于字典联系人中。如果是,则将其添加到不同位置的字典中。