Challenge is to improve a previous challenge, “Who’s Your Daddy” (see my successful code: http://pastebin.com/AU2aRWHk) by adding a choice that let’s the user enter a name and get back a grandfather. Program should still only use one dictionary of son-father pairs.
I cannot get this to work. My entire code so far can be seen at: http://pastebin.com/33KrEMhT
I’ve obviously made this WAY more difficult than it need to be and am now trapped in a world of complexity. Here’s code I’ve 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.")
After choosing “2”, my output:
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
Obviously temporarily trapped in a small loop and it doesn’t work. All other code works as expected. Help!
You loop over each entry in the dict, and match the value, and if it doesn’t match, then for each key-value pair you print that it doesn’t match.
It is the equivalent of the following simplified loop:
Use the
else:clause of theforloop instead, it’ll only be invoked if you completed going through all the values; use abreakif you find a match:A small demonstration of how the
else:clause works when used with aforloop:In the first example, we broke out of the loop with a
break, but in the second example we never reached thebreakstatement (inever was equal to5) so theelse:clause is reached andThroughis printed.