首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python编程绝对入门第5章挑战4

Python编程绝对入门第5章挑战4
EN

Stack Overflow用户
提问于 2012-11-14 00:55:08
回答 1查看 4.1K关注 0票数 1

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

我不能让它工作。到目前为止,我的所有代码都可以在以下位置看到:http://pastebin.com/33KrEMhT

显然,我已经让这件事变得比需要的更加困难,现在我被困在了一个复杂的世界里。下面是我编写的代码:

代码语言:javascript
复制
# 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“后,我的输出:

代码语言:javascript
复制
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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-14 01:19:11

循环遍历字典中的每个条目,并匹配该值,如果不匹配,则对每个键-值对打印不匹配的值。

它相当于以下简化的循环:

代码语言:javascript
复制
>>> 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

代码语言:javascript
复制
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)

下面的小演示演示了在使用for循环时else:子句是如何工作的:

代码语言:javascript
复制
>>> 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从未等于5),因此到达了else:子句并输出了Through

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13365075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档