Programs · Program 9-4
Q.Program 9-4: A program to calculate average marks of n students using a function where n is entered by the user.
Yanam BieapTextbookSubjective· 3mImportance★★★★★est
31% · 8/26 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Store the marks of n students (n entered by the user) in a list, pass the list to a function, and return total / n — for marks 78, 92, 65, 85 the average is 80.0.
The idea (average via a list + function). We do not know n in advance, which is exactly what lists are for: grow one element per student with append(). Separating the calculation into a function keeps the logic reusable and testable — it receives the list, totals it, and divides by the number of elements.
Program
def calc_average(marks):
"""Return the average of the values in the list marks."""
total = 0
for m in marks:
total += m
average = total / len(marks)
return average
# ---- main program ----
n = int(input("Enter the number of students: "))
marks = []
for i in range(n):
m = float(input("Enter marks of student " + str(i + 1) + ": "))
marks.append(m)
avg = calc_average(marks)
print("Average marks of", n, "students =", avg)
Sample run (expected output)
Enter the number of students: 4
Enter marks of student 1: 78
Enter marks of student 2: 92
Enter marks of student 3: 65
Enter marks of student 4: 85
Average marks of 4 students = 80.0
Trace of the total for the sample:
| Student | Marks | Running total |
|---|---|---|
| 1 | 78 | 78.0 |
| 2 | 92 | 170.0 |
| 3 | 65 | 235.0 |
| 4 | 85 | 320.0 |
Average = 320.0 / 4 = 80.0.
Key lines explained …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.