绝对新手的Python编程第5章挑战4

时间:2012-11-13 16:55:08

标签: python python-3.x

挑战是改善之前的挑战,“谁是你的爸爸”(请参阅​​我的成功代码: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

显然暂时被困在一个小循环中,它不起作用。所有其他代码按预期工作。救命啊!

1 个答案:

答案 0 :(得分:3)

你循环遍在dict中的每个条目,并匹配该值,如果它不匹配,那么对于每个键值对,你打印它不匹配。

它相当于以下简化循环:

>>> for i in range(3):
...     if i == 5:
...         print(i)
...     else:
...         print('Not 5')
... 
Not 5
Not 5
Not 5

使用else: clause of the for loop代替,只有在您完成所有值后才会调用它;如果找到匹配项,请使用break

for ol_man, kid in paternal_pairs.items():
    if temp_son == kid:
        print("\nThe grandfather of", son, "is", ol_man)
        break
else:
    print("\nNo grandfather listed for", son)

else:循环一起使用时for子句如何工作的小型演示:

>>> for i in range(3):
...     if i == 1:
...         print(i)
...         break
... else:
...     print('Through')
... 
1
>>> for i in range(3):
...     if i == 5:
...         print(i)
...         break
... else:
...     print('Through')
... 
Through

在第一个示例中,我们使用break打破了循环,但在第二个示例中,我们从未到达break语句(i从不等于{{1} }})所以达到5子句并打印else: