Exception Handling
Exception Handling
1. Syntax Errors
2. Runtime Errors
1. Syntax Errors:
The errors which occurs because of invalid syntax are called syntax errors.
Eg 1:
x=10
if x==10
print("Hello")
Eg 2:
print "Hello"
Note:
Programmer is responsible to correct these syntax errors. Once all syntax errors are
corrected then only program execution will be started.
2. Runtime Errors:
x=int(input("Enter Number:"))
print(x)
D:\Python_classes>py test.py
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'
Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors
What is Exception:
An unwanted and unexpected event that disturbs normal flow of program is called
exception.
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
Exception handling does not mean repairing exception. We have to define alternative way
to continue rest of the program normally.
Eg:
For example our programming requirement is reading data from remote file locating at
London. At runtime if london file is not available then the program should not be
terminated abnormally. We have to provide local file to continue rest of the program
normally. This way of defining alternative is nothing but exception handling.
try:
Q. What is an Exception?
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
2 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Default Exception Handing in Python:
Every exception in Python is an object. For every exception type the corresponding classes
are available.
Whevever an exception occurs PVM will create the corresponding exception object and
will check for handling code. If handling code is not available then Python interpreter
terminates the program abnormally and prints corresponding exception information to
the console.
The rest of the program won't be executed.
Eg:
1) print("Hello")
2) print(10/0)
3) print("Hi")
4)
5) D:\Python_classes>py test.py
6) Hello
7) Traceback (most recent call last):
8) File "test.py", line 2, in <module>
9) print(10/0)
10) ZeroDivisionError: division by zero
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Python's Exception Hierarchy
BaseException
Overflow Permission
Error Error
TimeOut
Error
Most of the times being a programmer we have to concentrate Exception and its child
classes.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
try:
Risky Code
except XXX:
Handling code/Alternative Code
without try-except:
1. print("stmt-1")
2. print(10/0)
3. print("stmt-3")
4.
5. Output
6. stmt-1
7. ZeroDivisionError: division by zero
with try-except:
1. print("stmt-1")
2. try:
3. print(10/0)
4. except ZeroDivisionError:
5. print(10/2)
6. print("stmt-3")
7.
8. Output
9. stmt-1
10. 5.0
11. stmt-3
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
case-2: If an exception raised at stmt-2 and corresponding except block matched
1,4,5 Normal Termination
case-3: If an exception raised at stmt-2 and corresponding except block not matched
1, Abnormal Termination
Conclusions:
1. within the try block if anywhere exception raised then rest of the try block wont be
executed eventhough we handled that exception. Hence we have to take only risky code
inside try block and length of the try block should be as less as possible.
2. In addition to try block,there may be a chance of raising exceptions inside except and
finally blocks also.
3. If any statement which is not part of try block raises an exception then it is always
abnormal termination.
1. print(10/0)
2. except ZeroDivisionError as msg:
3. print("exception raised and its description is:",msg)
4.
5. Output exception raised and its description is: division by zero
The way of handling exception is varied from exception to exception.Hence for every
exception type a seperate except block we have to provide. i.e try with multiple except
blocks is possible and recommended to use.
Eg:
try:
-------
-------
-------
except ZeroDivisionError:
perform alternative
arithmetic operations
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
6 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
except FileNotFoundError:
use local file instead of remote file
If try with multiple except blocks available then based on raised exception the
corresponding except block will be executed.
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError :
6) print("Can't Divide with Zero")
7) except ValueError:
8) print("please provide int value only")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 2
13) 5.0
14)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: 0
18) Can't Divide with Zero
19)
20) D:\Python_classes>py test.py
21) Enter First Number: 10
22) Enter Second Number: ten
23) please provide int value only
If try with multiple except blocks available then the order of these except blocks is
important .Python interpreter will always consider from top to bottom until matched
except block identified.
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ArithmeticError :
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("ZeroDivisionError")
9)
10) D:\Python_classes>py test.py
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
11) Enter First Number: 10
12) Enter Second Number: 0
13) ArithmeticError
We can write a single except block that can handle multiple different types of exceptions.
except (Exception1,Exception2,exception3,..): or
except (Exception1,Exception2,exception3,..) as msg :
Parenthesis are mandatory and this group of exceptions internally considered as tuple.
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except (ZeroDivisionError,ValueError) as msg:
6) print("Plz Provide valid numbers only and problem is: ",msg)
7)
8) D:\Python_classes>py test.py
9) Enter First Number: 10
10) Enter Second Number: 0
11) Plz Provide valid numbers only and problem is: division by zero
12)
13) D:\Python_classes>py test.py
14) Enter First Number: 10
15) Enter Second Number: ten
16) Plz Provide valid numbers only and problem is: invalid literal for int() with b
17) ase 10: 'ten'
Syntax:
except:
statements
Eg:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
8 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) except ZeroDivisionError:
6) print("ZeroDivisionError:Can't divide with zero")
7) except:
8) print("Default Except:Plz provide valid input only")
9)
10) D:\Python_classes>py test.py
11) Enter First Number: 10
12) Enter Second Number: 0
13) ZeroDivisionError:Can't divide with zero
14)
15) D:\Python_classes>py test.py
16) Enter First Number: 10
17) Enter Second Number: ten
18) Default Except:Plz provide valid input only
***Note: If try with multiple except blocks available then default except block should be
last,otherwise we will get SyntaxError.
Eg:
1) try:
2) print(10/0)
3) except:
4) print("Default Except")
5) except ZeroDivisionError:
6) print("ZeroDivisionError")
7)
8) SyntaxError: default 'except:' must be last
Note:
finally block:
2. It is not recommended to maintain clean up code inside except block, because if there
is no exception then except block won't be executed.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Hence we required some place to maintain clean up code which should be executed
always irrespective of whether exception raised or not raised and whether exception
handled or not handled. Such type of best place is nothing but finally block.
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
The speciality of finally block is it will be executed always whether exception raised or not
raised and whether exception handled or not handled.
1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
7)
8) Output
9) try
10) finally
1) try:
2) print("try")
3) print(10/0)
4) except ZeroDivisionError:
5) print("except")
6) finally:
7) print("finally")
8)
9) Output
10) try
11) except
12) finally
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
10 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Case-3: If there is an exception raised but not handled:
1) try:
2) print("try")
3) print(10/0)
4) except NameError:
5) print("except")
6) finally:
7) print("finally")
8)
9) Output
10) try
11) finally
12) ZeroDivisionError: division by zero(Abnormal Termination)
*** Note: There is only one situation where finally block won't be executed ie whenever
we are using os._exit(0) function.
Whenever we are using os._exit(0) function then Python Virtual Machine itself will be
shutdown.In this particular case finally won't be executed.
1) imports
2) try:
3) print("try")
4) os._exit(0)
5) except NameError:
6) print("except")
7) finally:
8) print("finally")
9)
10) Output
11) try
Note:
os._exit(0)
where 0 represents status code and it indicates normal termination
There are multiple status codes are possible.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
11 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
finally:
stmt-5
stmt6
Case-2: If an exception raised at stmt2 and the corresponding except block matched
1,4,5,6 Normal Termination
Case-3: If an exception raised at stmt2 but the corresponding except block not matched
1,5 Abnormal Termination
Case-4:If an exception raised at stmt4 then it is always abnormal termination but before
that finally block will be executed.
We can take try-except-finally blocks inside try or except or finally blocks.i.e nesting of try-
except-finally is possible.
try:
----------
----------
----------
try:
-------------
--------------
--------------
except:
--------------
--------------
--------------
------------
except:
-----------
-----------
-----------
General Risky code we have to take inside outer try block and too much risky code we
have to take inside inner try block. Inside Inner try block if an exception raised then inner
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
12 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
except block is responsible to handle. If it is unable to handle then outer except block is
responsible to handle.
Eg:
1) try:
2) print("outer try block")
3) try:
4) print("Inner try block")
5) print(10/0)
6) except ZeroDivisionError:
7) print("Inner except block")
8) finally:
9) print("Inner finally block")
10) except:
11) print("outer except block")
12) finally:
13) print("outer finally block")
14)
15) Output
16) outer try block
17) Inner try block
18) Inner except block
19) Inner finally block
20) outer finally block
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
case-1: If there is no exception
1,2,3,4,5,6,8,9,11,12 Normal Termination
case-2: If an exception raised at stmt-2 and the corresponding except block matched
1,10,11,12 Normal Termination
case-3: If an exceptiion raised at stmt-2 and the corresponding except block not matched
1,11,Abnormal Termination
case-5: If an exception raised at stmt-5 and inner except block not matched but outer
except block matched
1,2,3,4,8,10,11,12,Normal Termination
case-6:If an exception raised at stmt-5 and both inner and outer except blocks are not
matched
1,2,3,4,8,11,Abnormal Termination
case-8: If an exception raised at stmt-7 and corresponding except block not matched
1,2,3,.,.,.,8,11,Abnormal Termination
case-10: If an exception raised at stmt-8 and corresponding except block not matched
1,2,3,.,.,.,.,11,Abnormal Termination
case-12: If an exception raised at stmt-9 and corresponding except block not matched
1,2,3,.,.,.,.,8,11,Abnormal Termination
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
14 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
case-14: If an exception raised at stmt-11 or stmt-12 then it is always abnormal
termination.
Note: If the control entered into try block then compulsary finally block will be executed.
If the control not entered into try block then finally block won't be executed.
try:
Risky Code
except:
will be executed if exception inside try
else:
will be executed if there is no exception inside try
finally:
will be executed whether exception raised or not raised and handled or not
handled
Eg:
try:
print("try")
print(10/0)--->1
except:
print("except")
else:
print("else")
finally:
print("finally")
If we comment line-1 then else block will be executed b'z there is no exception inside try.
In this case the output is:
try
else
finally
If we are not commenting line-1 then else block won't be executed b'z there is exception
inside try block. In this case output is:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
15 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
try
except
finally
2. Wheneever we are writing except block, compulsory we should write try block. i.e
except without try is always invalid.
3. Whenever we are writing finally block, compulsory we should write try block. i.e finally
without try is always invalid.
4. We can write multiple except blocks for the same try,but we cannot write multiple
finally blocks for the same try
5. Whenever we are writing else block compulsory except block should be there. i.e
without except we cannot write else block.
7. We can define try-except-else-finally inside try,except,else and finally blocks. i.e nesting
of try-except-else-finally is always possible.
try:
1
print("try")
except:
2
print("Hello")
else:
3
print("Hello")
finally:
4
print("Hello")
try:
print("try")
5
except: √
print("except")
try:
print("try")
6
finally: √
print("finally")
try:
7
print("try") √
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
16 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
except:
print("except")
else:
print("else")
try:
print("try")
8
else:
print("else")
try:
print("try")
else:
9
print("else")
finally:
print("finally")
try:
print("try")
except XXX:
10
print("except-1") √
except YYY:
print("except-2")
try:
print("try")
except :
print("except-1")
11
else:
print("else")
else:
print("else")
try:
print("try")
except :
print("except-1")
12
finally:
print("finally")
finally:
print("finally")
try:
print("try")
13 print("Hello")
except:
print("except")
try:
14 print("try")
except:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
17 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print("except")
print("Hello")
except:
print("except")
try:
print("try")
except:
15 print("except")
print("Hello")
finally:
print("finally")
try:
print("try")
except:
16 print("except")
print("Hello")
else:
print("else")
try:
print("try")
except:
print("except")
17
try: √
print("try")
except:
print("except")
try:
print("try")
except:
print("except")
18
try: √
print("try")
finally:
print("finally")
try:
print("try")
except:
print("except")
19
if 10>20:
print("if")
else:
print("else")
try:
20
print("try") √
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
18 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
try:
print("inner try")
except:
print("inner except block")
finally:
print("inner finally block")
except:
print("except")
try:
print("try")
except:
print("except")
21 try:
print("inner try")
√
except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
except:
print("except")
finally:
22 try:
print("inner try")
√
except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
except:
print("except")
23
try:
print("try")
else:
print("else")
try:
print("try")
try:
24
print("inner try")
except:
print("except")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
try:
print("try")
else:
print("else")
25
except:
print("except")
finally:
print("finally")
Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1. Predefined Exceptions
2. User Definded Exceptions
1. Predefined Exceptions:
The exceptions which are raised automatically by Python virtual machine whenver a
particular event occurs, are called pre defined exceptions.
Eg 1: Whenever we are trying to perform Division by zero, automatically Python will raise
ZeroDivisionError.
print(10/0)
Eg 2: Whenever we are trying to convert input value to int type and if input value is not
int value then Python will raise ValueError automatically
x=int("ten")===>ValueError
Some time we have to define and raise exceptions explicitly to indicate that something
goes wrong ,such type of exceptions are called User Defined Exceptions or Customized
Exceptions
Programmer is responsible to define these exceptions and Python not having any idea
about these. Hence we have to raise explicitly based on our requirement by using "raise"
keyword.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException
Every exception in Python is a class that extends Exception class either directly or
indirectly.
Syntax:
class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
Eg:
1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg
Eg:
1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg
4)
5) class TooOldException(Exception):
6) def __init__(self,arg):
7) self.msg=arg
8)
9) age=int(input("Enter Age:"))
10) if age>60:
11) raise TooYoungException("Plz wait some more time you will get best match soon!!!")
12) elif age<18:
13) raise TooOldException("Your age already crossed marriage age...no chance of getting ma
rriage")
14) else:
15) print("You will get match details soon by email!!!")
16)
17) D:\Python_classes>py test.py
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
18) Enter Age:90
19) __main__.TooYoungException: Plz wait some more time you will get best match soon!!!
20)
21) D:\Python_classes>py test.py
22) Enter Age:12
23) __main__.TooOldException: Your age already crossed marriage age...no chance of g
24) etting marriage
25)
26) D:\Python_classes>py test.py
27) Enter Age:27
28) You will get match details soon by email!!!
Note:
raise keyword is best suitable for customized exceptions but not for pre defined
exceptions
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
22 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
PYTHON LOGGING
Logging the Exceptions:
It is highly recommended to store complete application flow and exceptions information
to a file. This process is called logging.
logging levels:
Depending on type of information, logging data is divided according to the following 6
levels in Python.
table
By default while executing Python program only WARNING and higher level messages will
be displayed.
logging.basicConfig(filename='log.txt',level=logging.WARNING)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The above line will create a file log.txt and we can store either WARNING level or higher
level messages to that file.
After creating log file, we can write messages to that file by using the following methods.
logging.debug(message)
logging.info(message)
logging.warning(message)
logging.error(message)
logging.critical(message)
Q.Write a Python program to create a log file and write WARNING and higher
level messages?
1) import logging
2) logging.basicConfig(filename='log.txt',level=logging.WARNING)
3) print("Logging Module Demo")
4) logging.debug("This is debug message")
5) logging.info("This is info message")
6) logging.warning("This is warning message")
7) logging.error("This is error message")
8) logging.critical("This is critical message")
log.txt:
Note:
In the above program only WARNING and higher level messages will be written to log file.
If we set level as DEBUG then all messages will be written to log file.
1) import logging
2) logging.basicConfig(filename='log.txt',level=logging.DEBUG)
3) print("Logging Module Demo")
4) logging.debug("This is debug message")
5) logging.info("This is info message")
6) logging.warning("This is warning message")
7) logging.error("This is error message")
8) logging.critical("This is critical message")
log.txt:
1) DEBUG:root:This is debug message
2) INFO:root:This is info message
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
24 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) WARNING:root:This is warning message
4) ERROR:root:This is error message
5) CRITICAL:root:This is critical message
Note: We can format log messages to include date and time, ip address of the client etc
at advanced level.
By using the following function we can write exceptions information to the log file.
logging.exception(msg)
1) import logging
2) logging.basicConfig(filename='mylog.txt',level=logging.INFO)
3) logging.info("A New request Came:")
4) try:
5) x=int(input("Enter First Number: "))
6) y=int(input("Enter Second Number: "))
7) print(x/y)
8) except ZeroDivisionError as msg:
9) print("cannot divide with zero")
10) logging.exception(msg)
11) except ValueError as msg:
12) print("Enter only int values")
13) logging.exception(msg)
14) logging.info("Request Processing Completed")
15)
16)
17) D:\Python_classes>py test.py
18) Enter First Number: 10
19) Enter Second Number: 2
20) 5.0
21)
22) D:\Python_classes>py test.py
23) Enter First Number: 10
24) Enter Second Number: 0
25) cannot divide with zero
26)
27) D:\Python_classes>py test.py
28) Enter First Number: 10
29) Enter Second Number: ten
30) Enter only int values
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
mylog.txt:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
PYTHON DEBUGGING BY USING ASSERTIONS
Debugging Python Program by using assert keyword:
The process of identifying and fixing the bug is called debugging.
Very common way of debugging is to use print() statement. But the problem with the
print() statement is after fixing the bug,compulsory we have to delete the extra added
print() statments,otherwise these will be executed at runtime which creates performance
problems and disturbs console output.
To overcome this problem we should go for assert statement. The main advantage of
assert statement over print() statement is after fixing bug we are not required to delete
assert statements. Based on our requirement we can enable or disable assert statements.
Hence the main purpose of assertions is to perform debugging. Usully we can perform
debugging either in development or in test environments but not in production
environment. Hence assertions concept is applicable only for dev and test environments
but not for production environment.
1. Simple Version
2. Augmented Version
1. Simple Version:
assert conditional_expression
2. Augmented Version:
assert conditional_expression,message
Eg:
1) def squareIt(x):
2) return x**x
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) assert squareIt(2)==4,"The square of 2 should be 4"
4) assert squareIt(3)==9,"The square of 3 should be 9"
5) assert squareIt(4)==16,"The square of 4 should be 16"
6) print(squareIt(2))
7) print(squareIt(3))
8) print(squareIt(4))
9)
10) D:\Python_classes>py test.py
11) Traceback (most recent call last):
12) File "test.py", line 4, in <module>
13) assert squareIt(3)==9,"The square of 3 should be 9"
14) AssertionError: The square of 3 should be 9
15)
16) def squareIt(x):
17) return x*x
18) assert squareIt(2)==4,"The square of 2 should be 4"
19) assert squareIt(3)==9,"The square of 3 should be 9"
20) assert squareIt(4)==16,"The square of 4 should be 16"
21) print(squareIt(2))
22) print(squareIt(3))
23) print(squareIt(4))
24)
25) Output
26) 4
27) 9
28) 16
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com