首页 > 解决方案 > 在 for 循环中添加了 else 语句,现在即使 if 为 true,也只会打印 else 部分

问题描述

这是我的第一门计算机科学课程,如果这个答案真的很明显,请原谅我。我写了下面的代码,它工作得很好。我只需要添加一个 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

标签: pythonloopsfor-loopif-statement

解决方案


每次循环都会评估该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:")

推荐阅读