Я создаю простую программу адресной книги в Python. Всякий раз, когда я вводю несколько контактов через меню командной строки, а затем нажмите «b», чтобы перечислить все контакты, отображается только последний контакт, который я ввел. Как я могу заставить программу сохранять все контакты?Как использовать словарь в цикле while?
# Import Collections to use Ordered Dictionary
import collections
# The main class
def main():
# Print the menu for program
print """
Contact Book App
a) New Contact
b) List Contacts
c) Search Contacts
d) Delete Contact
e) Quit
"""
# Creates an empty ordered dictionary
contact = collections.OrderedDict()
# Sets the loop as 1
loop = 1
# Create a while loop for the menu that keeps looping for user input until loop = 0
while loop == 1:
# Asks for users input from 1-5
userInput = raw_input("Please select an option: ").lower()
# OPTION 1 : ADD NEW CONTACT
if userInput == "a":
contact['name'] = raw_input("Enter name: ")
contact['phone'] = raw_input("Enter phone: ")
contact['email'] = raw_input("Enter email: ")
# Confirmation prompt
print "Contact Added!"
#For Debugging Purposes
# print(contact)
# OPTION 2 : LIST ALL CONTACTS
elif userInput == "b":
print "Listing Contacts"
print(contact)
# OPTION 3 : SEARCH CONTACTS
elif userInput == "c":
print "Searching Contacts"
print "Please Enter Contact Name"
# OPTION 4 : DELETE A CONTACT
elif userInput == "d":
print "Deleting Contact"
# OPTION 5 : QUIT PROGRAM
elif userInput == "e":
print "Quitting Contact Book"
loop = 0
else:
print "I did not understand your input"
main()
Вот мой результат:
Contact Book App
a) New Contact
b) List Contacts
c) Search Contacts
d) Delete Contact
e) Quit
Please select an option: a
Enter name: Dave Smith
Enter phone: 5553451212
Enter email: [email protected]
Contact Added!
Please select an option: a
Enter name: John Doe
Enter phone: 4445433232
Enter email: [email protected]
Contact Added!
Please select an option: b
Listing Contacts
OrderedDict([('name', 'John Doe'), ('phone', '4445433232'), ('email', '[email protected]')])
Please select an option:
Как вы можете видеть только последняя запись John Doe
появляется и Dave Smith
были перезаписаны.
Вы всегда переписываете один и тот же контакт. Вы должны составить список словарей. –