Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Determine grade based on marks - Python Program

Example 1 :

marks = int(input("Enter marks: ")) if marks >= 90: grade = 'A' elif marks >= 75: grade = 'B' elif marks >= 60: grade = 'C' elif marks >= 40: grade = 'D' else: grade = 'F' print("Grade:", grade)

Output

 
OUTPUT  :
Enter marks: 82
Grade: B
 

Example 2 :

def get_grade(marks): """ Determines the letter grade based on numerical marks. Args: marks (float): The numerical marks obtained by the student. Returns: str: The corresponding letter grade. """ if marks >= 90: return 'A' elif marks >= 80: return 'B' elif marks >= 70: return 'C' elif marks >= 60: return 'D' else: return 'F' # Get marks input from the user try: student_marks = float(input("Enter the student's marks (0-100): ")) if not (0 <= student_marks <= 100): print("Invalid input: Marks must be between 0 and 100.") else: # Determine and print the grade grade = get_grade(student_marks) print(f"The student's marks are: {student_marks}") print(f"The student's grade is: {grade}") except ValueError: print("Invalid input: Please enter a numerical value for marks.")

Output

 
OUTPUT  :
Enter the student's marks (0-100): 85
The student's marks are: 85.0
The student's grade is: B 

Explanation

This program defines a function get_grade that takes a student's numerical marks as input and returns a letter grade based on a predefined grading scale. The if-elif-else structure is used to evaluate the marks against different thresholds:

  • Marks 90 or above receive an 'A'.
  • Marks between 80 and 89 (inclusive) receive a 'B'.
  • Marks between 70 and 79 (inclusive) receive a 'C'.
  • Marks between 60 and 69 (inclusive) receive a 'D'.
  • Marks below 60 receive an 'F'.

The program then prompts the user to enter the student's marks, converts the input to a float, and includes error handling using a try-except block to catch ValueError if non-numerical input is provided. It also validates that the entered marks are within the expected range of 0 to 100. Finally, it calls the get_grade function and prints both the entered marks and the determined grade.