我的讲师给我布置了一项任务,要求我完成一些挑战,以帮助我提高对字典及其背后的概念的理解。我能够很容易地完成第一项任务,但我很难完成第二项任务。第一个任务是创建一个“谁是你的爸爸?”程序。
挑战是:编写一个谁是你的爸爸的程序,让用户输入男性的名字,并产生他父亲的名字。(你可以利用名人,虚构的人物,甚至历史人物来取乐。)允许用户添加、替换和删除子父对。
我能够创建这个挑战只有一个问题,那就是我只能替换一个儿子的父亲,而不是两个。
第二个挑战是:通过添加一个选项来改进这个程序,该选项允许用户输入一个名字并返回一个祖父。您的程序应该仍然只使用一个子-父对字典。确保在您的字典中包含多个代词,以便可以找到匹配项。
我想也许我可以使用一本嵌套在字典中的字典进行研究,但它只说明了一本字典。然后我想,我可以使用字典中的元组,然后在用户请求儿子和他们的祖父时访问这个元组,但在这方面也没有太多的运气,所以我决定来这里。
所以现在我想知道,我如何将祖父添加到每对中,您是否可以将第二个值添加到字典中的键?
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!")发布于 2019-10-24 19:38:52
在Ronald和一些常识的帮助下,我现在已经解决了这个问题。
为了找到祖父,我需要创建一个新的儿子父亲对,其中儿子的父亲将是列表中已有的儿子。例如,如果我创建了一个新的对,其中儿子名为tom,父亲名为henry。然后,我可以使用查找祖父功能来显示tom的祖父将是michael。
#Find a grandfather
elif choice == "5":
grandson = input("Please enter the son and I will find the grandfather: ").lower()
if grandson in names:
father = names[grandson]
if father in names:
grandfather = names[father]
print("The grandfather of " + grandson + " is " + grandfather)
else:
print(father + " is not in the dictionary")
else:
print(grandson + " is not in the dictionary")这是我创建的代码,但是,我如何让它在几代人中工作,或者这段代码已经完成了。
https://stackoverflow.com/questions/58532038
复制相似问题