Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
66 lines (51 loc) · 2 KB

File metadata and controls

66 lines (51 loc) · 2 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Divisor cannot be 0.")
return dividend / divisor
grades = [] # Imagine we have no grades yet
# average = divide(sum(grades) / len(grades)) # Error!
try:
average = divide(sum(grades), len(grades))
print(average)
except ZeroDivisionError as e:
print(e)
# Much friendlier error message because now we're dealing with it
# In a "students and grades" context, not purely in a mathematical context
# I.e. it doesn't make sense to put "There are no grades yet in your list"
# inside the `divide` function, because you could be dividing something
# that isn't grades, in another program.
print("There are no grades yet in your list.")
# -- Built-in errors --
# TypeError: something was the wrong type
# ValueError: something had the wrong value
# RuntimeError: most other things
# Full list of built-in errors: https://docs.python.org/3/library/exceptions.html
# -- Doing something if no error is raised --
grades = [90, 100, 85]
try:
average = divide(sum(grades), len(grades))
except ZeroDivisionError:
print("There are no grades yet in your list.")
else:
print(f"The average was {average}")
# -- Doing something no matter what --
# This is particularly useful when dealing with resources that you open and then must close
# The `finally` part always runs, so you could use it to close things down
# You can also use it to print something at the end of your try-block if you like.
students = [
{"name": "Bob", "grades": [75, 90]},
{"name": "Rolf", "grades": []},
{"name": "Jen", "grades": [100, 90]},
]
try:
for student in students:
name = student["name"]
grades = student["grades"]
average = divide(sum(grades), len(grades))
print(f"{name} averaged {average}.")
except ZeroDivisionError:
print(f"ERROR: {name} has no grades!")
else:
print("-- All student averages calculated --")
finally:
print("-- End of student average calculation --")
Morty Proxy This is a proxified and sanitized view of the page, visit original site.