SlideShare a Scribd company logo
Exception Handling in Python
February 13, 2018
1 Exception
• An indication of a special event that occurs during a programs exceution.
• Indicates that, although the event can occur, the event occurs infrequently.
• Leads to Resource Leak
– Aborting a program component could leae a file or a network connection in a state in
which other programs are not able to acquire the resource.
• When a Python script encounters a situation that it can’t cope with, it raises an exception.
• An exception is a Python object that represents an error
• Examples of Exceptions
1. Division by Zero
2. Addition of wo incompatible types
3. Accessing a file that is nonexistent.
4. Accessing a nonexistent index of a sequence.
5. Deleting a table in a disconnected database seerver.
6. Withdraing money greater than the available amount.
7. etc ...
1.1 Exception Handling
• When no exceptions occur, Exception Handling code incurs little or no performance penal-
ties.
• Programs that implement Exception handling operate more effiently than programs that
perform Error Handling throughout the program logic.
• Exception handling enables the programmer to remove error-handling code from the "main
line" of the programs execution.
• This improves program clarity and enhances modifiability
1
• Advantages of Exception Handling
1. Handle the error
– catching the exception
– resolving the exception
2. Continue processing as if no error had occured
3. Programs are more clear, robust and more fault-tolerant
1.2 Exception class
• Exception are objects of classes that inherit from class Exception.
• Programmer defined exception classes should derive directly or indirectly from class Excep-
tion.
1.2.1 Class Hierarchy of all built-in Exceptions
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
2
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
In [1]: print(1/0)
print("Cool code")
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-fcea2cfbf768> in <module>()
----> 1 print(1/0)
2 print("Cool code")
3
ZeroDivisionError: division by zero
In [16]: x = 10
if x > 0:
print "greater"
File "<ipython-input-16-f27b142f89d4>", line 3
print "greater"
ˆ
SyntaxError: Missing parentheses in call to 'print'
1.3 Syntax : try - except - else clause
In [15]: try:
print(1/0)
except:
pass
print("Cool Code")
Cool Code
In [14]: try:
x = 1
y = "Hai"
quotient = x/y
except TypeError:
print("Type error found!!")
except ZeroDivisionError:
4
print("Division by zero!!")
else:
print(quotient)
Type error found!!
In [13]: try:
x = 1
y = 0
quotient = x/y
except TypeError:
print("Type error found!!")
except ZeroDivisionError:
print("Division by zero!!")
else:
print(quotient)
Division by zero!!
In [12]: try:
x = 1
y = 0
quotient = x/y
except TypeError:
print("Type error found!!")
except ZeroDivisionError:
print("Division by zero!!")
else:
print(quotient)
print("Finally done!!")
Division by zero!!
Finally done!!
1.4 finally clause
• Programs frequently request and release resources dynamically.
• Programs that obtain certain types of resources (such as files) sometines must return re-
sources explicitly to the system to avoid resource leaks.
• The finally clause is an ideal location to place resource deallocation code for resources ac-
quired.
In [11]: try:
fh = open("testfile","w")
try:
fh.write("This is my test file for exception handling!!")
5
print("File Created in the working directory!!")
finally:
fh.close()
except IOError:
print("Error : can't find the file or read data")
print("Done!!")
File Created in the working directory!!
Done!!
In [22]: class Jeep:
def __init__(self,name):
self.name = name
class Van:
def __init__(self,value):
self.value = value
j = Jeep("ABC")
v = Van("XYZ")
try:
if v.value != j.name:
raise Exception
except Exception:
print("Names are not matching!!")
finally:
del j
del v
print("Both objects are deleted!!")
#print(v, j)
Names are not matching!!
Both objects are deleted!!
1.5 Raising / Throwing an Exception
• raise keyword
• Catching and handling exceptions enables a program to know when an error has occured,
then to take actions to minimize the consequences of that error.
• specify an argument or arguments that initailize the exception object.
– Syntax : raise [ExceptionName]
In [9]: x = int(input("Enter level :"))
try:
6
if (x >10 or x < 1):
raise ValueError
else:
print("Wait while the game is loading....")
except ValueError:
print("The game consists of 10 levels only ranging from 1 to 10")
Enter level :-1
The game consists of 10 levels only ranging from 1 to 10
In [35]: x = 2
y = 8
z = y / x
print("quotient: ",z)
while(1):
try:
s = int(input("enter the number :"))
z = y / s
print("Quotient: ",z)
except ValueError as arg:
print("Invalid Input!!", arg)
except ArithmeticError as arg:
print("Invalid Input!!", arg)
else:
print("Exit while loop")
break
print("Done")
quotient: 4.0
enter the number :hello
Invalid Input!! invalid literal for int() with base 10: 'hello'
enter the number :0
Invalid Input!! division by zero
enter the number :2
Quotient: 4.0
Exit while loop
Done
1.6 User defined Exceptions
• User can create exception classes to handle exceptions specific to a program.
• User Defined Exception classes must be derived from bass class, Exception
In [38]: class MyException(Exception):
def __init__(self):
self.argument = "I am a User Defined Exception"
try:
7
print("Example of a User Defined Exception")
print()
raise MyException
except MyException:
print(MyException().argument)
Example of a User Defined Exception
I am a User Defined Exception
In [42]: import math
class NegativeNumberError(ArithmeticError):
def __init__(self):
self.argument = "Square root of Negative Number not defined!!"
def square_root(number):
if number < 0:
raise NegativeNumberError
return math.sqrt(number)
while(1):
try:
user_value = float(input("enter the value :"))
print(square_root(user_value))
except ValueError:
print("Oops!! Value Error found!!")
except NegativeNumberError as arg:
print(NegativeNumberError().argument)
else:
print("Exit while loop")
break
enter the value :-1
Square root of Negative Number not defined!!
enter the value :hello
Oops!! Value Error found!!
enter the value :2
1.4142135623730951
Exit while loop
In [43]: class CarException(Exception):
def __init__(self):
self.argument = "Found an invalid Car name!!"
pass
class Car:
def __init__(self,value):
8
self.value = value
car_list = [Car("Maruti 800"), Car("Scorpio"),Car("Van")]
for c in car_list:
try:
print(c.value, end = ' ')
if c.value == "Van":
raise CarException
except CarException:
print(": ",CarException().argument)
else:
print(" : Valid Car name!!!")
print("Done!!")
Maruti 800 : Valid Car name!!!
Scorpio : Valid Car name!!!
Van : Found an invalid Car name!!
Done!!
1.7 Assertion
• Assertion is a sanity-check that you can turn on/off when you are done with your testing of
the program
• It’s like a raise-if statement (or to be more accurate, a raise-if-not statement).
• An expression is tested, and if the result comes up false an exception is raised.
• Programs often place assertions
• at the start of a function to check for valid input,
• and after a function call to check for valid output
• Syntax:
• assert Expression [, Arguments]
In [61]: def apply_discount(product,discount):
price = int(product['price'] *(1.0-discount))
try:
assert 0 <= price<= product['price']
except AssertionError:
print("Assertion Error")
else:
return price/100
# Sample product: Nice Shoes for Rs. 149.00
shoes = {'name':'Fancy Shoes','price':14900}
9
# 25% off --> 111.75
apply_discount(shoes,0.25)
Out[61]: 111.75
In [62]: def apply_discount(product,discount):
price = int(product['price'] *(1.0-discount))
try:
assert 0 <= price<= product['price']
except AssertionError:
print("Assertion Error")
else:
return price/100
# Sample product: Nice Shoes for Rs. 149.00
shoes = {'name':'Fancy Shoes','price':14900}
# 200% discount
apply_discount(shoes,2.0)
Assertion Error
In [54]: def set_bearing(new_bearing):
bearing = new_bearing
try:
assert(0 <= bearing <=90)
except AssertionError:
print("AssertionError")
return bearing
print(set_bearing(45))
45
In [55]: def compute_perimeter(parcel):
perimeter = 0
for p in parcel:
#assert(p >= 0)
perimeter += p
try:
10
assert(perimeter > 1)
except AssertionError:
print("AssertionError")
return perimeter
parcel = [2,3,-4]
print(compute_perimeter(parcel))
AssertionError
1
11

More Related Content

PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PPT
PDF
Python exceptions
PPTX
Exception handling in Java
PPT
Exception handling
PPTX
Exception handling
PPTX
Exceptions handling in java
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Python exceptions
Exception handling in Java
Exception handling
Exception handling
Exceptions handling in java

What's hot (20)

PPTX
Error and exception in python
PPTX
Presentation on-exception-handling
PPT
Exception Handling
PPT
Exception Handling
PPTX
Python Programming Essentials - M21 - Exception Handling
PPT
Exception handling
PDF
Python programming : Exceptions
PPTX
Exception handling in java
PPT
Exception handling in java
PPT
Java exception
PPTX
Java - Exception Handling
PPTX
7.error management and exception handling
PPTX
Exception handling in java
PPTX
130410107010 exception handling
PPSX
Exception Handling
PPTX
Exception Handling in Java
PPTX
Exceptionhandling
PPTX
Exception handling in java
ODP
Exception handling in java
PPTX
Exception handling in Java
Error and exception in python
Presentation on-exception-handling
Exception Handling
Exception Handling
Python Programming Essentials - M21 - Exception Handling
Exception handling
Python programming : Exceptions
Exception handling in java
Exception handling in java
Java exception
Java - Exception Handling
7.error management and exception handling
Exception handling in java
130410107010 exception handling
Exception Handling
Exception Handling in Java
Exceptionhandling
Exception handling in java
Exception handling in java
Exception handling in Java
Ad

Similar to Exception handling in python (20)

PDF
lecs101.pdfgggggggggggggggggggddddddddddddb
PPTX
Exception handling.pptxnn h
PPTX
Exception Handling in Python Programming.pptx
PPTX
Exception Handling in Python programming.pptx
PPTX
Exception handling with python class 12.pptx
PPTX
Exception Handling in python programming.pptx
DOCX
Exception handlingpdf
PPTX
Python Exception Handling
PPTX
Python Lecture 7
PPTX
Python Unit II.pptx
PPT
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
PPTX
Exception Handling in Python
PPTX
Python Exception handling using Try-Except-Finally
PPTX
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
PPTX
Python Exceptions Powerpoint Presentation
PDF
Wondershare UniConverter Crack FREE Download 2025 version
PPTX
Mastering Errors and Exceptions in Python: A Comprehensive Guide
PPT
Exception Handling on 22nd March 2022.ppt
PPT
Py-Slides-9.ppt
lecs101.pdfgggggggggggggggggggddddddddddddb
Exception handling.pptxnn h
Exception Handling in Python Programming.pptx
Exception Handling in Python programming.pptx
Exception handling with python class 12.pptx
Exception Handling in python programming.pptx
Exception handlingpdf
Python Exception Handling
Python Lecture 7
Python Unit II.pptx
33aa27cae9c84fd12762a4ecdc288df822623524-1705207147822.ppt
Exception Handling in Python
Python Exception handling using Try-Except-Finally
EXCEPTIONS-PYTHON.pptx RUNTIME ERRORS HANDLING
Python Exceptions Powerpoint Presentation
Wondershare UniConverter Crack FREE Download 2025 version
Mastering Errors and Exceptions in Python: A Comprehensive Guide
Exception Handling on 22nd March 2022.ppt
Py-Slides-9.ppt
Ad

More from Lifna C.S (7)

PDF
Mobile 2.0
PDF
Mobile Design
PDF
Mobile Information Architecture
PDF
Types of Mobile Applications
PDF
Arrays in python
PDF
Basic data structures in python
PDF
File and directories in python
Mobile 2.0
Mobile Design
Mobile Information Architecture
Types of Mobile Applications
Arrays in python
Basic data structures in python
File and directories in python

Recently uploaded (20)

PDF
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
PPTX
The-Looming-Shadow-How-AI-Poses-Dangers-to-Humanity.pptx
PPTX
AgentX UiPath Community Webinar series - Delhi
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
PDF
Introduction to Data Science: data science process
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
Road Safety tips for School Kids by a k maurya.pptx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
PDF
Chad Ayach - A Versatile Aerospace Professional
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
PDF
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
PDF
ETO & MEO Certificate of Competency Questions and Answers
PPTX
436813905-LNG-Process-Overview-Short.pptx
PPTX
TE-AI-Unit VI notes using planning model
PPTX
Soil science - sampling procedures for soil science lab
PPT
Drone Technology Electronics components_1
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
The-Looming-Shadow-How-AI-Poses-Dangers-to-Humanity.pptx
AgentX UiPath Community Webinar series - Delhi
July 2025: Top 10 Read Articles Advanced Information Technology
Introduction to Data Science: data science process
Structs to JSON How Go Powers REST APIs.pdf
Road Safety tips for School Kids by a k maurya.pptx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
Chad Ayach - A Versatile Aerospace Professional
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
ETO & MEO Certificate of Competency Questions and Answers
436813905-LNG-Process-Overview-Short.pptx
TE-AI-Unit VI notes using planning model
Soil science - sampling procedures for soil science lab
Drone Technology Electronics components_1

Exception handling in python

  • 1. Exception Handling in Python February 13, 2018 1 Exception • An indication of a special event that occurs during a programs exceution. • Indicates that, although the event can occur, the event occurs infrequently. • Leads to Resource Leak – Aborting a program component could leae a file or a network connection in a state in which other programs are not able to acquire the resource. • When a Python script encounters a situation that it can’t cope with, it raises an exception. • An exception is a Python object that represents an error • Examples of Exceptions 1. Division by Zero 2. Addition of wo incompatible types 3. Accessing a file that is nonexistent. 4. Accessing a nonexistent index of a sequence. 5. Deleting a table in a disconnected database seerver. 6. Withdraing money greater than the available amount. 7. etc ... 1.1 Exception Handling • When no exceptions occur, Exception Handling code incurs little or no performance penal- ties. • Programs that implement Exception handling operate more effiently than programs that perform Error Handling throughout the program logic. • Exception handling enables the programmer to remove error-handling code from the "main line" of the programs execution. • This improves program clarity and enhances modifiability 1
  • 2. • Advantages of Exception Handling 1. Handle the error – catching the exception – resolving the exception 2. Continue processing as if no error had occured 3. Programs are more clear, robust and more fault-tolerant 1.2 Exception class • Exception are objects of classes that inherit from class Exception. • Programmer defined exception classes should derive directly or indirectly from class Excep- tion. 1.2.1 Class Hierarchy of all built-in Exceptions BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError 2
  • 3. | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning In [1]: print(1/0) print("Cool code") --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-1-fcea2cfbf768> in <module>() ----> 1 print(1/0) 2 print("Cool code") 3
  • 4. ZeroDivisionError: division by zero In [16]: x = 10 if x > 0: print "greater" File "<ipython-input-16-f27b142f89d4>", line 3 print "greater" ˆ SyntaxError: Missing parentheses in call to 'print' 1.3 Syntax : try - except - else clause In [15]: try: print(1/0) except: pass print("Cool Code") Cool Code In [14]: try: x = 1 y = "Hai" quotient = x/y except TypeError: print("Type error found!!") except ZeroDivisionError: 4
  • 5. print("Division by zero!!") else: print(quotient) Type error found!! In [13]: try: x = 1 y = 0 quotient = x/y except TypeError: print("Type error found!!") except ZeroDivisionError: print("Division by zero!!") else: print(quotient) Division by zero!! In [12]: try: x = 1 y = 0 quotient = x/y except TypeError: print("Type error found!!") except ZeroDivisionError: print("Division by zero!!") else: print(quotient) print("Finally done!!") Division by zero!! Finally done!! 1.4 finally clause • Programs frequently request and release resources dynamically. • Programs that obtain certain types of resources (such as files) sometines must return re- sources explicitly to the system to avoid resource leaks. • The finally clause is an ideal location to place resource deallocation code for resources ac- quired. In [11]: try: fh = open("testfile","w") try: fh.write("This is my test file for exception handling!!") 5
  • 6. print("File Created in the working directory!!") finally: fh.close() except IOError: print("Error : can't find the file or read data") print("Done!!") File Created in the working directory!! Done!! In [22]: class Jeep: def __init__(self,name): self.name = name class Van: def __init__(self,value): self.value = value j = Jeep("ABC") v = Van("XYZ") try: if v.value != j.name: raise Exception except Exception: print("Names are not matching!!") finally: del j del v print("Both objects are deleted!!") #print(v, j) Names are not matching!! Both objects are deleted!! 1.5 Raising / Throwing an Exception • raise keyword • Catching and handling exceptions enables a program to know when an error has occured, then to take actions to minimize the consequences of that error. • specify an argument or arguments that initailize the exception object. – Syntax : raise [ExceptionName] In [9]: x = int(input("Enter level :")) try: 6
  • 7. if (x >10 or x < 1): raise ValueError else: print("Wait while the game is loading....") except ValueError: print("The game consists of 10 levels only ranging from 1 to 10") Enter level :-1 The game consists of 10 levels only ranging from 1 to 10 In [35]: x = 2 y = 8 z = y / x print("quotient: ",z) while(1): try: s = int(input("enter the number :")) z = y / s print("Quotient: ",z) except ValueError as arg: print("Invalid Input!!", arg) except ArithmeticError as arg: print("Invalid Input!!", arg) else: print("Exit while loop") break print("Done") quotient: 4.0 enter the number :hello Invalid Input!! invalid literal for int() with base 10: 'hello' enter the number :0 Invalid Input!! division by zero enter the number :2 Quotient: 4.0 Exit while loop Done 1.6 User defined Exceptions • User can create exception classes to handle exceptions specific to a program. • User Defined Exception classes must be derived from bass class, Exception In [38]: class MyException(Exception): def __init__(self): self.argument = "I am a User Defined Exception" try: 7
  • 8. print("Example of a User Defined Exception") print() raise MyException except MyException: print(MyException().argument) Example of a User Defined Exception I am a User Defined Exception In [42]: import math class NegativeNumberError(ArithmeticError): def __init__(self): self.argument = "Square root of Negative Number not defined!!" def square_root(number): if number < 0: raise NegativeNumberError return math.sqrt(number) while(1): try: user_value = float(input("enter the value :")) print(square_root(user_value)) except ValueError: print("Oops!! Value Error found!!") except NegativeNumberError as arg: print(NegativeNumberError().argument) else: print("Exit while loop") break enter the value :-1 Square root of Negative Number not defined!! enter the value :hello Oops!! Value Error found!! enter the value :2 1.4142135623730951 Exit while loop In [43]: class CarException(Exception): def __init__(self): self.argument = "Found an invalid Car name!!" pass class Car: def __init__(self,value): 8
  • 9. self.value = value car_list = [Car("Maruti 800"), Car("Scorpio"),Car("Van")] for c in car_list: try: print(c.value, end = ' ') if c.value == "Van": raise CarException except CarException: print(": ",CarException().argument) else: print(" : Valid Car name!!!") print("Done!!") Maruti 800 : Valid Car name!!! Scorpio : Valid Car name!!! Van : Found an invalid Car name!! Done!! 1.7 Assertion • Assertion is a sanity-check that you can turn on/off when you are done with your testing of the program • It’s like a raise-if statement (or to be more accurate, a raise-if-not statement). • An expression is tested, and if the result comes up false an exception is raised. • Programs often place assertions • at the start of a function to check for valid input, • and after a function call to check for valid output • Syntax: • assert Expression [, Arguments] In [61]: def apply_discount(product,discount): price = int(product['price'] *(1.0-discount)) try: assert 0 <= price<= product['price'] except AssertionError: print("Assertion Error") else: return price/100 # Sample product: Nice Shoes for Rs. 149.00 shoes = {'name':'Fancy Shoes','price':14900} 9
  • 10. # 25% off --> 111.75 apply_discount(shoes,0.25) Out[61]: 111.75 In [62]: def apply_discount(product,discount): price = int(product['price'] *(1.0-discount)) try: assert 0 <= price<= product['price'] except AssertionError: print("Assertion Error") else: return price/100 # Sample product: Nice Shoes for Rs. 149.00 shoes = {'name':'Fancy Shoes','price':14900} # 200% discount apply_discount(shoes,2.0) Assertion Error In [54]: def set_bearing(new_bearing): bearing = new_bearing try: assert(0 <= bearing <=90) except AssertionError: print("AssertionError") return bearing print(set_bearing(45)) 45 In [55]: def compute_perimeter(parcel): perimeter = 0 for p in parcel: #assert(p >= 0) perimeter += p try: 10
  • 11. assert(perimeter > 1) except AssertionError: print("AssertionError") return perimeter parcel = [2,3,-4] print(compute_perimeter(parcel)) AssertionError 1 11