How to determine grade based on marks using Python if-elif-else

PythonPythonBeginner
Practice Now

Introduction

This tutorial will guide you through the process of implementing a grading system using Python's if-elif-else statements. You will learn how to determine a student's grade based on their marks, a common task in educational settings. By the end of this tutorial, you will have created a functional grading program that can be applied to real-world scenarios. This hands-on approach will strengthen your understanding of conditional statements in Python, which are fundamental building blocks for more complex programming logic.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/type_conversion("Type Conversion") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") python/FileHandlingGroup -.-> python/file_opening_closing("Opening and Closing Files") python/FileHandlingGroup -.-> python/file_reading_writing("Reading and Writing Files") subgraph Lab Skills python/type_conversion -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} python/conditional_statements -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} python/for_loops -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} python/function_definition -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} python/catching_exceptions -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} python/file_opening_closing -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} python/file_reading_writing -.-> lab-415721{{"How to determine grade based on marks using Python if-elif-else"}} end

Understanding Python Conditional Statements

Before we create our grading system, let us understand the basic conditional statements in Python. Conditional statements allow your program to make decisions based on specific conditions.

Creating Your First Python File

Let us start by creating a new Python file:

  1. In the WebIDE, click on the "File" menu at the top left
  2. Select "New File"
  3. Save the file as conditional_demo.py in the /home/labex/project directory

Basic If-Else Statement

In your conditional_demo.py file, write the following code:

## Basic if-else example
score = 75

if score >= 70:
    print("You passed the test!")
else:
    print("You need to study more.")

## Try changing the score to see different results

This simple program checks if the score variable is 70 or higher. If it is, it prints "You passed the test!". Otherwise, it prints "You need to study more."

Testing Your Code

To run your code, open a terminal in the WebIDE and execute:

python3 /home/labex/project/conditional_demo.py

You should see the output:

You passed the test!

Adding More Conditions with If-Elif-Else

Let us expand our example to handle more conditions using the if-elif-else structure:

## If-elif-else example
score = 85

if score >= 90:
    print("Excellent!")
elif score >= 80:
    print("Very good!")
elif score >= 70:
    print("Good!")
elif score >= 60:
    print("Satisfactory")
else:
    print("Needs improvement")

## Try different values for score to see different results

Save the file and run it again:

python3 /home/labex/project/conditional_demo.py

Output:

You passed the test!
Very good!

The if-elif-else structure evaluates conditions from top to bottom. Once a condition is true, its corresponding code block executes, and the rest of the conditions are skipped.

Understanding this flow is crucial for building our grading system in the next step.

Creating a Basic Grading System

Now that we understand conditional statements, let us build a simple grading system. We will create a function that converts numerical marks to letter grades.

Creating the Grading System File

  1. In the WebIDE, create a new file called grading_system.py
  2. Save it in the /home/labex/project directory

Implementing the Basic Grading Function

In your grading_system.py file, write the following code:

def get_grade(marks):
    """
    Convert numerical marks to letter grades.

    A: 90-100
    B: 80-89
    C: 70-79
    D: 60-69
    F: 0-59
    """
    if marks >= 90:
        return 'A'
    elif marks >= 80:
        return 'B'
    elif marks >= 70:
        return 'C'
    elif marks >= 60:
        return 'D'
    else:
        return 'F'

## Test the function with a few examples
test_marks = [95, 82, 75, 65, 45]

for mark in test_marks:
    grade = get_grade(mark)
    print(f"Marks: {mark} - Grade: {grade}")

This code creates a function get_grade() that takes a student's marks as input and returns the corresponding letter grade based on common grading thresholds.

Running Our Grading System

Let us test our grading system by running the code:

python3 /home/labex/project/grading_system.py

You should see output similar to:

Marks: 95 - Grade: A
Marks: 82 - Grade: B
Marks: 75 - Grade: C
Marks: 65 - Grade: D
Marks: 45 - Grade: F

Understanding the Code

Let us break down how this works:

  1. We defined a function called get_grade() that takes one parameter: marks
  2. Inside the function, we used if-elif-else statements to check the marks against different grade thresholds
  3. We created a list of test marks to demonstrate how the function works with different values
  4. We used a for loop to iterate through each mark, get its grade, and print the result

This basic grading system works well for standard cases, but what about edge cases? In the next step, we will improve our system to handle those.

Handling Edge Cases in Our Grading System

Our basic grading system works, but it does not account for edge cases such as:

  1. Invalid inputs (marks less than 0 or greater than 100)
  2. Non-numeric inputs

Let us improve our grading system to handle these scenarios.

Update the Grading System

Create a new file called improved_grading.py in the /home/labex/project directory with the following code:

def get_grade(marks):
    """
    Convert numerical marks to letter grades with input validation.

    A: 90-100
    B: 80-89
    C: 70-79
    D: 60-69
    F: 0-59

    Returns "Invalid marks" for inputs outside the range of 0-100
    """
    try:
        ## Convert to float in case input is a string number
        marks = float(marks)

        ## Check if marks are in valid range
        if marks < 0 or marks > 100:
            return "Invalid marks: must be between 0 and 100"
        elif marks >= 90:
            return 'A'
        elif marks >= 80:
            return 'B'
        elif marks >= 70:
            return 'C'
        elif marks >= 60:
            return 'D'
        else:
            return 'F'
    except ValueError:
        return "Invalid marks: not a number"

## Test the function with valid and invalid inputs
test_inputs = [95, 82, 75, 65, 45, -5, 105, "abc", "75"]

for value in test_inputs:
    grade = get_grade(value)
    print(f"Input: {value} - Result: {grade}")

Run the Improved Grading System

Execute the improved grading system:

python3 /home/labex/project/improved_grading.py

The output should look similar to:

Input: 95 - Result: A
Input: 82 - Result: B
Input: 75 - Result: C
Input: 65 - Result: D
Input: 45 - Result: F
Input: -5 - Result: Invalid marks: must be between 0 and 100
Input: 105 - Result: Invalid marks: must be between 0 and 100
Input: abc - Result: Invalid marks: not a number
Input: 75 - Result: C

Improvements Explained

Let us examine the improvements we made:

  1. Input Type Conversion: We use float() to convert the input to a number, allowing our function to accept string inputs like "75"

  2. Valid Range Check: We added a condition to check if the marks are within the valid range of 0-100

  3. Error Handling: We wrapped our code in a try-except block to catch ValueError exceptions that occur when non-numeric inputs are provided

  4. Detailed Error Messages: We return specific error messages to inform the user what went wrong instead of just returning an error code

These improvements make our grading system more robust by handling various edge cases gracefully. The program now provides helpful feedback when invalid inputs are encountered rather than crashing or producing incorrect results.

Enhancing the Grading System with Feedback Messages

Let us further improve our grading system by adding personalized feedback messages for each grade. This makes the system more informative and user-friendly.

Creating the Enhanced Grading System

Create a new file called enhanced_grading.py in the /home/labex/project directory:

def get_grade_with_feedback(marks):
    """
    Convert numerical marks to letter grades with personalized feedback.

    Returns a tuple containing the grade and a feedback message.
    """
    try:
        marks = float(marks)

        if marks < 0 or marks > 100:
            return (None, "Invalid marks: must be between 0 and 100")
        elif marks >= 90:
            return ('A', "Excellent! Outstanding performance.")
        elif marks >= 80:
            return ('B', "Very good! Above average performance.")
        elif marks >= 70:
            return ('C', "Good work! Average performance.")
        elif marks >= 60:
            return ('D', "Satisfactory. Below average but passing.")
        else:
            return ('F', "Needs improvement. Please study more.")
    except ValueError:
        return (None, "Invalid marks: not a number")

def format_report(student_name, marks, subject):
    """
    Generate a formatted report for a student.
    """
    grade, feedback = get_grade_with_feedback(marks)

    if grade is None:
        return f"Report for {student_name}: {feedback}"

    return f"""
Report Card
-----------
Student: {student_name}
Subject: {subject}
Marks: {marks}
Grade: {grade}
Feedback: {feedback}
"""

## Test the enhanced system with a few examples
students = [
    {"name": "Alice", "marks": 92, "subject": "Mathematics"},
    {"name": "Bob", "marks": 78, "subject": "Science"},
    {"name": "Charlie", "marks": 45, "subject": "History"},
    {"name": "David", "marks": "abc", "subject": "English"}
]

for student in students:
    report = format_report(student["name"], student["marks"], student["subject"])
    print(report)

Running the Enhanced Grading System

Execute the enhanced grading system:

python3 /home/labex/project/enhanced_grading.py

You should see output similar to:

Report Card
-----------
Student: Alice
Subject: Mathematics
Marks: 92
Grade: A
Feedback: Excellent! Outstanding performance.


Report Card
-----------
Student: Bob
Subject: Science
Marks: 78
Grade: C
Feedback: Good work! Average performance.


Report Card
-----------
Student: Charlie
Subject: History
Marks: 45
Grade: F
Feedback: Needs improvement. Please study more.

Report for David: Invalid marks: not a number

New Features Explained

Let us examine the enhancements we implemented:

  1. Personalized Feedback: Each grade now includes a specific feedback message that provides context and encouragement.

  2. Return Format: Our get_grade_with_feedback() function returns a tuple containing both the grade and the feedback message.

  3. Report Formatting: We created a new function format_report() that generates a well-structured report card for each student.

  4. Testing with Real-world Data: We used a list of dictionaries to simulate real student data, which is a common data structure in programming.

  5. Graceful Error Handling: The system still handles invalid inputs gracefully, but now presents the errors in a user-friendly format.

These enhancements make our grading system more practical for real-world use. The personalized feedback helps students understand their performance, while the formatted report provides a professional presentation of the results.

Applying the Grading System to a Real Dataset

Now, let us apply our grading system to a more realistic scenario. We will create a program that reads student data from a file, calculates grades, and writes a comprehensive report.

Creating a Sample Dataset

First, let us create a file with sample student data. Create a new file called student_data.csv in the /home/labex/project directory with the following content:

name,subject,marks
John,Mathematics,88
Emily,Mathematics,92
Michael,Mathematics,75
Sophia,Mathematics,68
Daniel,Mathematics,42
Olivia,Mathematics,95
William,Mathematics,73
Emma,Mathematics,60
James,Mathematics,79
Ava,Mathematics,85

Creating the Complete Grading Application

Now, create a new file called grading_application.py in the /home/labex/project directory:

def get_grade_with_feedback(marks):
    """
    Convert numerical marks to letter grades with personalized feedback.

    Returns a tuple containing the grade and a feedback message.
    """
    try:
        marks = float(marks)

        if marks < 0 or marks > 100:
            return (None, "Invalid marks: must be between 0 and 100")
        elif marks >= 90:
            return ('A', "Excellent! Outstanding performance.")
        elif marks >= 80:
            return ('B', "Very good! Above average performance.")
        elif marks >= 70:
            return ('C', "Good work! Average performance.")
        elif marks >= 60:
            return ('D', "Satisfactory. Below average but passing.")
        else:
            return ('F', "Needs improvement. Please study more.")
    except ValueError:
        return (None, "Invalid marks: not a number")

def process_student_data(input_filename, output_filename):
    """
    Process student data from a CSV file and generate a report.
    """
    try:
        ## Read the input file
        with open(input_filename, 'r') as file:
            lines = file.readlines()

        ## Skip the header line
        headers = lines[0].strip().split(',')
        data = [line.strip().split(',') for line in lines[1:]]

        ## Prepare the output
        output_lines = ["Student Grade Report\n", "=" * 20 + "\n\n"]

        ## Calculate statistics
        valid_marks = []
        grade_counts = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'F': 0, 'Invalid': 0}

        ## Process each student
        for student in data:
            name, subject, marks = student
            grade, feedback = get_grade_with_feedback(marks)

            if grade:
                valid_marks.append(float(marks))
                grade_counts[grade] += 1

                output_lines.append(f"Student: {name}\n")
                output_lines.append(f"Subject: {subject}\n")
                output_lines.append(f"Marks: {marks}\n")
                output_lines.append(f"Grade: {grade}\n")
                output_lines.append(f"Feedback: {feedback}\n\n")
            else:
                grade_counts['Invalid'] += 1
                output_lines.append(f"Student: {name}\n")
                output_lines.append(f"Subject: {subject}\n")
                output_lines.append(f"Error: {feedback}\n\n")

        ## Calculate statistics
        if valid_marks:
            average_mark = sum(valid_marks) / len(valid_marks)
            max_mark = max(valid_marks)
            min_mark = min(valid_marks)

            output_lines.append("Class Statistics\n")
            output_lines.append("-" * 15 + "\n")
            output_lines.append(f"Average Mark: {average_mark:.2f}\n")
            output_lines.append(f"Highest Mark: {max_mark:.1f}\n")
            output_lines.append(f"Lowest Mark: {min_mark:.1f}\n\n")

            output_lines.append("Grade Distribution\n")
            output_lines.append("-" * 17 + "\n")
            for grade, count in grade_counts.items():
                output_lines.append(f"{grade}: {count}\n")

        ## Write the output file
        with open(output_filename, 'w') as file:
            file.writelines(output_lines)

        print(f"Report successfully generated and saved to {output_filename}")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

## Run the application
input_file = "/home/labex/project/student_data.csv"
output_file = "/home/labex/project/grade_report.txt"

process_student_data(input_file, output_file)

## Display the report in the console as well
print("\nGenerated Report Contents:")
print("--------------------------")
with open(output_file, 'r') as file:
    print(file.read())

Running the Complete Application

Run the application:

python3 /home/labex/project/grading_application.py

The program will read the student data, calculate grades, generate a report, and display it in the console. You should see output similar to:

Report successfully generated and saved to /home/labex/project/grade_report.txt

Generated Report Contents:
--------------------------
Student Grade Report
====================

Student: John
Subject: Mathematics
Marks: 88
Grade: B
Feedback: Very good! Above average performance.

Student: Emily
Subject: Mathematics
Marks: 92
Grade: A
Feedback: Excellent! Outstanding performance.

...

Class Statistics
---------------
Average Mark: 75.70
Highest Mark: 95.0
Lowest Mark: 42.0

Grade Distribution
-----------------
A: 2
B: 2
C: 3
D: 1
F: 2
Invalid: 0

Examining the Report File

You can also check the generated report file:

cat /home/labex/project/grade_report.txt

The file should contain the same content that was displayed in the console.

Understanding the Complete Application

The complete grading application we created demonstrates several important programming concepts:

  1. File I/O: Reading data from and writing data to files
  2. Data Processing: Converting and analyzing raw data
  3. Statistics Calculation: Computing averages and finding minimum/maximum values
  4. Error Handling: Managing potential errors during file operations
  5. Formatting Output: Creating a well-structured, readable report

This application represents a real-world use case for our grading system, showing how Python's if-elif-else statements can be applied to solve practical problems in educational settings.

Summary

In this tutorial, you have successfully built a comprehensive grading system using Python's if-elif-else statements. Starting with basic conditional statements, you progressively enhanced your program to handle edge cases, provide personalized feedback, and process real student data.

Here are the key skills you have developed:

  1. Using if-elif-else statements to implement decision-making logic
  2. Validating user input and handling errors gracefully
  3. Providing meaningful feedback based on conditions
  4. Processing data from files and generating reports
  5. Calculating statistics from a dataset

These skills are fundamental to many programming tasks and can be applied to various real-world scenarios beyond grading systems. The principles of conditional logic that you have learned will serve as building blocks for more complex programs in your future Python projects.

Remember that good programming practices include:

  • Clear, descriptive variable and function names
  • Proper error handling
  • Well-structured and organized code
  • Helpful comments and documentation

Continue practicing by extending this grading system or applying what you have learned to new programming challenges!