无法弄清楚为什么程序不提供输出

时间:2018-10-31 19:40:59

标签: python python-3.x

我编写了一个程序,询问用户他需要计算平均成绩的等级数。但是我不明白为什么它没有给我输出。这是我的代码:

def input_data():
    number_of_smth = int(input())

    return number_of_smth

def answer_output(array, avg):
    print("The average of ", len(array), " grades is ", avg)
    print("High is: ", array[0], "; Low is: ", len(array)-1)

def array_init(n):
    array = []
    for element in range(0, n):
        array[element] = input_data()

    return array

def sorting(array):
    for j in range(len(array) - 1, 0, -1):
        for i in range(j):
            if array[i] > array[i + 1]:
               temp = array[i]
               array[i] = array[i + 1]
               array[i + 1] = temp

    return array

def average(array):
    sum_of_array_elements = 0
    for element in range(0, len(array), 1):
        sum_of_array_elements += array[element]

    return sum_of_array_elements / len(array)

def main():
    print("Please type the number of grades")
    grades_list = sorting(array_init(input_data()))
    answer_output(grades_list, average(grades_list))

main()

1 个答案:

答案 0 :(得分:0)

array_init中存在错误。第array[element] = input_data()行以IndexError失败。发生这种情况是因为array为空。在位置element上没有要分配的内容。您可以改用array.append(input_data())在列表中创建所需的项目。通过使用此类内置函数python,可以大大提高可读性和可维护性。

def answer_output(array, avg):
    print("The average of ", len(array), " grades is ", avg)
    print("High is: ", array[0], "; Low is: ", len(array)-1)

def main():
    print("Please type the number of grades")
    number_of_grades = int(input())
    # use list comprehension to read in the numbers
    grades_list = [int(input()) for i in range(number_of_grades)]
    # sort the list    
    grades_list.sort()
    # average is the sum over the count
    average_grade = sum(grades_list) / len(grades_list)
    # print out the results
    answer_output(grades_list, average_grade)