Statement
Solution
Exercise 2.2: Grade Calculator
Create a program that calculates a student's letter grade based on their score.
Your program should:
- Take a score (0-100) as input.
- Check if the input is Invalid (less than 0 or greater than 100).
- If valid, determine the grade using these rules:
- A: 90 and above
- B: 80 to 89
- C: 70 to 79
- D: 60 to 69
- F: Below 60
Sample Interaction:
Input
Output
85
Enter score: 85
--------------------
Grade: B
105
Enter score: 105
--------------------
Invalid score. Please enter 0-100.
Solution
We use if, elif (else if), and else to check multiple conditions in order.
# 1. Get User Input
score = int(input("Enter score: "))
print("-" * 20)
# 2. Check for Validation first
if score < 0 or score > 100:
print("Invalid score. Please enter 0-100.")
# 3. Check Grades using ELIF
elif score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Key Concepts:
elifallows you to check a new condition if the previousifwas False.- Python checks conditions from top to bottom. As soon as one is True, it skips the rest.
orallows us to check if the score is out of bounds in either direction.
Test Console
Run code to see output...