0% found this document useful (0 votes)
10 views57 pages

PP Unit-Iii

The document covers Python modules and exception handling, detailing how to import and use modules, as well as the structure and functionality of exception handling in Python. It explains the concept of modules as files containing Python code, and outlines the process of handling exceptions using try, except, and finally blocks. Additionally, it discusses predefined and user-defined exceptions, packages, and the advantages of using packages in Python programming.

Uploaded by

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

PP Unit-Iii

The document covers Python modules and exception handling, detailing how to import and use modules, as well as the structure and functionality of exception handling in Python. It explains the concept of modules as files containing Python code, and outlines the process of handling exceptions using try, except, and finally blocks. Additionally, it discusses predefined and user-defined exceptions, packages, and the advantages of using packages in Python programming.

Uploaded by

adithyaaa.k7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

UNIT-III

Modules
Exception
Handling
Topics to be covered:
Modules:
Importing module,
Math module,
Random module,
Packages
Exception Handling:
Exception,
Exception Handling,
Except clause, Try? Finally clause User Defined
Exceptions
A group of lines with some name is called a
Function.
A group of functions saved to a file, is called
Module
A group of Modules is nothing but Library.
 Python module is but a piece of code.
 Exiting the interpreter destroys all functions and
variables we created. But when we want a longer
program, we create a script.
 With Python, we can put such definitions in a file, and
use them in a script, or in an interactive instance of the
interpreter. Such a file is a module.
 A python module can be defined as a python program
file which contains a python code including python
functions, class, or variables.
 In other words, we can say that our python code file
saved with the extension (.py) is treated as the module.
 We may have a runnable code inside the python module.
 Modules in Python provides us the flexibility to organize
the code in a logical way.
 To use the functionality of one module into another, we
must have to import the specific module.
A group of functions, variables and classes
saved to a file, which is nothing but module.
Every python file(.py) acts as module.

Demo module contains one variable and 2


functions.
If we want to use members of module in our
program then we should import that module .
import modulename
We can access members by using module
name.
modulename. Variable
modulename.funcion()

Whenever we are using a module in our


program, for that module compiled file will
be generated and stored in the hard disk
permanently.
Renaming a module at the time of import
(module aliasing):

from…import:
We can import particular members of module by
using from…import.
The main advantage of this is we can access
members directly without using module name.
 We can import all members of a module import*
 from Demo import*

 Various possibilities of import:


 import modulename
 import module1,module2,module3
 import module1 as m
 import module1 as m1,module2 as m2,module3
 from module import member
 from module import member1,member2,member3
 from module import member1 as x
 from module import*
Reloading a module:
By default module will be loaded only once even
though we are importing multiple times.
In the above program test module will be
loaded only once even though we are importing
multiple times.
The problem in this approach is after loading a
module if it is updates outside then updates
version of module1 is not available to our
program.
We can solve this problem by reloading module
explicitly based on our requirement.
We can reload by using reload() function from
imp module.
The main advantage of explicit module
reloading is we can ensure that updates version
is always available to our program.
Finding members of module by using dir()
function:
Python provides inbuilt function dir() to list out
all members of current module or a specified
module.
dir()To list out all members of current module.
dir(moduleName)To list out all members of
specified module.
For every module at the time of execution
Python Interpreter will add some special
properties automatically for internal use.
The special variable__name__:
For every Python program, a special varaible
__name__ will be added internally.
This variable stores information regarding
whether the program is executed as an
individual program or as a module.if the
program executed as an individual program
then the valu of this varaible is __main__
If the program executed as a module from some
other program then the value of this variable is
the name of module where it is defined.
Hence by using this __name__ variable we can
identify whether the program executed directly
or as a module.
Math module:
Python provides inbuilt module math.
Tis module defines several functions which can
be used for mathematical operations.
1.sqrt()
2.ceil()
3.floor()
4.fabs()
5.log(x)
6.sin(x)
7.tan(x)

Note: We can find help for any module by using


help() function
random module:
This module defines several functions to
generate random numbers.
We can use these functions while developing
games, in cryptography and to generate random
numbers on fly for authentication.
1.random():
This function always generates some float value
between 0 and 1 (not inclusive)
0<x<1
2.randomint():
To generate random integer between two given
numbers(inclusive)
3.uniform():
It returns random float values between 2 given
numbers (not inclusive)

random()in between 0 and 1(not inclusive)


randint(x,y)in between x and y(inclusive)
uniform(x,y)in between x and y (not inclusive)
randrange([start],sop,[step]):
Returns a random number from range
Startx<stop
Start argument is optional and default value is 0
Step argument is optional and default value is 1
choice():
It wont return random number
It will return a random object from the given list
or tuple.
Exception Handling:
In programming language there are two
types of errors are possible.
1.Syntax Errors
2.Runtime Errors
Syntax Errors:
The errors which occurs because of invalid
syntax are called syntax errors.
Runtime Errors:
It is also known as exceptions.
While executing the program if something goes
wrong because of end user input or
programming logic or memory problems etc
then we will get Runtime Errors.
print(10/0)ZeroDivisionError: division by zero
print(10/”Ten”)TypeError:Unsupported operand
type(s) for/:’int’ and ‘str’
Note: Exception Handling concept applicable for
Runtime Errors but not for syntax errors.
What is Exception?
An exception is an event, which occurs during the

execution of a program, that disrupts the normal flow of


the program's instructions.
In general, 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.

When a Python script raises an exception, it must either

handle the exception immediately otherwise it would


terminate and come out.
Python Exceptions
 An exception can be defined as an abnormal condition in a
program resulting in the disruption in the flow of the
program.
 Whenever an exception occurs, the program halts the
execution, and thus the further code is not executed.
 Therefore, an exception is the error which python script is
unable to tackle with.
Common Exceptions
 A list of common exceptions that can be thrown from a
normal python program is given below.
 ZeroDivisionError: Occurs when a number is divided by
zero.
 NameError: It occurs when a name is not found. It may be
local or global.
 IndentationError: If incorrect indentation is given.
 IOError: It occurs when Input Output operation fails.
 EOFError: It occurs when the end of the file is reached, and
yet operations are being performed.
Default Exception Handling in Python:
Every exception in Python is an object.
For every Exception type the corresponding
classes are available.
Whenever 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. Rest of the program won’t be
executed.
Every Exception in Python is a class.
All exception classes are child classes of
BaseException.i.e every exception class extends
Base Exception either directly or indirectly.
Hence BaseException acts as root for python
Exception Hierarchy.
In-built Python Exception classes:
NOTE: We are calling them exception class as
all these are defined in python as classes.
Exception handling in python
If the python program contains suspicious code
that may throw the exception, we must place
that code in the try block.
The try block must be followed with the except
statement which contains a block of code that
will be executed if there is some exception in
the try block.
try block:
 The try block is used to put the whole code that is to be
executed in the program(which you think can lead to exception),
if any exception occurs during execution of the code inside the
try block, then it causes the execution of the code to be directed
to the except block and the execution that was going on in the
try block is interrupted.
 But, if no exception occurs, then the whole try block is executed
and the except block is never executed.
The except block
 The try block is generally followed by the except block which
holds the exception cleanup code(exception has occured, how to
effectively handle the situation) like some print statement to
print some message or may be trigger some event or store
something in the database etc.
 In the except block, along with the keyword except we can also
provide the name of exception class which is expected to
occur. In case we do not provide any exception class name, it
catches all the exceptions, otherwise it will only catch the
exception of the type which is mentioned.
Try with multiple except block:
 The way of handling exception is varied from exception
to exception.
 Hence for every exception type a separate except block
we have to provide. i.e. try with multiple except blocks is
possible and recommended to use.
 If try with multiple except blocks available then based on
raised exception the corresponding except block will be
executed.
try:
--------
--------
--------
Except ZeroDivision Error:
perform alternative
arithmetic operations
Except FileNotFoundError:
use local file instead of remote file
Single except block ha can handle multiple
exceptions:

We can write 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.
Default except block:
We can use default except block to handle any
type of exceptions.
In default except block generally we can print
normal error messages.
Syntax:
except:
statements
 If try with multiple excepts blocks available
then default except block should be last,
otherwise we will get SyntaxError.

The following are various possible combinations


of except block:
 except ZeroDivisionError :
 except ZeroDivisionError as msg:
 except (ZeroDivisionError, ValueError):
 except (ZeroDivisionError, ValueError) as msg:
 except:
finally block:
The specialty of finally block is it will be
executed always whether exception raised or
not and whether exception handled or not
handled.
Syntax:
try:
 Risky code
except:
 Handling Code
finally:
 cleanup code
There is only one situation where finally block
won’t be executed i.e. whenever we are using
os._exit(0) function.
whenever we are using os._exit(0) function then
PVM itself will be shutdown.
Where 0 represents status code and it
indicates normal termination
These are multiple status codes are possible.
Whether it is ZERO or NON-ZERO there is no
change in the result in the program.
else block with try-except-finally:
We can use else block with try-except-finally blocks.
Else block will be executed if and only if there are no
exceptions inside try block.
Syntax:
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 and handled or not handled.
Types of Exceptions:
In python there are two types of exceptions.
1.Predefined exceptions.
2.User defined Exceptions.
1.Predefined Exceptions:
Also known as in-built exceptions.
The exceptions which are raised automatically by
PVM whenever a particular event occurs, are
called pre defined exceptions.
Examples:
ZeroDivisionError
ValueError..etc
Packages:
 It is an encapsulation mechanism to group related modules into
a single unit.
 Package is nothing but folder or directory which represents
collection of Python modules.
 Any folder or directory contains __init__.py file, is considered as
Python package.
 This file can be empty.
 A package contains sub-packages also.
 A package is basically a directory with Python files and a file
with the name __init__.py.
 This means that every directory inside of the Python path,
which contains a file named __init__.py, will be treated as a
package by Python. It's possible to put several modules into a
Package.
Advantages:
 We can resolve naming conflicts.
 We can identify our components uniquely.
 It improves modularity of the application.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy