Table of Contents

Calculate Average Marks of Students

Example Description
This code takes input from the user for the number of students and their respective marks, then calculates and displays the average marks.

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:

  1. Define a function ‘computeAverage’ that takes a list of marks and the number of students as input.
  2. Initialize a variable ‘total’ to 0.
  3. Iterate over each mark in the list and add it to the ‘total’ variable.
  4. Calculate the average by dividing the total by the number of students.
  5. Return the average.
  6. Create an empty list ‘list1’.
  7. Take input from the user for the number of students.
  8. Use a loop to iterate for ‘n’ students.
  9. Take input from the user for the marks of each student and append it to ‘list1’.
  10. Call the ‘computeAverage’ function with ‘list1’ and ‘n’ as arguments and store the result in the ‘average’ variable.
  11. 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