0% found this document useful (0 votes)
2 views29 pages

Python Unit 3

This document covers Unit-03 of Python Programming, focusing on testing, debugging, exceptions, and assertions. It explains how to handle exceptions using try-except clauses, the types of exceptions, and the debugging process using the pdb module. Additionally, it discusses assertions as a method for sanity-checking code during testing.

Uploaded by

prajapatimeet360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Python Unit 3

This document covers Unit-03 of Python Programming, focusing on testing, debugging, exceptions, and assertions. It explains how to handle exceptions using try-except clauses, the types of exceptions, and the debugging process using the pdb module. Additionally, it discusses assertions as a method for sanity-checking code during testing.

Uploaded by

prajapatimeet360
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Faculty of Engineering & Technology

Sankalchand Patel College of Engineering, Visnagar

Python Programming
(1ET2070201)

Unit-03
Testing, Debugging, Exceptions and Assertions
Content
• Debugging
• Handling Exceptions
• Assertions
Handling Exceptions
• When Python (or any programming language) has an error, it stops
the current execution and displays an error message
• “It raises an exception”
• Example:
>>> 1/0

Traceback (most recent call last):


File "<pyshell#0>", line 1, in -toplevel-
1/0
ZeroDivisionError: integer division or modulo by zero
Handling Exceptions
• Using a try statement with an except clause
• The most basic way to “handle” (or trap) an exception is to use the Python
“try” and “except” clause
• Example
try:
num = int( input( “Enter a number” ))
except:
print (“Something went wrong”)
Handling Exceptions
• Specifying an exception type
• There are different type of exceptions
• IOError
• Raised when an I/O operation fails, such as opening a non-existent file for reading
• IndexError
• Raised when a sequence is indexed with a number out of range
• KeyError
• Raised when a dictionary key is not found
• NameError
• Raised when a name of variable or function is not found
• SyntaxError
• Raised when a syntax error is found
• TypeError
• Raised when a built-in operation or function is applied to an object with the wrong type
• ValueError
• Raised when a built-in operation or function received an argument that has the right type but
inappropriate value
• ZeroDivisionError
• Raised when the second argument of a division or modulo operation is zero
Handling Exceptions
• Specifying an exception type
• Example
try:
num = int( input( “Enter a number” ))
except(ValueError):
print (“Something went wrong”)

• The print statement is only executed if the ValueError exception is raised


Handling Exceptions
• When should you trap exceptions?
• Any point of external interaction with your program
• Opening a file for reading
• Converting data from an outside source such as a user

• If you do not know what exception to trap, test it in interactive mode with
Python
Handling Exceptions
• Handling multiple exception types
• The except clauses can trap multiple types of exceptions
• Example:

for value in (None, “Hello”):


try:
print (“Attempting to convert”, value, “->”)
print (float( value ))
except(TypeError, ValueError):
print (“An error occurred”)
Handling Exceptions
• Handling multiple exception types
• Example:

for value in (None, “Hello”):


try:
print (“Attempting to convert”, value, “->”)
print (float( value ))
except(TypeError):
print (“Can only convert a string or a number”)
except(ValueError):
print (“Problem converting a string of digits”)
Handling Exceptions
• Getting an exception’s argument
• Python allows the program to get the actual error message…(useful for
debugging)
• Example:
try:
num = int( input( “Enter a number” ))
except(ValueError), e:
print (“Data entered was not a number”, e)
Handling Exceptions
• Adding an else clause
• Example:
try:
num = int( input( “Enter a number” ))
except(ValueError), e:
print (“Data entered was not a number”, e)
else:
print (“The value of num is”, num)
Generating Exceptions
raise ExceptionType("message")

• useful when the client uses your object improperly


• types: ArithmeticError, AssertionError, IndexError, NameError,
SyntaxError, TypeError, ValueError

• Example:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...
Debugging

In computer programming and software development,


debugging is the process of finding and resolving bugs
within computer programs, software, or systems.
Debugging
• Debugging in Python is facilitated by pdb module (python
debugger) which comes built-in to the Python standard
library.
• It is actually defined as the class Pdb which internally
makes use of bdb(basic debugger functions) and cmd
(support for line-oriented command interpreters)
modules.
• The major advantage of pdb is it runs purely in the
command line, thereby making it great for debugging code
on remote servers when we don’t have the privilege of a
GUI-based debugger.
pdb supports:
• Setting breakpoints
• Stepping through code
• Source code listing
• Viewing stack traces
To start debugging within the program just insert import pdb,
pdb.set_trace() commands.

Run script normally, and execution will stop where we have


introduced a breakpoint.

So basically we are hard coding a breakpoint on a line below


where we call set_trace().

With python 3.7 and later versions, there is a built-in function


called breakpoint() which works in the same manner. Refer
following example on how to insert set_trace() function.
Command
Command Function
help To display all commands
Display the stack trace and line
where
number of the current line
Execute the current line and move to
next
the next line ignoring function calls
Step into functions called at the
step
current line
From the Command Line: It is the easiest way of using a debugger. You
just have to run the following command in terminal

python -m pdb [Link] (put your file name instead of [Link])

Example 3: Navigating in pdb prompt


We can navigate in pdb prompt using n (next), u (up), d (down). To
debug and navigate all throughout the Python code, we can navigate
using the mentioned commands.
Example 4: Post-mortem debugging using
Python pdb module
Post-mortem debugging means entering debug mode after
the program is finished with the execution process (failure
has already occurred).

pdb supports post-mortem debugging through


the pm() and post_mortem() functions. These functions
look for active trace back and start the debugger at the line
in the call stack where the exception occurred. In the output
of the given example, you can notice pdb appear when an
exception is encountered in the program.
Managing Breakpoints
After adding breakpoints with the help of numbers assigned to them, we can
manage the breakpoints using the enable an disable and remove command.
disable tells the debugger not to stop when that breakpoint is reached,
while enable turns on the disabled breakpoints.

Given below is the implementation to manage breakpoints using Example 4.


Python pdb Breakpoints
While working with large programs, we often want to add a number of
breakpoints where we know errors might occur. To do this you just have
to use the break command. When you insert a breakpoint, the
debugger assigns a number to it starting from

1. Use the break to display all the breakpoints in the program.

Syntax:
break filename: lineno, condition
Assertion
▪ An assertion is a sanity-check that you can turn on or turn off when you are done
with your testing of the program.

▪ The assert keyword is used when debugging code.

▪ The assert keyword lets you test if a condition in your code returns True, if not,
the program will raise an AssertionError.

▪ The easiest way to think of an assertion is to liken it to 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.
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in
version 1.5

The syntax for assert is :


assert Expression[, Arguments]

Parameters:

condition : The boolean condition returning true or false.

error_message : The optional argument to be printed in


console in case of AssertionError
Example

Output:
Example:

Output: ----------->
Example:

You might also like