Python模块取消

时间:2015-02-18 19:49:13

标签: python module nested-loops

我知道你可以在Python中调用一个模块,但是你也可以在其中取消它吗?此代码应该只显示一次找到名称。它继续打印,直到我中断程序并从IDLE获取KeyboardInterrupt。我可以对我应该投入或改变的内容有所帮助吗? P.S。:我有Python 3.4.2

from array import *
s = ["Turner", "Philips", "Stevenson", "Jones", "Gonzalez",
"Whitaker", "Bruner", "Webster", "Foster", "Anderson",
"Klein", "Connors", "Rivers", "Wilson", "Duncan"]
g = [94, 82, 87, 78, 65,
90, 85, 97, 70, 100,
57, 88, 73, 92, 84]

s.sort()
for i in range(15):
    idx = int(i)

    studentList = s[idx]
    gradeList = g[idx]

    print(studentList, gradeList)

print("")
print("Student five: ", s[4], g[4])
print("Student ten: ", s[9], g[9])
print("Student fifteen: ", s[14], g[14])

gradeAverage = (g[0] + g[1] + g[2] + g[3] + g[4] + g[5] + g[6] + g[7] + g[8]
              + g[9] + g[10] + g[11] + g[12] + g[13] + g[14]) / 15

print("")
print("The average of the list of the grades is: ", gradeAverage)
print("The median of the list of grades is: ", g[7])
print("")

def byRank():
    studentFound = False
    index = 0
    searchValue = input("Student to be found: ")
    while(studentFound == False) & (index <= len(s) - 1):
        if s[index] == searchValue:
            studentFound == True
            print("Name", searchValue, "was found at index", index)
        else:
            index = index + 1
            print("Name not found. Searching...")
    print("Name is not in the array.")

byRank()

3 个答案:

答案 0 :(得分:1)

实现byRank()功能的正确方法是使用仅为此目的而制作的list.index()方法。尝试更像:

def byRank():
    searchValue = input("Student to be found: ")
    try:
        index = s.index(searchValue)
    except ValueError:
        print("Name is not in the array.")
    else:
        print("Name", searchValue, "was found at index", index)

答案 1 :(得分:0)

studentFound == True不会更改studentFound的值。使用单个=进行分配。或者只使用break来表示这样的简单案例。

您通常不使用while循环来迭代Python中的序列 - 相反,如果您不想使用内置的index方法,这样的事情会更好:< / p>

for index, candidate in enumerate(s):
    if candidate == searchValue:
        print("Name", searchValue, "was found at index", index)
        break

但一次只有一个问题。

答案 2 :(得分:0)

您的代码中有多处错误。最大的错误是你的while循环测试。以下是修复

def byRank():
    studentFound = False
    index = 0
    searchValue = raw_input("Student to be found: ")
    while not studentFound and index < len(s):
        if s[index] == searchValue:
            studentFound = True
            print("Name ", searchValue, " was found at index ", index)
        else:
            index += 1
            print("Name not found. Searching...")
    print("Name is not in the array.")

仅供参考 - 如果您愿意丢弃工作,Tom Hunt的答案是更好的编写代码的方式。