File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
Basics/Exercise/15_exception_handling Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## Exercise: Python Exception Handling
2
+
3
+ 1 . Write a Python program that takes a numeric grade from the user (between 0 and 100), and prints the corresponding letter grade:
4
+
5
+ ```
6
+ 90–100 → A
7
+ 80–89 → B
8
+ 70–79 → C
9
+ 60–69 → D
10
+ <60 → F
11
+ ```
12
+
13
+ 2 . Your program should handle the following exceptions:
14
+ - If the user enters a non-numeric value, catch the ` ValueError ` and display a user-friendly message.
15
+ - If the user enters a number outside the valid range (0 to 100), raise a ` ValueError ` yourself with a custom message.
16
+
17
+ 3 . Use the ` try–except–else–finally ` structure:
18
+ - ` try ` : Attempt to parse the input and compute the letter grade.
19
+ - ` except ` : Handle conversion errors and invalid ranges.
20
+ - ` else ` : Print the final grade if everything was successful.
21
+ - ` finally ` : Print a goodbye message like ` "Thank you for using the Grade Calculator. Goodbye!" ` no matter what.
22
+
23
+ [ Solution] ( https://gist.github.com/your-solution-link-here )
Original file line number Diff line number Diff line change
1
+ def calculate_letter_grade (score : int ) -> str :
2
+ if 90 <= score <= 100 :
3
+ return "A"
4
+ elif 80 <= score <= 89 :
5
+ return "B"
6
+ elif 70 <= score <= 79 :
7
+ return "C"
8
+ elif 60 <= score <= 69 :
9
+ return "D"
10
+ else :
11
+ return "F"
12
+
13
+ try :
14
+ user_input = input ("Enter your grade (0–100): " )
15
+ grade = int (user_input )
16
+
17
+ if grade < 0 or grade > 100 :
18
+ raise ValueError ("Grade must be between 0 and 100." )
19
+
20
+ letter = calculate_letter_grade (grade )
21
+ except ValueError as ve :
22
+ print (f"⚠️ { ve } " )
23
+ else :
24
+ print (f"✅ Your letter grade is: { letter } " )
25
+ finally :
26
+ print ("🎓 Thank you for using the Grade Calculator. Goodbye!" )
You can’t perform that action at this time.
0 commit comments