gpt4 book ai didi

绝对初学者的Python编程第5章挑战4

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:47 25 4
gpt4 key购买 nike

<分区>

挑战是通过添加一个让用户输入姓名并取回祖父的选项来改进之前的挑战“谁是你的爸爸”(参见我的成功代码:http://pastebin.com/AU2aRWHk)。程序应该仍然只使用一个父子对字典。

我无法让它工作。到目前为止我的整个代码可以在以下位置看到:http://pastebin.com/33KrEMhT

显然,我已经使这种方式变得比需要的更困难,现在我陷入了一个复杂的世界。这是我编写的代码:

# 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

很明显暂时陷入了一个小循环,并没有起作用。所有其他代码都按预期工作。帮助!

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com