-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp17.py
More file actions
494 lines (261 loc) · 10.6 KB
/
p17.py
File metadata and controls
494 lines (261 loc) · 10.6 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# Built-in Errors
# Exception, How to handle them
# raise your own errors, debugging, etc
# Built-in Errors
# syntax error ---> made some kind of illegality in syntax
# Indentation Error ---> related to space after loop, function, class, collon
# def rav():
# print("fd")
# print("sf") # indentation error
# name error ---> it happens when we use things(variable, method,....) which is not defined
# type error ----> print(5+"af")
print(5*"af") # o/p: afafafafaf
# Index Error
# l=[1,2,3]
# print(l[3]) # index error
# Value Error
# s="abc"
# print(int(s))
# Attribute Error
# l=[1,2,3]
# l.push(4) # here i am getting attribute error because list has not push method.
# Key Error
# d={'name':'Rakholiya'}
# print(d['age']) # key error
# Raise Errors
def add(a,b):
return a+b
print(add(2,3)) # o/p: 5
print(add('2','3')) # o/p: 23
def add1(a,b):
if (type(a) is int) and (type(b) is int):
return a+b
return "OOPS you are passing wrong data type to function"
print(add1(2,3)) # o/p: 5
print(add1('2','3')) # o/p: OOPS you are passing wrong data type to function
def add2(a,b):
if (type(a) is int) and (type(b) is int):
return a+b
raise TypeError("OOPS you are passing wrong data type to function") # here,we can raise any error, like we can write valueError instead of type error
print(add2(2,3)) # o/p: 5
# print(add2('2','3')) # o/p: TypeError: OOPS you are passing wrong data type to function
# def add2(a,b):
# if (type(a) is int) and (type(b) is int):
# return a+b
# raise ValueError("OOPS you are passing wrong data type to function")
# print(add2(2,3)) # o/p: 5
# print(add2('2','3')) # o/p: ValueError: OOPS you are passing wrong data type to function
# Raise errors example 1
# NotImplementedError # we raise this error when we use inheritance in oop
# abstract method
class Animal:
def __init__(self,name):
self.name=name
def sound(self):
return "this is animal sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed=breed
class Cat(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed=breed
doggy=Dog("boony",'pug')
print(doggy.sound()) # o/p: this is animal sound
class Animal1:
def __init__(self,name):
self.name=name
def sound(self):
return "meao meao"
class Dog1(Animal1):
def __init__(self, name, breed):
super().__init__(name)
self.breed=breed
class Cat1(Animal1):
def __init__(self, name, breed):
super().__init__(name)
self.breed=breed
doggy=Dog1("boony",'pug')
print(doggy.sound()) # o/p: meao meao # this sound comes from dog object that i don't want,
# but i want that class which inherit animal class define sound method, otherwise i should be got raise Error----> it is called NotImplementedError
# class Animal2:
# def __init__(self,name):
# self.name=name
# def sound(self):
# raise NotImplementedError('you have to define this method in subclasses')
# class Dog2(Animal2):
# def __init__(self, name, breed):
# super().__init__(name)
# self.breed=breed
# class Cat2(Animal2):
# def __init__(self, name, breed):
# super().__init__(name)
# self.breed=breed
# doggy=Dog2("boony",'pug')
# print(doggy.sound()) # o/p: NotImplementedError: you have to define this method in subclasses
class Animal3:
def __init__(self,name):
self.name=name
def sound(self): # abstract method
raise NotImplementedError('you have to define this method in subclasses')
class Dog3(Animal3):
def __init__(self, name, breed):
super().__init__(name)
self.breed=breed
def sound(self):
return "bhow bhow"
class Cat3(Animal3):
def __init__(self, name, breed):
super().__init__(name)
self.breed=breed
def sound(self):
return "meao meao"
doggy=Dog3("boony",'pug')
print(doggy.sound()) # o/p: bhow bhow
# Raise Example 2
class Mobile:
def __init__(self, name):
self.name=name
class MobileStore:
def __init__(self):
self.mobiles=[]
def add_mobile(self, new_mobile):
self.mobiles.append(new_mobile)
oneplus=Mobile("oneplus")
samsung="Samsung Galaxy s10"
mobostore=MobileStore()
print(mobostore.mobiles) # o/p: []
mobostore.add_mobile(samsung)
print(mobostore.mobiles) # o/p: ['Samsung Galaxy s10']
# here, i don't want to store any other string which are not in Mobile's object store in mobiles list. I mean i want that the string which are present in Mobile's obj store in mobiles's list.
class Mobile1:
def __init__(self, name):
self.name=name
class MobileStore1:
def __init__(self):
self.mobiles1=[]
def add_mobile(self, new_mobile):
if isinstance(new_mobile,Mobile1):
self.mobiles1.append(new_mobile)
else:
raise TypeError("new_mobile should be object of mobile class")
oneplus1=Mobile1("oneplus")
samsung1="Samsung Galaxy s10"
mobostore1=MobileStore1()
# mobostore1.add_mobile(samsung1) # o/p: TypeError: new_mobile should be object of mobile class
# print(mobostore1.mobiles1)
mobostore1.add_mobile(oneplus1)
print(mobostore1.mobiles1) # o/p: [<__main__.Mobile1 object at 0x034F9820>]
mobo_phones=mobostore1.mobiles1
print(mobo_phones[0].name) # o/p: oneplus
# or
print(mobostore1.mobiles1[0].name) # o/p: oneplus
# Exception Handling
# try except else finally
# Exception is the error which comes at time of execution
# try except
while True:
try:
age=int(input('Enter your age:\n'))
break
except ValueError:
print("Maybe you entered string insted of number, try again")
except:
print("unexpected error......")
if age<18:
print("you can't play this game")
else:
print("you can play this game")
# else finally clause
while True:
try:
number=int(input('Enter your age:\n'))
print(f"user input : {number}")
break
except ValueError:
print("Please type integer !!!")
except:
print("unexpected error......")
while True:
try:
number=int(input('Enter your age:\n'))
except ValueError:
print("Please type integer !!!")
except:
print("unexpected error......")
else: # this block will run when try block will run successfully, without exception
print(f"user input : {number}") # else is used to increase the redability of code
break
finally:
print("Finally block......")
# o/p: # o/p:
# Enter your age: # Enter your age:
# d # 2
# Please type integer !!! # user input : 2
# Finally block...... # Finally block......
# Excercise 1
# make a function 'divide'
# divide(a,b)
def divide(a,b):
try:
c=0
c=a/b
except ZeroDivisionError:
print("please don't divide by Zero")
except TypeError:
print("Please input numbers only")
else:
return c
print(divide(4,2)) # o/p: 2.0
print(divide(4,0)) # o/p: please don't divide by Zero
print(divide('4',2)) # o/p: Please input numbers only
print(divide(4,'2')) # o/p: Please input numbers only
# Custom Exception
# Q - why custom exception?
# A - to increase the redability of code
def validate(name):
if len(name)<8:
raise ValueError("name is too short")
user_name=input("Enter name:\n")
validate(user_name)
print(f"hello {user_name}")
# o/p:
# Enter name:
# sd
# ValueError: name is too short
# make our own exception(custom exception)
class NameTooShortError(ValueError):
pass
def validate1(name):
if len(name)<8:
raise NameTooShortError("name is too short")
user_name1=input("Enter name:\n")
validate1(user_name1)
print(f"hello {user_name1}")
# o/p:
# Enter name:
# as
# __main__.NameTooShortError: name is too short
# video 214 # Python Debugger
# Debugging ----> find the errors in our code and fix them.
# dedebugging is the process of finding and resolving defects or problems within a computer program that prevent correct operation of computer software or a system.
# why debugging?
# 1) our program is not running and causing unexpected error.
# 2) our program is working fine but not working the same way we want.
# steps for debugging
# 1) set trace (using pdb module)
# 2) execute code line by line
import pdb # import pdb module
# module----> python file contains usefull classes and functions wrote by developer.
# l ---> use to see where we are
# n ---> run our code and send us on next line
# var_name ---> we can see that variable is existing or not
# q ---> use to quite the process
# c ---> continue our code without debugging
pdb.set_trace() # this always stop my program each time after line ----> this we can see by using 'l' command
name=input("Enter your name:\n")
age=input("Please type your age:\n")
print(f"hello {name} your age is {age}")
age2=age+5 # o/p: TypeError: can only concatenate str (not "int") to str
print(f'{name} you will be {age2} in next five years')