我的讲师已将我的任务定为完成几个挑战,以帮助提高我对字典及其背后概念的理解。我已经能够很轻松地完成第一个任务,但是我对第二个任务非常执着。第一个任务是创建“谁是你的爸爸?程序'。
挑战说明:编写“谁是你的爸爸”程序,该程序允许用户输入男性的名字并产生其父亲的名字。 (您可以使用名人,虚构人物甚至历史人物来娱乐。)允许用户添加,替换和删除父子对。
我只能够解决一个问题,即我只能代替儿子的父亲,而不能同时代替两个儿子。
第二个挑战指出:通过添加一个选项使用户输入名称并找回祖父来改进该程序。您的程序仍应仅使用一对父子对字典。确保在词典中包括几代人,以便找到匹配项。
我以为我也许可以使用嵌套在字典中的字典并进行研究,但是它只说明了一个字典。然后我以为我可以在字典中使用一个元组,然后在用户请求一个儿子和他们的祖父但又不太幸运的时候访问这个元组,所以我决定来这里。
所以现在我想知道如何将祖父添加到每个对中,是否可以在字典的键中添加第二个值?
names = { "henry" : "michael",
"louis" : "jason",
"owen" : "justin",
"jake" : "glynn",
"adam" : "mark",
}
choice = None
while choice != "0":
print(
"""
Welcome to the Who's Your Daddy? program.
You can find out a father of the names listed,
you can then add, replace and delete a son/father pair.
0 - Exit
1 - List sons and their fathers
2 - Add a pair
3 - Replace a pair
4 - Delete a pair
"""
)
choice = input("Choice: ")
#exit
if choice == "0":
print("Goodbye")
#List sons
if choice == "1":
print(*names.keys(), sep='\n')
son_choice = input("Who's father would you like to know the name of?: ")
if son_choice in names:
print(names[son_choice])
else:
print("That name is not in the list!")
#Add a pair
elif choice == "2":
son_add = input("Enter the name of someone: ").lower()
if son_add not in names:
father_add = input("Now enter the name of their father: ").lower()
names[son_add] = father_add
print("That pair has been added")
else:
print("That name already exists!")
#Replace a pair
elif choice == "3":
son_replace = input("What name do you want to replace?: ")
if son_replace in names:
father_replace = input("Enter the name of their father: ")
names[son_replace] = father_replace
print("The pair has been replaced")
else:
print("That name doesn't exist, please add it first!")
#Delete a pair
elif choice == "4":
son_delete = input("What name do you want me to delete?: ")
if son_delete in names:
del names[son_delete]
print("Pair deleted!")
else:
print("That pair does not exist!")
else:
print("Sorry, that's an invalid choice!")
input("\n\nPress the enter key to exit!")