在 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