Python 使用while循环向字典添加值
嘿,我的while循环在向字典添加值时遇到了一个问题Python 使用while循环向字典添加值,python,dictionary,python-3.4,Python,Dictionary,Python 3.4,嘿,我的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
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中使用此方法并将输入更改为原始输入时,我收到以下输出:
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,然后输入另一个编号为987654321的test1,它将用第二个替换第一个。您需要有一组代码来检查多个相同的输入,然后将它们作为新触点输入,而不是替换以前的触点
我会尝试添加一个函数,扫描字典联系人中是否已经存在输入。如果确实如此,则将其添加到另一个位置的字典。我运行了您的代码,它工作正常。顺便说一下,您不需要if addContact=='no'块。您的代码似乎工作正常,有什么问题吗?你说的“只添加用户上次输入的值”是什么意思?你是在输入多个同名的人吗?是的,这就是我输入同名的问题。哈哈,谢谢,那么你是想首先找出如何避免这个问题,还是想在这里结束它。如果您不想再进一步,请拒绝回答,这样问题就可以自动删除。或者,你也可以不接受答案,自己使用帖子下方的删除链接删除问题。此答案确实确定了潜在问题和潜在解决方案,但实际上并没有提供问题的解决方案。请给出您的答案,为您确定的问题提供解决方案,以便将其转化为一个好的答案。否则,它只不过是一个扩展注释,这不是答案部分的目的。是的,这是我的问题,我输入了多个同名值。谢谢你的帮助