在Python中创建一个for循环来检查列表值

我的家庭作业有问题。我需要创建一个 for 循环来计算某个值在列表中出现的次数。这是代码:


def get_test_scores():

    tests = []

    for i in range(SIZE):

        test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))

        while (test_score <0) or (test_score >100):

            print("ERROR!")

            test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))        

    tests.append(test_score)    

    return tests


def find_perfect(tests):

    count = 0

    for test_score in tests:

        if test_score == 100:

            count += 1

    return count

我无法获得计数值来反映我输入了多少个 100


阿晨1998
浏览 113回答 3
3回答

蛊毒传说

当您处理此类事情(无论是作业还是生产代码)时,最好测试每个单独的函数以确保它们正常工作。例如,尝试find_perfect使用不同的(硬编码的)列表运行;你会发现它每次都能得到正确的答案。现在尝试测试get_test_scores并打印输出。哎呀!您的问题是您仅附加最后的测试分数。该线tests.append(test_score)应该位于for循环内部。

紫衣仙女

你tests.append(test_score)会发生一次,因为它在 for 循环之外,试试这个:def get_test_scores():&nbsp; &nbsp; tests = []&nbsp; &nbsp; for i in range(SIZE):&nbsp; &nbsp; &nbsp; &nbsp; test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))&nbsp; &nbsp; &nbsp; &nbsp; while (test_score <0) or (test_score >100):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("ERROR!")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; tests.append(test_score)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return tests顺便说一句,我认为值得快速计算你有多少个 100 并且不再迭代,在 python 中,你可以从像 tuple 这样的函数返回很少的值,例如:def get_test_scores():&nbsp; &nbsp; tests = []&nbsp; &nbsp; count = 0&nbsp; &nbsp; for i in range(SIZE):&nbsp; &nbsp; &nbsp; &nbsp; test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))&nbsp; &nbsp; &nbsp; &nbsp; while (test_score <0) or (test_score >100):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("ERROR!")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; test_score = int(input("Enter test score #"+str(i+1)+" in the range 0-100: "))&nbsp; &nbsp; &nbsp; &nbsp; if test_score == 100:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count += 1&nbsp; &nbsp; &nbsp; &nbsp; tests.append(test_score)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return count, tests用法 :count, scores = get_test_scores()count 是一个数字,scores 是分数列表

DIEA

tests.append(test_score)通过在 for 循环之前添加 tab 来使其内部
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python