在 Python 中计算平均值和成绩

Zeeshan Afridi 2022年6月21日
在 Python 中计算平均值和成绩

无论你是想要解决基本学校作业的学生,​​还是正在寻找一些代码来为学校或大学构建评分系统,请阅读本文。

在 Python 中计算平均值和成绩

这个测试平均和成绩 Python 程序有两个主要任务。

  1. 计算 5 门科目的平均分。
  2. 根据平均分计算成绩。

代码示例:

# Calculate average
def calculate_average(total):
    return total / 5


# Grading scale
def find_score(grade):
    if 90 <= grade <= 100:
        return "A"
    elif 80 <= grade <= 89:
        return "B"
    elif 70 <= grade <= 79:
        return "C"
    elif 60 <= grade <= 69:
        return "D"
    else:
        return "F"


# Enter marks of 5 subjects
scores = []
for i in range(1, 6):
    score = int(input("Enter score {0}: ".format(i)))
    print("That's a(n): " + find_score(score))
    scores.append(score)

# sum of all subject marks
total = sum(scores)
avg_marks = calculate_average(total)
final_grade = find_score(avg_marks)

print("Average grade is: " + str(avg_marks))
print("That's a(n): " + str(final_grade))

输出:

Enter score 1: 99
That's a(n): A
Enter score 2: 98
That's a(n): A
Enter score 3: 78
That's a(n): C
Enter score 4: 95
That's a(n): A
Enter score 5: 87
That's a(n): B
Average grade is: 91.4
That's a(n): A

基本上我们在这个程序中有两个核心函数,find_score()calculate_average()find_score() 函数接收来自用户的参数作为科目分数,并且该函数相应地使用 if-else 条件逻辑对每个主题标记进行评分。

每个科目的科目分数存储在数组 scores[] 中,数组的总和传递给 calculate_average() 函数,该函数返回总分的平均值。

作者: Zeeshan Afridi
Zeeshan Afridi avatar Zeeshan Afridi avatar

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

LinkedIn