C3 Py
C3 Py
Modules in Python
===============================================
Index
---------
=>Purpose of Modules
=>Definition of Module
=>Types of Modules
=>Number of Approaches to Re-use the Modules
a) By Using import statement
b) By Using from ... import statement
=>Programming Examples
=>Re-Loading the Modules
=>Programming Examples
-------------------------------------------------------------------------------------------------------
=============================================
Modules in Python
=============================================
=>We know that Functions concept makes us to understand How to perform
operations and we can re-use within the same program but not able to re-use the
functions across the programs.
=>To reuse the functions and global variables across the programs, we must use
the concept of MODULES.
---------------------------------------
=>Definition of Module:
---------------------------------------
=>A Module is a collection of variables (global variables) , Functions and Classes.
-----------------------------------
=>Types of Modules:
-----------------------------------
=>In Python Programming, we have two types of Modules. They are
1) Pre-defined (or) Built-in Modules
2) Programmer or user or custom-defined modules.
-----------------------------------------------------
1) Pre-defined (or) Built-in Modules:
----------------------------------------------------
=>These modules are developed by Python Language Developers and they are
avialable in Python Software (APIs) and they are used python programmers for
dealing with Universal Requirements.
=>After developing step-1, step-2 and step-3 , we must save on some file name
with an extension .py (FileName.py) and it is treated as module name.
=>When a file name treated as a module name , internally Python execution
environment creates a folder automatically on the name of __pycache__ and it
contains module name on the name of "filename.cpython-310.pyc ".
-------------------
Examples:
------------------
__pycache__ <-----Folder Name
-------------------------------------------
aop.cpathon-310.pyc <-------------------Module
Name
mathsinfo.cpython-310.pyc<--------------Module
Name
icici.cpython-310.pyc<----------------------Module
Name
----------------------------------------------
===============================================
Number of approaches to re-use Modules
===============================================
=>We know that A Module is a collection of variables, Functions and Classes.
=>To re-use the features(Variable Names, Function Names and Class Names ) of
module, we have 2 approaches.They are
1) By using import statement
2) By using from.... import statement.
---------------------------------------------------------------------------------------
1) By using import statement:
---------------------------------------------------------------------------------------
=>'import' is a keyword
=>The purpose of import statement is that "To refer or access the variable names,
function names and class names in current program"
=>we can use import statement in 4 ways.
-------------------
=>Syntax-1: import module name
-------------------
=>This syntax imports single module
----------------
Example: import icici
import aop
import mathsinfo
--------------------------------------------------------------------
=>Syntax-2: import module name1, module name2....Module name-n
-------------------
=>This syntax imports multiple modules
----------------
Example: import icici , aop, mathsinfo
--------------------------------------------------------------------------------------------------------
--------------------
=>Syntax-3: import module name as alias name
-------------------
=>This syntax imports single module and aliased with another name
----------------
Example: import icici as i
import aop as a
import mathsinfo as m
--------------------------------------------------------------------------------------------------------
--------------------
=>Syntax-4: import module name1 as alias name, module name2 as alias
name......module name-n as alias name
-------------------
=>This syntax imports multiple modules and aliased with another names
----------------
Example: import icici as i, aop as a , mathsinfo as m
=>Hence after importing all the variable names, Function names and class names
by using "import statement" , we must access variable names, Function names
and class names w.r.t Module Names or alias names.
Module Name.Variable Name
Module Name.Function Name
Module Name.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name
==============================================================
==============
2) By using from.... import statement.
=======================================
=>Here "form" "import" are the key words
=>The purpose of from.... import statement is that " To refer or access the
variable names, function names and class names in current program directly
without writing module name as alias name of Module name."
=> we can use from.... import statement in 3 ways.
-------------------
Syntax-1: from module name import Variable Names,Function Names, Class
Names
------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a
module.
--------------------------------------------------------------------------------------------------------
---
Syntax-2: from module name import Variable Names as alias name,Function
Names as
alias name , Class Names as alias names.
-----------------------------------------------------------------------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a
module with alias Names
Example: from calendar import month as m
from aop import addop as a,subop as s, mulop as m
from mathinfo import pi as p ,e as k
from icici import bname as b,addr as n , simpleint as si
--------------------------------------------------------------------------------------------------------
-------------
Syntax-3: from module name import *
---------------
=>This syntax imports ALL Variable Names,Function Names, Class Names of a
module.
=>This syntax is not recommmended to use bcoz it imports required Features of
Module and also import un-interrested features also imported and leads more
main memory space.
=>Hence after importing all the variable names, Function names and class names
by using "from ....import statement" , we must access variable names, Function
names and class names Directly without using Module Names or alias names.
Variable Name
Function Name
Class Name
=>Hence with "import statement" we can give alias name for module names only
but not for Variables Names, Function Names and Class Names. Where as with
"from ... import statement " we can give lias names for Variables Names, Function
Names and Class Names but not for Module Name.
=======================================X======================
===========
==========================================
realoding a modules in Python
==========================================
=>To reaload a module in python , we use a pre-defined function called reload(),
which is present in imp module and it was deprecated in favour of importlib
module.
=>Syntax:- imp.reload(module name)
(OR)
importlib.reload(module name) ----->recommended
----------------------------------
=>Purpose / Situation:
-----------------------------------
=>reaload() reloads a previously imported module.
=>if we have edited the module source file by using an external editor and we
want to use the changed values/ updated values / new version of previously
loaded module then we use reload().
===================================X==========================
============
#shares.py---file and treated as module name
def sharesinfo():
d={"Tech":19,"Pharma":11,"Auto":1,"Finance":00}
return d
#main program
#sharesdemo.py
import shares
import time
import importlib
def disp(d):
print("-"*50)
print("\tShare Name\tValue")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t:{}".format(sn,sv))
else:
print("-"*50)
#main program
d=shares.sharesinfo()
disp(d)
time.sleep(15)
importlib.reload(shares) # relodaing previously imported module
d=shares.sharesinfo() # obtaining changed / new values of previously imported
module
disp(d)
Packages in Python
=========================================
Index
-----------
=>Purpose of Package
=>Definition of Package
=>Development of Package
=>Number of Approaches to re-use Packages
a) By Using sys.path.append()
b) By using PYTHONPATH Environmental Variable
=>Programming Examples
--------------------------------------------------------------------------------------------------------
-----------
Package in Python
=============================================
=>The Function concept is used for Performing some operation and provides
code re-usability within the same program and unable to provide code re-
usability across programs.
=>To deal with the package, we need to the learn the following.
a) create a package
b) re-use the package
--------------------------------------------------------------------------------------------------
a) create a package:
----------------------------
=>To create a package, we use the following steps.
i) create a Folder
ii) place / write an empty python file called __init__.py
iii) place / write the module(s) in the folder where is it
considered as Package
Name
Example:
--------------
bank <-----Package Name
-----------
__init__.py <----Empty Python File
simpleint.py <--- Module Name
aop.py-----Module Name
icici1.py---Module Name
welcome.py <--- Module Name
========================================================
b) re-use the package
---------------------------------
=>To the re-use the modules of the packages across the folders / drives /
enviroments, we have to two approaches. They are
i) By using sys module
ii) by using PYTHONPATH Environmental Variable Name
------------------------------------------------------------------------------------------
i) By using sys module:
-------------------------------------
Syntax:
----------- sys.path.append("Absolute Path of Package")
Example:
sys.path.append("E:\\KVR-PYTHON-6pM\\ACKAGES\\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-6PM\ACKAGES\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-6PM/ACKAGES/BANK")
-----------------------------------------------------------------------------------------------
ii) by using PYTHONPATH Enviromental Variables:
------------------------------------------------------------------------
=>PYTHONPATH is one of the Enviromental Variable
=>Search for Enviromental Variable
Steps for setting :
------------------------------
Var name : PYTHONPATH
Var Value : E:\KVR-PYTHON-7AM\PACKAGES\BANK
============================================
Exaception Handling
============================================
Index
---------
=>Purpose of Exception Handling
=>Types of Errors
i) Compile Time Errors
ii) Logical Errors
iii) Runtime Errors
=>Definition of Exception
=>Definition of Exception handling
=>Types of Exceptions.
a) Pre-defined Exceptions
b) Programmer-Defined Exceptions
=>Handling Exceptions
=>Keywords for Handling Exceptions
1. try
2. except
3. else
4. finally
5. raise
=>Syntax for Handling Exceptions
=>Programming Examples
---------------------------------------------------------------------
=>Development of Programmer-Defined Exceptions
=>Programming Examples
--------------------------------------------------------------------
=>ATM Case Study
================================================
Building Blocks of Exception Handling
================================================
1. When the application user or end user enters Invalid Input then we get Run
time Errors.
( Invalid Input----->Run time Error )
2. By default Runtime Erros always generates Technical Error Messages.
-------------------------------------
3. Definition of Exception: Every Runtime Error is called Exception
------------------------------------- ( Invalid Input---->Runtime Error------>Exception )
Hence Every Valid Input gives Result.
Every InValid Input gives Exception.
================================================
Types of Errors in Exception Handling
================================================
=>The Purpose of Exception Handling is that " To Build Robust (Strong)
Applications ".
=>In Real Time, To develop any project, we must choose one programming
language and by using that language, we develop, compile and execute the
programs. During this process we get 3 types of Errors. They are
1. try
2. except
3. else
4. finally
5. raise
--------------------------------------------------------------------------------------------------------
-----------
Syntax for handling the exceptions
--------------------------------------------------------------------------------------------------------
-----------
try:
Block of statements
Generating Exceptions
except <exception-class-name-1>:
Block of statetements generates
User-Friendly Error Messages
except <exception-class-name-2>:
Block of statetements generates
User-Friendly Error Messages
---------------------------------------------------
---------------------------------------------------
except <exception-class-name-n>:
Block of statetements generates
User-Friendly Error Messages
else:
Block of statetements generates
Results
finally:
Block of statetements executes
compulsorily
--------------------------------------------------------------------------------------------------------
-----------
except
else
finally
=======================================
Types of Exceptions in Python
=======================================
=>In Python Programming, we have 2 types of exceptions. They are
Syntax: try:
----------------------
----------------------
except :
------------------------------------
------------------------------------
------------------
Examples: Refer Div5.py Program
-----------------
-----------------------------------------------------------------------------------------------------
Standard Syntax-1:
try:
Block of statements
Generating Exceptions
except <exception-class-name-1>:
Block of statetements generates
User-Friendly Error Messages
except <exception-class-name-2>:
Block of statetements generates
User-Friendly Error Messages
---------------------------------------------------
---------------------------------------------------
except <exception-class-name-n>:
Block of statetements generates
User-Friendly Error Messages
except : #default Exception block
default error messages
else:
Block of statetements generates
Results
finally:
Block of statetements executes
compulsorily
(OR)
ry:
------------------------------------
------------------------------------
except (exceptio-class-1,exceptio-class-2,...exceptio-class-n):
-------------------------------------------
Multiple User-friendly Error Messages
------------------
Examples: Refer Div6.py Program
-----------------
===================================x==========================
===========
=============================================
Development of Programmer-Defined Exceptions
=============================================
=>These exceptions are defined and developed by Python Programmers and they
are available as part of Python Project and used by other python Programmers
who are in the project for dealing with Common Problems.
=>Some of the Common Problems are
a) Attempting to enter Invalid PIN
b) Attemmpting to enter Wrong User Name and Password
c) Attempting to withdraw more amount than existing
...............................etc
--------------------------------------------------------------------------------------------------------
------------
=>Steps for Developing Programming Exceptions.
--------------------------------------------------------------------------------------------------------
------------
Step-1: Choose the Programmer-defined class name
Step-2: The Programmer-defined class name must Inherit from Base class
exception called "Exception
or BaseExeception"
Step-3: The above development must be saved on some file name with an
extension.py (Module
Name)
--------------------------------------------------------------------------------------------------------
------------------------------------
Example: class LoginError(Exception):pass
class InSuffBal(BaseException):pass
=>Here LoginError and InSuffBal are comes under Programmer-defined
Exception sub classses.
--------------------------------------------------------------------------------------------------------
------------------------------------
=================================================
raise key word
=================================================
=>raise keyword is used for hitting / raising / generating the exception provided
some condition must be satisfied.
=>raise keyword always used inside of Function Definition only.
=>PVM uses raise keyword implicitly for hitting pre-defined Exception where as
Programmer makes the PVM to use raise keyword explicitly for Hitting or
Generating Programmer-defined Exceptions.
Examples:
-------------------
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError
else:
return (a/b)
-----------------------------------------------------------------------------
============================================
Data Persistenecy by Files of Python
============================================
-------------------
Def. of File:
-----------------------------------------------------
=>A File is a collection of Records.
=>Files Resides in Secondary Memory(HDD).
=>Technically, File Name is a named location in Secondary Memory.
-----------------------------------------------------
=>All the objects data of main memory becomes records in File of Secondary
memory and records of file of secondary memory becomes the objects in main
memory.
----------------------------------------------------
Def. of Stream:
----------------------------------------------------
=>The Flow of Data between object(s) of Main Memory and Files of Seconday
memory is called
Stream.
--------------------------------------------------------------------------------------------------------
--------------------------
=================================================
Types of Application in Files
=================================================
=>The purpose of Files in any programming language is that " To maintain Data
Persistency".
=>The Process of storing the data permanently is called Data Persistency.
=>In this context, we can develop two types of applications. They are
1) Non-Persistant Applications
2) Persistant Applications
=>In Non-Persistant Applications development, we read the data from Keyboard ,
stored in main memory(RAM) in the form objects, processed and whose results
displayed on Moniter.
Examples: ALL our previous examples comes under Non-Persistant
Applications.
1) Write Operation:
-----------------------------
=>The purpose of write operation is that " To transfer or save the object data of
main memory as record in the file of secondary memory".
=>Steps:
1) Choose the File Name
2) Open the File Name in Write Mode
3) Perform cycle of Write Operations.
=>While we are performing write operations, we get the following exceptions.
a) IOError
b) OSError
c) FileExistError
------------------------------
2) Read Operation:
------------------------------
=>The purpose of read operation is that " To transfer or read the record from file
of secondary memory into the object of main memory".
=>Steps
a) Choose the file name
b) Open the file name in Read Mode
c) Perform cycle of read operations.
=>While we performing read operations, we get the following exceptions.
a) FileNotFoundError
b) EOFError
================================x=============================
============
======================================
File Opening Modes
======================================
=>The purpose of File Opening Modes is that "In which type file mode we are
opening the file".
=>In Python Programming, we have 8 File Opening Modes. They are
1. r 2. w 3. a 4. r+ 5. w+ 6. a+ 7. x 8. x+
-----------------------------------------------------------------------------------------------
1) r
-----------------------------------------------------------------------------------------------
=>This mode is used for opening the file name in READ Mode.
=>If we open the file name in 'r' mode and if the file name does not exist then we
get
FileNotFoundError.
=>"r" mode is default mode of all file opening modes.
-----------------------------------------------------------------------------------------------
2) w
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "w" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "w" then EXISTING FILE Data
OVERLAPPED with new Data.
-----------------------------------------------------------------------------------------------
3) a
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "a" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "a" then EXISTING FILE Data APPENDED
with new Data.
-----------------------------------------------------------------------------------------------
4) r +
-----------------------------------------------------------------------------------------------
=>This mode is used for opening the file name in READ Mode.
=>If we open the file name in 'r+' mode and if the file name does not exist then we
get
FileNotFoundError.
=>With "r+" mode, First we Must read the data and Later we can perform Write
Operation.
--------------------------------------------------------------------------------------------------------
----------------------------------------
5) w +
--------------------------------------------------------------------------------------------------------
------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "w" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "w" then EXISTING FILE Data
OVERLAPPED with new Data.
=>With "w+" mode , Additionally we can perform Read Operation After
Performing Write Operation.
--------------------------------------------------------------------------------------------------------
-----------------------------------
6) a+
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "a+" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "a+" then EXISTING FILE Data APPENDED
with new Data.
=>With "a+" mode , Additionally we can perform Read Operation After
Performing Write Operation.
--------------------------------------------------------------------------------------------------------
--------------------------------------
7) x
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and exclusively Opening the file
name in WRITE Mode
always.
=>Once we open File Name in "x" mode , we can Perform Write Operations only.
=>If we open existing file in "x" mode then we get FileExistError
--------------------------------------------------------------------------------------------------------
------------------
8) x+
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and exclusively Opening the file
name in WRITE Mode always.
=>Once we open File Name in "x+" mode , we can Perform Write Operations First
and Letter we can Perform Read Operations also
=>If we open existing file in "x+" then we get FileExistError
--------------------------------------------------------------------------------------------------------
------------------
=========================================
Opening Files
=========================================
=>To perform any type of Operation, we must open the file.
=>In Python Programming, To open the file, we have two approaches. They are
1. By using open()
2. By using " with open() as "
--------------------------------------------------------------------------------------------------------
-----------
1) By using open()
--------------------------------------------------------------------------------------------------------
-----------
=>Syntax: varname=open("File Name","File Mode")
--------------------
Explanation
--------------------
=>varname represents File Pointer and always points to the content of file and it
is an object of type TextIOWrapper
=>open() is one of the pre-defined Function, which is used for opening the
specified File Name
in Specified File Mode
=>File Name represents Name of the file
=>File Mode represents r,w,a,r+,w+,a+,x,x+
=>When we open the file with open() then it is recommended to close the file
manually by
using close(). In otherwords open() does not provide auto-closability of Files.
--------------------------------------------------------------------------------------------------------
-----------
2) By using " with open() as "
--------------------------------------------------------------------------------------------------------
-----------
Syntax:- with open("File Name","File Mode") as Varname:
----------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
-------------------------------------------------------------------
Other statemenets out-of "with open() as " statements
--------------------------------------------------------------------
Explanation:
-------------------
=>Here "with" and "as" are are the key words
=>open() is one of the pre-defined Function, which is used for opening the
specified File Name
in Specified File Mode
=>varname represents File Pointer and always points to the content of file and it
is an object
of type TextIOWrapper
=>File Name represents Name of the file
=>File Mode represents r,w,a,r+,w+,a+,x,x+
=>The advantage of " with open() as " is that "Auto-Closability of File. In
Otherwords, as long as PVM is executing Indentation block of " with open() as "
then File Name is Active(Open) and Once PVM comes out-of Indentation block of
" with open() as" then File Name closed automatically (no need to use close() ).
==============================X===============================
==========
==============================================
Writing the data to the File
==============================================
=>To write the data to the file, we have 2 pre-defined Functions in file pointer
object. They are
1) write()
2) writelines()
--------------------------------------------------------------------------------------------------------
----------
1)write()
--------------------------------------------------------------------------------------------------------
----------
=>Syntax: filepointerobj.write(strdata)
=>This Function is used for writing any type of Data to the file in the form of str
=>Examples: refer FileWriteEx1.py
--------------------------------------------------------------------------------------------------------
----------
2)writelines()
--------------------------------------------------------------------------------------------------------
----------
=>Syntax: filepointerobj.writelines(Iterable-object)
=>This Function is used for writing any type of Iterable Object to the file in the
form of str
=>Examples: refer FileWriteEx2.py
--------------------------------------------------------------------------------------------------------
----------
==============================================
Reading the Data from File
==============================================
=>To read the data from the file, we have 2 pre-defined functions present File
Pointer object. They are
1) read()
2) readlines()
--------------------------------------------------------------------------------------------------------
------------------
1) read()
--------------------------------------------------------------------------------------------------------
------------------
=>Syntax:- varname=filepointerobj.read()
=>This Function is used for reading the entire data from file and placed in LHS
Varname in the form of
str.
----------------
Examples:
----------------
--------------------------------------------------------------------------------------------------------
------------------
2) readline()
--------------------------------------------------------------------------------------------------------
------------------
=>Syntax:- varname=filepointerobj.readlines()
=>This Function is used for reading the entire data from file the form of Line by
line and placed in LHS
Varname in the form of list object.
------------------
Examples:
------------------
--------------------------------------------------------------------------------------------------------
------------------
================================
Types of Files
================================
=>In Python Programming, we have two types of Files. They are
a) Text Files
b) Binary Files
1) Text File:
--------------------
=>A Text File always contains Alphabets, Digits and Special Symbols.
=>Text Files always denoted by a letter "t"
=>The default file in python is text file.
-------------------------------------------------------
Examples: .py .java .c .cpp .txt .doc....etc
-----------------------------------------------------------------------------------------------------
2) Binary File:
--------------------
=>A BinaryFile always contains Data in Binary Format ( Pixles)
=>Binary Files always denoted by a letter "b"