簡體   English   中英

在While循環中如何使用字典?

[英]How to use Dictionary in While Loop?

我正在用Python創建一個簡單的通訊錄程序。 每當我通過命令行菜單輸入多個聯系人,然后按“ b”列出所有聯系人時,它僅顯示我輸入的最后一個聯系人。 如何使程序保存所有聯系人?

# 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: dsmith@gmail.com
Contact Added!
Please select an option: a
Enter name: John Doe
Enter phone: 4445433232
Enter email: jdoe@hotmail.com
Contact Added!
Please select an option: b
Listing Contacts
OrderedDict([('name', 'John Doe'), ('phone', '4445433232'), ('email', 'jdoe@hotmail.com')])
Please select an option:

如您所見,只有John Doe出現,而Dave Smith被覆蓋。

列出並添加新的聯系人:

contacts = []    
...
# OPTION 1 : ADD NEW CONTACT
if userInput == "a":
    contact = collections.OrderedDict()
    contact['name'] = raw_input("Enter name: ")
    contact['phone'] = raw_input("Enter phone: ")
    contact['email'] = raw_input("Enter email: ")
    contacts.append(contact)
...
contacts = []

# 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 = collections.OrderedDict()
        contact['name'] = raw_input("Enter name: ")
        contact['phone'] = raw_input("Enter phone: ")
        contact['email'] = raw_input("Enter email: ")
        contacts.append(contact)

        # Confirmation prompt
        print "Contact Added!"

        #For Debugging Purposes
        # print(contact)

    # OPTION 2 : LIST ALL CONTACTS
    elif userInput == "b":
        print "Listing Contacts"

        print(contacts)

[...]

每次您要求用戶提供新的聯系人詳細信息時,都會覆蓋以前創建的單個聯系人。 相反,您必須維護一個聯系人列表,創建一個新聯系人並將該聯系人添加到列表中。 另外,我建議創建一個class Contact而不是僅僅使用字典。

class Contact:
    def __init__(self, name, phone, mail):
        self.name = name
        self.phone = phone
        self.mail = mail
    def __repr__(self):
        return "Contact(%r, %r, %r)" % (self.name, self.phone, self.mail)

另外,您可以使用break退出循環,而不使用變量。 在您的main (節選)中:

...
contacts= []   # initialize list of contacts

while True:
    userInput = raw_input("Please select an option: ").lower()

    if userInput == "a":
        name = raw_input("Enter name: ")
        phone = raw_input("Enter phone: ")
        email = raw_input("Enter email: ")
        contacts.append(Contact(name, phone, email)) # create and add new contact
        print "Contact Added!"

    elif userInput == "b":
        print "Listing Contacts"
        print(contacts) # use contacts list here

    ... more options

    elif userInput == "e":
        print "Quitting Contact Book"
        break           # use break here
    else:
        print "I did not understand your input"

每次您在字典中使用鍵“名稱”創建新條目時,都會覆蓋前一個。 最好創建一個新的詞典列表,並將每個人存儲為該列表中的單獨詞典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM