Python模块取消

2024-10-04 03:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道可以在Python中调用模块本身,但也可以在模块本身中取消它吗?此代码应该只显示一次找到的名称。它继续打印,直到我用中断程序并从空闲状态获取KeyboardInterrupt。你能帮我换些什么吗?附言:我有python3.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()

Tags: 模块ofthenameinindexisarray
3条回答

studentFound == True不会更改studentFound的值。使用单个=进行赋值。或者用break来处理这样一个简单的例子。你知道吗

在Python中,通常不使用while循环来迭代序列—相反,如果不想使用内置的index方法,这样的方法会更好:

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

但一次只能解决一个问题。你知道吗

实现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)

代码中有几个错误。最大的错误是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.")

仅供参考汤姆亨特的答案是更好的方式来编写代码,如果你愿意放弃你的工作。你知道吗

相关问题 更多 >