Skip to content

Commit 1a545ff

Browse files
authored
Merge pull request #506 from realpython/python-built-in-exceptions
Sample code for the built-in exceptions article
2 parents b3055a0 + 9787055 commit 1a545ff

File tree

11 files changed

+152
-0
lines changed

11 files changed

+152
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python's Built-In Exceptions: A Walkthrough With Examples
2+
3+
This folder provides the code examples for the Real Python tutorial [Python's Built-In Exceptions: A Walkthrough With Examples](https://realpython.com/python-built-in-exceptions/).
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
def average_grade(grades):
2+
if not grades:
3+
raise ValueError("empty grades not allowed")
4+
return sum(grades) / len(grades)
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from abc import ABC
2+
3+
4+
class Bird(ABC):
5+
def swim(self):
6+
raise NotImplementedError("must be implemented in subclasses")
7+
8+
def fly(self):
9+
raise NotImplementedError("must be implemented in subclasses")
10+
11+
12+
class Duck(Bird):
13+
def swim(self):
14+
print("The duck is swimming")
15+
16+
def fly(self):
17+
print("The duck is flying")
18+
19+
20+
class Penguin(Bird):
21+
def swim(self):
22+
print("The penguin is swimming")
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# def fizzbuzz(number):
2+
# if number % 3 == 0:
3+
# return "fizz"
4+
# elif number % 5 == 0:
5+
# return "buzz"
6+
# elif number % 15 == 0:
7+
# return "fizz buzz"
8+
# else:
9+
# return number
10+
11+
12+
def fizzbuzz(number):
13+
if number % 15 == 0:
14+
return "fizz buzz"
15+
elif number % 3 == 0:
16+
return "fizz"
17+
elif number % 5 == 0:
18+
return "buzz"
19+
else:
20+
return number
21+
22+
23+
if __name__ == "__main__":
24+
assert fizzbuzz(9) == "fizz"
25+
assert fizzbuzz(10) == "buzz"
26+
assert fizzbuzz(15) == "fizz buzz"
27+
assert fizzbuzz(7) == 7
28+
print("All tests pass")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Uncomment the following code to see the error message
2+
# def greet(name):
3+
# print(f"Hello, {name}!")
4+
# print("Welcome to Real Python!")
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
try:
2+
with open("hello.txt", mode="x") as file:
3+
file.write("Hello, World!")
4+
except FileExistsError:
5+
print("The file already exists")
6+
7+
try:
8+
with open("hello.txt", mode="r") as file:
9+
print(file.read())
10+
except FileNotFoundError:
11+
print("The file doesn't exist.")

python-built-in-exceptions/ls.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import sys
2+
from pathlib import Path
3+
4+
if (args_count := len(sys.argv)) > 2:
5+
print(f"One argument expected, got {args_count - 1}")
6+
raise SystemExit(2)
7+
elif args_count < 2:
8+
print("You must specify the target directory")
9+
raise SystemExit(2)
10+
11+
target_dir = Path(sys.argv[1])
12+
13+
if not target_dir.is_dir():
14+
print("The target directory doesn't exist")
15+
raise SystemExit(1)
16+
17+
for entry in target_dir.iterdir():
18+
print(entry.name)

python-built-in-exceptions/mean.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def mean(grades):
2+
try:
3+
return sum(grades) / len(grades)
4+
except ZeroDivisionError:
5+
raise ValueError("mean() arg shouldn't be empty") from None
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
COLORS = {
2+
"Red": {"Hex": "#FF0000", "RGB": (255, 0, 0)},
3+
"Orange": {"Hex": "#FF7F00", "RGB": (255, 127, 0)},
4+
"Yellow": {"Hex": "#FFFF00", "RGB": (255, 255, 0)},
5+
"Green": {"Hex": "#00FF00", "RGB": (0, 255, 0)},
6+
"Blue": {"Hex": "#0000FF", "RGB": (0, 0, 255)},
7+
"Indigo": {"Hex": "#4B0082", "RGB": (75, 0, 130)},
8+
"Violet": {"Hex": "#8B00FF", "RGB": (139, 0, 255)},
9+
}
10+
11+
12+
class RainbowColor:
13+
def __init__(self, name="Red"):
14+
name = name.title()
15+
if name not in COLORS:
16+
raise ValueError(f"{name} is not a valid rainbow color")
17+
self.name = name
18+
19+
def as_hex(self):
20+
return COLORS[self.name]["Hex"]
21+
22+
def as_rgb(self):
23+
return COLORS[self.name]["RGB"]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class SquareIterator:
2+
def __init__(self, values):
3+
self.values = values
4+
self.index = 0
5+
6+
def __iter__(self):
7+
return self
8+
9+
def __next__(self):
10+
if self.index >= len(self.values):
11+
raise StopIteration
12+
square = self.values[self.index] ** 2
13+
self.index += 1
14+
return square

0 commit comments

Comments
 (0)