首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python模块取消

Python模块取消
EN

Stack Overflow用户
提问于 2015-02-18 19:49:13
回答 3查看 54关注 0票数 0

我知道,您可以在Python内部调用一个模块,但也可以在其内部取消它吗?这段代码应该只显示一次已找到的名称。它继续打印,直到我中断程序和从空闲的KeyboardInterrupt。我能帮些忙吗?我该放些什么或换什么?P.S.:我有Python 3.4.2

代码语言:javascript
复制
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()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-02-18 19:57:34

实现byRank()函数的正确方法是使用为此目的创建的list.index()方法。试一试更像是:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-02-18 19:57:10

studentFound == True不更改studentFound的值。使用单个=进行赋值。或者只需在这样一个简单的情况下使用break

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

代码语言:javascript
复制
for index, candidate in enumerate(s):
    if candidate == searchValue:
        print("Name", searchValue, "was found at index", index)
        break

但一次只有一个问题。

票数 0
EN

Stack Overflow用户

发布于 2015-02-18 19:59:14

代码中有几个错误。最大的错误是while循环测试。以下是修复方法

代码语言:javascript
复制
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.")

FYI --汤姆·亨特的答案是如果你愿意放弃你的工作的话,写代码的更好的方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28592582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档