-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConditional___Event_Driven_Programming_PythonApplication.py
More file actions
403 lines (275 loc) · 11.5 KB
/
Copy pathConditional___Event_Driven_Programming_PythonApplication.py
File metadata and controls
403 lines (275 loc) · 11.5 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# If statements
# for if/elif statements the most restrictive conditons should go near the top of the chain to make sure the correct decision is made
print("If Statements")
print()
dietry_restriction = set(["Meat","Cheese"])
# dietry_restriction = set(["Meat",""])
# dietry_restriction = set(["",""])
if 'Meat' and 'Cheese' in dietry_restriction: # first conditon
print("Get Vegan pizza")
elif 'Meat' in dietry_restriction: # next alternative
print("Get cheese pizza")
else:
print("Get something else") # backup choice if neither of the previous conditions are true
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
# Match Case
# Match Cases are an alternative to if statements, can be used for structural pattern matching
# Same as Switch Case in C#
print("Match Cases")
print()
def order_special(day): # instead of checking different conditions just checks for specfic cases
match day:
case 'Sunday':
return 'Spinach Pizza'
case 'Monday':
return 'Mushroom Pizza'
case 'Tuesday':
return 'Pepperoni Pizza'
case 'Wednesday':
return 'Veggie Pizza'
case 'Thursday':
return 'Hawaiian Pizza'
today = 'Monday'
special = order_special(today)
print(f"Today is {today} and the special is {special}")
print()
# Missing Case
def order_special2(day): # instead of checking different conditions just checks for specfic cases
match day:
case 'Sunday':
return 'Spinach Pizza'
case 'Monday':
return 'Mushroom Pizza'
case 'Tuesday':
return 'Pepperoni Pizza'
case 'Wednesday':
return 'Veggie Pizza'
case 'Thursday':
return 'Hawaiian Pizza'
today = 'Friday'
special = order_special2(today)
print(f"Today is {today} and the special is {special}")
print()
# Missing Case with Exception Handelling
def order_special3(day):
match day:
case 'Sunday':
return 'Spinach Pizza'
case 'Monday':
return 'Mushroom Pizza'
case 'Tuesday':
return 'Pepperoni Pizza'
case 'Wednesday':
return 'Veggie Pizza'
case 'Thursday':
return 'Hawaiian Pizza'
case _: # wildcard to have a response ready for unexpected values
print("There is no special today")
return None
today = 'Friday'
special = order_special3(today)
print(f"Today is {today} and the special is {special}")
print()
# Real Day
def order_special4(day):
match day:
case 'Sunday':
return 'Spinach Pizza'
case 'Monday':
return 'Mushroom Pizza'
case 'Tuesday':
return 'Pepperoni Pizza'
case 'Wednesday':
return 'Veggie Pizza'
case 'Thursday':
return 'Hawaiian Pizza'
case _: # wildcard to have a response ready for unexpected values
print("There is no special today")
return None
from ast import Try
from calendar import Day, weekday # uses the actual day
import datetime
from sys import exception
today = datetime.datetime.now()
today = today.strftime("%A") # selects the right day format
special = order_special4(today)
print(f"Today is {today} and the special is {special}")
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
# For Loops
# A programming construct with a set loop limit
print("For Loops")
print()
# Incorrect iteration
sink = ['bowl','plate','cup']
print(f"There are {len(sink)} dishes in the sink")
for dish in sink:
print(f" - Put a {dish} in the dishwasher") # removing list during iteration causes the items to shift positions which can cause problems
sink.remove(dish)
print(f"There are {len(sink)} dishes in the sink: {sink}") # check that the sink is empty
print()
sink = ['bowl','plate','cup']
print(f"There are {len(sink)} dishes in the sink")
for dish in list(sink): # creates a copy of the list to iterate through while items are being removed from the original
print(f" - Put a {dish} in the dishwasher")
sink.remove(dish)
print(f"There are {len(sink)} dishes in the sink: {sink}")
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
# While Loops
# While Loops run as long as a condition is true
# While loops are used when you don't know how long the loop is meant to go for
print("While Loops")
print()
import random
dirty = True
scrub_count = 0
while dirty:
scrub_count += 1
print(f"Scrubbed the pan {scrub_count} times")
print("Rinsing to check if the pan is clean...\n")
if not random.randint(0,9): #if the number is not 0 as bool(0) means False, so if not False means True so when it is 0 the pan is clean
print("All Clean")
dirty = False
else:
print("Still dirty")
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
# Break Statements
# Break statements are usefull when you want to stop a loop early
dishwasher = ['plate','spoon','knife','fork','cup',
'plate','knife','fork','spoon','knife',
'fork', 'cup','bowl','spoon','knife'
'plate','bowl','cup','knife','fork']
for dish in list(dishwasher):
if not random.randint(0,19): # if not false/ if true / = 0 or >0
print("Out of space")
break
else:
print(f"Putting {dish} in the cabinet")
dishwasher.remove(dish)
if not dishwasher: # if list is empty
print("Dishes done")
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
# Error handling
# Catch errors
#try and except blocks lets your programs catch exceptions and handle them without crashing
print("Try and Except Blocks")
print()
#Trying to download things that don't exist
import urllib.request
try: # tries to access a google webpage
webpage = urllib.request.urlopen('http://www.godogle.com')
except:
print("Webpage could not open") # the excpetion for the wrong url
else:
for line in webpage: # prints the raw binary data for the webpage
print(line)
print()
#Validate Input
# It is important to validate imput and label exceptions so user know what went wrong
class CircuitBreaker:
def __init__(self,max_amps):
self.capacity = max_amps
self.load = 0
def connect(self,amps):
if self.load + amps > self.capacity:
raise Exception("Connection will exceed capacity") # tells the user what the error was
elif self.load + amps < 0:
raise Exception("Connection will cause a negative load")
else:
self.load += amps
cb = CircuitBreaker(20)
print(cb.capacity)
print(cb.load)
print()
# cb.connect(14)
# cb.connect(35)
print()
# cb.connect(-32)
# Customise errors
# Error handling allows code to execute properly when unexpected things occur
print("Customise errors")
print()
class ElectricalError(Exception):
def __init__(self, device, problem):
self.device = device
self.problem = problem
def __str__(self):
return f'The {self.device} is {self.problem}!'
class PlumbingError(Exception):
def __init__(self, device, problem):
self.device = device
self.problem = problem
def __str__(self):
return f'The {self.device} is {self.problem}!'
def cause_error(error_type):
if error_type == 'electrical':
raise ElectricalError('circuit breaker', 'overloaded') # defining the problem
elif error_type == 'plumbing':
raise PlumbingError('dishwasher', 'spraying water') # defining the problem
else:
raise Exception('a generic household problem')
# cause some problems
try:
cause_error('yard')
except ElectricalError as e:
print(e)
print('Barron fix it.')
except PlumbingError as e:
print(e)
print('Call the plumber.')
except: # for any generic exception
print('Call the landlord.')
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
#Polling
# Polling is when a program continously checks for an even, this can be inefficient and waste cpu resources
import time # The sleep function uses a mechanism called an interup which lets the program sleep and frees up the CPU to do other things
hungry = True
while hungry:
print('Opening the front door')
front_door = open('front_door.txt', 'r', encoding='utf-8') # reads text file named front_door.txt
text = front_door.read()
if 'Delivery Person' in text: # the loop wont stop until Delivery person is in the textfile
print('The pizza is here!!!!!!!!!!')
hungry = False
else:
print('Not yet...')
print('Closing the front door.\n')
front_door.close()
time.sleep(1) # rest for 1 second to help the cpu out by slowing the program down
print()
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
print("----------------------------------------------------------------------------------------------------------------------")
# Event driven programming
import asyncio # a python library that allows concurrent code to run asynchronously
import time
def alarm(): # handler for when the alarm goes off
print("Wake up!")
print("Calling the Pizza Company")
loop.call_later(1,alarm)
def doorbell(): # handler for when the doorbell rings
print("Ding! Dong!")
time.sleep(3) # program sleeps for 3 seconds but still waits to complete doorbell handler before attempting phonecall
print("Opening the door... 'Thanks for Bringing the Pizza'")
loop.stop()
def phonecall():# handler for when the phone is called
print("Ring! Ring!")
print("Answering the phone... 'Hello who's this?'")
loop = asyncio.get_event_loop() # event loop is used to manage and run asynchronous tasks
loop.call_later(1,alarm) # makes program wait 1 second before starting the alarm function
loop.call_later(4,doorbell)
loop.call_later(5,phonecall)
print("starting the event loop...")
loop.run_forever() #run until stop is called
print("The event loop stopped; closing it down. ")
loop.close() # ends the loop