【问题标题】:Added an else statement inside a for loop, and now only the else part prints even when if is true在 for 循环中添加了 else 语句,现在即使 if 为 true,也只会打印 else 部分
【发布时间】:2019-12-05 01:25:12
【问题描述】:

这是我第一次参加计算机科学课程,如果这个答案真的很明显,请原谅我。我写了下面的代码,它工作得很好。我只需要添加一条 else 语句来说明无效的名称输入。

这是之前的:

    mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
    myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]

    name = input("Please enter a name:")
    #search through mynames to find the name
    while name!='q':
        for x in range(20):
            if mynames[x] == name:
                 print(mynames[x], "scored", myscores[x])
        name = input("Please enter a name:")

这是之后:

     mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
    myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]

    name = input("Please enter a name:")
    #search through mynames to find the name
    while name!='q':
        for x in range(20):
            if mynames[x] == name:
                print(mynames[x], "scored", myscores[x])
            else:
                print("That name is not in this class.")
                name = input("Please enter a name:")
        name = input("Please enter a name:")

它只是不停地打印“那个名字不在这个类中。”无论我输入什么。SOS

【问题讨论】:

  • 它继续打印,因为它在循环的每次迭代之前执行else,其中mynames[x] != name
  • 你试过输入Naomi吗?
  • 您应该考虑使用字典。 dict(zip(mynames, myscores)) 将从您的列表中创建一个。从那里查找值要容易得多。
  • 从python退一步,想想逻辑。您的代码当前要求name,如果该名称不是q,那么它会检查mynames 列表的第一个索引是否与该名称相同。如果不是,则表示该名称不在该类中。这样想有帮助吗?

标签: python loops for-loop if-statement


【解决方案1】:

if 语句每次循环都会被求值,所以你需要跟踪是否找到了名字,然后只在最后打印。

例如:

    while name!='q':
        found = False
        for x in range(20):
            if mynames[x] == name:
                print(mynames[x], "scored", myscores[x])
                found = True
                break
         if not found:
             print("That name is not in this class.")
         name = input("Please enter a name:")

【讨论】:

  • 您不必保留found 标志。 Python 对此有一个特殊的 for..else 构造。
  • 这是一个很好的观点,虽然我认为 found 标志对于编程新手来说可能更容易理解
【解决方案2】:

我认为您将真正受益于使用dictionary。请参阅以下示例。

mynames = ['Naomi', 'James', 'Amos', 'Alex', 'Bobbie', 'Josephus', 'Fred', 'Camina', 'Julie', 'Prax', 'Christien', 'Anderson', 'Havelock', 'Ashford', 'Bull', 'Anna', 'Arjun', 'Souther', 'Carissa', 'Samara']
myscores = [89, 98, 76, 76, 84, 93, 82, 64, 63, 75, 76, 86, 96, 75, 86, 100, 99, 87, 84, 94]
name_score_map = dict(zip(mynames, myscores))

name = input("Please enter a name:")
#search through mynames to find the name
while name!='q':
    if name in name_score_map:
        print(name, "scored", name_score_map[name])
    else:
        print("That name is not in this class.")
    name = input("Please enter a name:")

在第一行中,我们构建了一个字典,将学生的姓名映射到他们获得的分数。这消除了遍历mynames 列表以查看名称是否在其中然后使用相应索引来获取分数的需要。这实际上消除了您在每次迭代中执行print("That name is not in this class.") 时遇到的问题,其中mynames[x] != name

然后我们可以通过查看名称是否在name_score_map 中来检查名称是否有分数。这将搜索的时间复杂度从 O(n) 降低到 O(1)。然后,我们可以简单地使用名称作为name_score_map 字典的键来获取分数。

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多