Introduction:
This Python code calculates the average marks of a given number of students using a function. It takes input from the user for the number of students and their respective marks, and then calculates and displays the average marks.
Code:
#Function to calculate average marks of n students
def computeAverage(list1,n):
#initialize total
total = 0
for marks in list1:
#add marks to total
total = total + marks
average = total / n
return average
#create an empty list
list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
#append marks in the list
list1.append(marks)
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)
Logic:
- Define a function ‘computeAverage’ that takes a list of marks and the number of students as input.
- Initialize a variable ‘total’ to 0.
- Iterate over each mark in the list and add it to the ‘total’ variable.
- Calculate the average by dividing the total by the number of students.
- Return the average.
- Create an empty list ‘list1’.
- Take input from the user for the number of students.
- Use a loop to iterate for ‘n’ students.
- Take input from the user for the marks of each student and append it to ‘list1’.
- Call the ‘computeAverage’ function with ‘list1’ and ‘n’ as arguments and store the result in the ‘average’ variable.
- Display the average marks to the user.
Output:
>> How many students marks you want to enter: 5
>> Enter marks of student 1 :100
>> Enter marks of student 2 :98
>> Enter marks of student 3 :89
>> Enter marks of student 4 :78
>> Enter marks of student 5 :65
>> Average marks of 5 students is: 86.0