Python program to obtain the marks in computer of some student and find mean median and mode

# Function to get marks from user
def get_marks():
    marks = []
    num_students = int(input("Enter the number of students: "))
    for i in range(num_students):
        mark = int(input(f"Enter the mark for student {i+1}: "))
        marks.append(mark)
    return marks

# Function to calculate mean
def calculate_mean(marks):
    return sum(marks) / len(marks)

# Function to calculate median
def calculate_median(marks):
    marks.sort()
    n = len(marks)
    mid = n // 2
    if n % 2 == 0:  # even number of elements
        median = (marks[mid - 1] + marks[mid]) / 2
    else:  # odd number of elements
        median = marks[mid]
    return median

# Function to calculate mode
def calculate_mode(marks):
    frequency = {}
    for mark in marks:
        if mark in frequency:
            frequency[mark] += 1
        else:
            frequency[mark] = 1
    max_count = max(frequency.values())
    modes = [key for key, value in frequency.items() if value == max_count]
    
    if len(modes) == len(frequency):
        return "No unique mode found"
    else:
        return modes

# Main program
def main():
    marks = get_marks()
    mean = calculate_mean(marks)
    median = calculate_median(marks)
    mode = calculate_mode(marks)
    print("\nMarks: ", marks)
    print(f"Mean: {mean}")
    print(f"Median: {median}")
    print(f"Mode: {mode}")

# Run the main function
if __name__ == "__main__":
    main()
Output:
Enter the number of students: 5
Enter the mark for student 1: 85
Enter the mark for student 2: 90
Enter the mark for student 3: 75
Enter the mark for student 4: 85
Enter the mark for student 5: 90

Marks:  [85, 90, 75, 85, 90]
Mean: 85.0
Median: 85
Mode: [85, 90]

Explanation

  1. get_marks function:
    • Prompts the user to enter the number of students.
    • Iteratively collects marks for each student and stores them in a list.
  2. calculate_mean function:
    • Computes the mean by dividing the sum of all marks by the number of marks.
  3. calculate_median function:
    • Sorts the marks list.
    • Calculates the median by finding the middle element(s). If the number of elements is even, it takes the average of the two middle elements.
  4. calculate_mode function:
    • Counts the frequency of each mark using a dictionary.
    • Finds the mark(s) with the highest frequency. If all marks are unique, it indicates that there is no unique mode.
  5. main function:
    • Calls the above functions to get marks and calculate statistics.
    • Prints the marks, mean, median, and mode.

Leave a Reply

Your email address will not be published. Required fields are marked *