Founding Batch Offer · HLD · LLD · System Design at ₹799 until 30 Nov

Grade Calculator in Python

Check marks before assigning a letter grade in Python. A first conditional ladder shows why high cutoffs come first and why 107% must not receive an A.

BeginnerConditional ProgramsExample 1 of 20
grade-calculator.py
1# Program to calculate grade from percentage
2
3percentage = float(input("Enter your percentage: "))
4
5if percentage < 0 or percentage > 100:
6 print("Invalid percentage. Please enter a value between 0 and 100.")
7else:
8 if percentage >= 90:
9 grade = 'A'
10 elif percentage >= 80:
11 grade = 'B'
12 elif percentage >= 70:
13 grade = 'C'
14 elif percentage >= 60:
15 grade = 'D'
16 else:
17 grade = 'F'
18
19 print(f"Your grade is: {grade}")

Output

Your grade is: B

85 is below 90 but at least 80, so the selected grade is B.

In this one

  • Order grade thresholds correctly
  • Validate a percentage range
  • Trace the first matching elif

How it works

  1. 1

    Read percentage and reject values outside 0–100.

  2. 2

    Test thresholds in descending order and assign one grade.

  3. 3

    Print grade only inside the valid-input branch.

Edge cases

Exact cutoff

Enter 90.

>= includes the boundary, so the grade is A.

Out-of-range mark

Enter 107.

The validation message runs and no grade is assigned or printed.

What's going on

Walk the thresholds from the top: >= 90, then >= 80, then >= 70, then >= 60. Reverse that order and 95 matches the lowest passing threshold first. elif stops at the first hit, not the most generous hit.

The outer condition rejects percentages below zero or above 100. Inside the valid range, 85 misses 90 and reaches B. Later branches do not run, so grade receives one value before the final print.

Boundary tests tell you more than random middle values. Try 89.9, 90, and 100. This program uses a sample grading policy; change the cutoffs to match a real course rather than treating these letters as a universal rule.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why test >= 90 before >= 60?

Pick an answer to check it.

Question 2

What grade does 80 receive?

Pick an answer to check it.

Questions people ask

Why test >= 90 before >= 60?

The first matching branch wins, so higher grades must be checked first.

What grade does 80 receive?

B, because it fails >= 90 and satisfies >= 80.

Why put printing inside the valid branch?

Invalid input never assigns grade, so printing it outside would risk using an undefined name.