挑战是通过添加让用户输入名称并取回祖父的选项来改进先前的挑战“谁是你的爸爸”(参见我的成功代码: http: //pastebin.com/AU2aRWHk )。程序仍然应该只使用一本父子对的字典。
我不能让它工作。到目前为止,我的整个代码都可以在以下位置看到: http: //pastebin.com/33KrEMhT
我显然让这种方式变得比它需要的更困难,现在我被困在一个复杂的世界中。这是我 F'd up 的代码:
# create dictionary
paternal_pairs ={"a": "b",
"b": "c",
"c": "d"}
# initialize variables
choice = None
# program's user interface
while choice != 0:
print(
"""
Who's Yo Daddy:
2 - Look Up Grandfather of a Son
"""
)
choice = input("What would you like to do?: ")
print()
# look up grandfather of a son
if choice == "2":
son = input("What is the son's name?: ")
# verify input exists in dictionary
if son in paternal_pairs.values():
for dad, boy in paternal_pairs.items():
if dad == son:
temp_son = dad
for ol_man, kid in paternal_pairs.items():
if temp_son == kid:
print("\nThe grandfather of", son, "is", ol_man)
else:
print("\nNo grandfather listed for", son)
else:
print("\nNo grandfather listed for", son)
# if input does not exist in dictionary:
else:
print("Sorry, that son is not listed. Try adding a father-son pair.")
选择“2”后,我的输出:
What is the son's name?: d
No grandfather listed for d
No grandfather listed for d
No grandfather listed for d
No grandfather listed for d
No grandfather listed for d
No grandfather listed for d
No grandfather listed for d
No grandfather listed for d
显然暂时被困在一个小循环中,它不起作用。所有其他代码都按预期工作。帮助!