簡體   English   中英

Python字典初始化

[英]Python- dictionary initialization

我需要有三個名稱和電子郵件地址才能開始該程序。 我嘗試使用emailaddress = {"Drew": drew@myemail.com, "Lucie": lucie@snailmail.com, "Brodie": brodie@geemail.com}但這會給我以下信息:

追溯(最近一次通話):

文件“ C:/ Users / Drew / Documents / CIT 144 / Email dictionary.py”,第17行

emailaddress = {“提請”:drew@myemail.com,“露西”:lucie@snailmail.com,

NameError:未定義名稱“ drew”

該程序將與emailaddress = {} ,但如果具有鍵/值,則會出現該錯誤。 我是Python和程序設計的新手,因此非常感謝您的幫助或解釋!!!

## This program keeps names and email addresses
# in a dictionary called emailaddress as key-value pairs.
# The program should initialize the dictionary with three
# people/email addresses. Then program should display the
# menu and loop until 5 is selected
##

def displayMenu():
    print()
    print("1) Look up email address")
    print("2) Add a name and email address")
    print("3) Change email address")
    print("4) Delete name and email address")
    print("5) End program")
    print()

emailaddress = {}
choice = 0
displayMenu()
while choice != 5:
    choice = int(input("Enter your selection (1-5): "))

    if choice == 1:
        print("Look up email address:")
        name = input("Name: ")
        if name in emailaddress:
            print("The email address is", emailaddress[name])
        else:
            print(name, "was not found")
    elif choice == 2:
        print("Add a name and email address")
        name = input("Name: ")
        email = input("Email: ")
        emailaddress[name] = email
    elif choice == 3:
        print("Change email address")
        name = input("Name: ")
        if name in emailaddress:
            email = input("Enter the new address: ")
            emailaddress[name] = email
        else:
            print(name, "was not found")
    elif choice == 4:
        print("Delete name and email address")
        name = input("Name: ")
        if name in emailaddress:
            del emailaddress[name]
        else:
            print(name, "was not found")          
    elif choice != 5:
        print("Enter a valid selection")
        displayMenu()

您只是在聲明不帶引號的字符串,使python嘗試解釋它們而失敗。

emailaddress = {"Drew": "drew@myemail.com", "Lucie": "lucie@snailmail.com", "Brodie": "brodie@geemail.com"}

將工作。 注意電子郵件周圍的引號

emailaddress = {"Drew": drew@myemail.com, "Lucie": lucie@snailmail.com, 
"Brodie": brodie@geemail.com}

drew@myemail.com不是字符串。 應該用引號引起來。

暫無
暫無

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

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