Skip to content

Commit da7fa19

Browse files
committed
adds python file equivalents of notebooks
1 parent b644fbf commit da7fa19

File tree

2 files changed

+190
-0
lines changed

2 files changed

+190
-0
lines changed
+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# Fun with Exceptions
2+
# Exceptions handle errors that you can't know about until running the application
3+
#
4+
# They are different than errors that are known about in advance
5+
6+
print("let's do something totally wrong. See if you can spot me in the output!")
7+
print("Too many parentheses"))
8+
9+
10+
print("More wrongness. Do I get printed?")
11+
print("Who has ever "messed up" quotations marks?")
12+
13+
14+
# Notice how both failed to execute AND didn't show the initial print.
15+
#
16+
# That's what happens with syntax errors.
17+
#
18+
# But how about logical errors that ARE syntactically correct?
19+
20+
print("What happens now? Do you see me printed?")
21+
value = 1/0
22+
23+
# Got a ZeroDivisionError at runtime
24+
#
25+
# Notice intial print DID display this time
26+
#
27+
# Check out the error
28+
#
29+
# Getting a descriptive error is good
30+
#
31+
# WAY better than getting a non-descriptive or even non-existent one
32+
#
33+
# So always pay attention to anything an error is telling you
34+
35+
36+
# You can handle these errors in your code
37+
38+
try:
39+
print("Divide by zero again", 1 / 0)
40+
except ZeroDivisionError:
41+
print("Don't divide by zero silly.")
42+
43+
print("handled the exception above, carrying on")
44+
45+
46+
# Notice that we "caught" a specific exception. It is a best practice to only catch specific exceptions
47+
#
48+
# To put it another way it is a VERY BAD THING to catch generic exceptions Here is why that's considered an anti-pattern
49+
50+
51+
try:
52+
print("Divide by zero again", 1 / "spam")
53+
except:
54+
print("Don't divide by zero silly.")
55+
56+
print("Total lie!. The problem was not dividing by zero. It was a type error")
57+
58+
59+
# variation on previous step
60+
61+
try:
62+
print("Divide by zero again", 1 / "spam")
63+
except Exception:
64+
print("Don't divide by zero silly.")
65+
66+
print("Still wrong. Handling the base Exception is a 'catch all'")
67+
68+
# If you must handle every exception then make sure to retain the relevant error info.
69+
#
70+
# For example, you may have requirement that end user never sees a program error.
71+
#
72+
# In that case make sure to log/record the error details and then present something more palatable to end user
73+
74+
75+
try:
76+
spam = "nonsense" / 42
77+
except ZeroDivisionError:
78+
print("Don't divide by zero silly.")
79+
except Exception as e: # notice we can refer to the exception using 'as'
80+
# log the exception somewhere, probably including the stack trace
81+
print("So sorry end user. Something broke!")
82+
83+
# Python also allows you do a couple more things with exceptions
84+
#
85+
# One is an 'else' block which runs when there was NOT an exception This is not that commonly used but every now and then is helpful
86+
87+
88+
print("Attempting to create message")
89+
try:
90+
message = "nothing" + "wrong" + "here"
91+
except TypeError:
92+
print("Unable to create message")
93+
else:
94+
print("Message successfully created")
95+
96+
# The last piece is the 'finally' block which is run no matter what happened
97+
98+
99+
print("prepare for breakage")
100+
101+
try:
102+
value = True + " nonsense" # change to str(True) and see what happens
103+
except TypeError as e:
104+
print(f"Something broke! Details: {e}")
105+
else:
106+
print(f"smooth sailing. value is {value}")
107+
finally:
108+
print("clean up mess as needed")
109+
110+
# you can raise exceptions intentionally as well
111+
#
112+
# If there's no better choice can use the Generic Exception
113+
#
114+
# It's a best practice to choose the most appropriate type of Error
115+
116+
117+
age = -10
118+
119+
if age < 0:
120+
raise ValueError("Invalid age - must be greater than or equal to zero")
121+
122+
123+
raise Exception("Something bad happened")
124+
125+
# You can also create your own Exception types.
126+
#
127+
# This will make more sense when we cover Classes next session
128+
#
129+
# but here's a sneak peek
130+
131+
132+
133+
class SocialDistanceError(Exception):
134+
def __init__(self, distance):
135+
super().__init__(f"Stay 6 feet away, not {distance}")
136+
137+
138+
distance_feet = 4
139+
140+
if distance_feet < 6:
141+
raise SocialDistanceError(distance_feet)

class-03/demo/file-io/file_io.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Files in Python
2+
file = open('assets/spam.txt')
3+
print(file)
4+
contents = file.read()
5+
print(contents)
6+
7+
# Closing the file
8+
# The file is still "open"
9+
print('Is file closed?', file.closed)
10+
# let's explicitly close it
11+
file.close()
12+
print('Is file closed?', file.closed)
13+
14+
# often you don't need to worry about closing the file since Python usually handles that.
15+
# but words like 'often' and 'usually' are a programmers constant foe
16+
# fortunately, there's an easy way to make sure that it always gets closed up properly
17+
with open('assets/spam.txt') as file:
18+
print(file.read())
19+
20+
print('file is closed?', file.closed)
21+
22+
23+
# That with key word there creates something called a context manager
24+
# They are a more advanced topic, but you'll see them used a lot with files because they are so dang handy
25+
# Quick documentation with help and dir
26+
# You can see the attributes of file object easy enough
27+
help(file)
28+
dir(file)
29+
30+
31+
# File modes
32+
# When you open a file you supply a 'mode' - the default mode is 'r' for 'read'
33+
# so open('somefile.txt') is the same as open('somefile.txt','r')
34+
# You pretty much have to memorize the modes
35+
# Luckilly there aren't that many. Here are the most popular
36+
# r for read
37+
# w for write
38+
# a for append
39+
help(open)
40+
41+
with open('assets/brain.jpg', 'rb') as f:
42+
contents = f.read()
43+
44+
for x in contents[:128]:
45+
print(type(contents))
46+
47+
with open('assets/brain.copy.jpg', 'wb') as f2:
48+
f2.write(contents)
49+

0 commit comments

Comments
 (0)