【问题标题】:Python Programming for Absolute Beginner Chapter 5 Challenge 4 [closed]绝对初学者的 Python 编程第 5 章挑战 4 [关闭]
【发布时间】:2012-11-13 16:55:07
【问题描述】:

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

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

【问题讨论】:

  • @hamza: 没有错误,我想,只是字典中每个条目的 No grandfather listed for d 行...

标签: python python-3.x


【解决方案1】:

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

相当于下面的简化循环:

>>> 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 永远不等于5)所以else:到达子句并打印Through

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2021-05-30
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多