チャレンジは、ユーザーが名前を入力しておじいさんを取り戻すという選択肢を追加することで、以前のチャレンジ「誰があなたのパパですか」(私の成功したコードを参照してください: http://pastebin.com/AU2aRWHk ) を改善することです。プログラムは、息子と父親のペアの辞書を 1 つだけ使用する必要があります。
これを機能させることはできません。これまでのコード全体は、http: //pastebin.com/33KrEMhTで見ることができます。
私は明らかにこの方法を必要以上に難しくしてしまい、今では複雑な世界に閉じ込められています。ここに私がF'dアップしたコードがあります:
# 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
明らかに一時的に小さなループに閉じ込められ、機能しません。他のすべてのコードは期待どおりに機能します。ヘルプ!