0% found this document useful (0 votes)
50 views425 pages

Python New

Uploaded by

dinesh kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
50 views425 pages

Python New

Uploaded by

dinesh kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 425

Python

1
<PYTHON>
===============================================
Real Time Applications of Python
===============================================
=>With Programming, we can develop 22+ Real Time Applications

1) Web Applications Development----->


a) Java------>Servlets , JSP
b) C#.net---->ASP.net
c) Python---->Django,Falsk, Bottle. etc
2) Gaming Application Development.
3) Artificial Intelligence-----Machine Learning and Deep
Learning
4) Desk top GUI Applications
5) Image Processing applications.
6) Text Processing Applications
7) Business Applications.
8) Audio and Video Based Applications
9) Web Scrapping Applications / Web Harvesting Applications
10) Data Visulization.
11) Complex Math Calculations.
12) Scientific Applications
13) Software Development
14) Operating System
15) CAD and CAM based Applications
16) Embedded Applications
17) IOT Based Applications
18) Language Applications
19) Automation of Testing
20) Animation Applications
21) Data Analysis and Data Analystics
22) Education Sector
23) Computer Vision

===========================================
Getting started with Python
===========================================
=>History of Python
=>Versions of Python
=>Downloading Process of Python
=============================================================
=>History of Python

=>Python Programming language foundation stone laid in the year 1980.


=>Python Programming language implemetation started in the year 1989.
=>Python Programming language officially released in the year 1991 Feb.
=>Python Programming language developed By GUIDO VAN ROSSUM.
=>Python Programming language developed at CWI Institute in Nether
lands.
=>ABC programming language is the Predecessor of Python Programming
language.
x

=>Versions of Python
====================

2
=>Python Programming Contains two Versions. They are
1) Python 2.x----- Here x ---> 1 2 3 4 5 6 7 -----
outdated---
2) Python 3.x----> here x 1 2 3 4 5 4 6 7 8
9 10
=>Python 3.x does not contain backward compatability with Python 2.x
=>To down load Python 3.x software , we use www.python.org
=>Python Software and its updations are maintained by a Non-Commerical
Organization called " Python Software Foundation(PSF) "

=============================================
Python Programming Inspired from
=============================================
=>Python Programming Inspired from 4 programming language

1) Functional Programming from C


2) Object Oriented Programming from CPP
3) Scripting Programming from PERL
4) Modular Programming from Modulo3
=============================================

============================================
Features of Python
============================================
=>Features of language are nothing but Services (or) Facilities
provided by Language developers which are used by language Programmers
for devolping real time applications.
=>Python Programming provides 11 features . They are
1. Simple
2. Freeware and Open Source
3. Platform Independent
4. Dynamically Typed Programming
5. Interpreted Programming
6. High Level Programming
7. Robust (Strong )
8. Both Procedural and Object Oriented Programming
9. Extensible
10. Embedded
11. Supports Third party APIs---Numpy, Pandas, Scipy,
Scikit, matplotlib
=========================X================================

3
=================
1. Simple
=================
=>Python is one of the Simple Programming Language bcoz 3 technical
factors.
They are

1) Python Provides Rich Set of APIs (Libraries). So that Python


Programmers can Re-Use the pre-defined Code without writing our own
code.
Def Of API (Application Programming Interface):

=>An API is a collection of MODULES.


=>A MODULE is a Collection of FUNCTIONS, VARIABLES and CLASSES
Examples:- math , cmath, calendar, random , datetime....etc
========================================================
2)Python Programming Provide In-Built Garbage Collection Facility. So
that Garbage Collector Collects Un-Used Memory Space and Improves
Performnace of Python Based Applications.
=>Definition of Garbage Collector:

=>A Garbage Collector is one of the in-Built Python Background which


is running behind of Regular Python Program and whose role is to
collect un-used memory and imporoves the Performnace Python Based
Applications.
=>hence Garbage Collector takes about automatic Memory management.
==================================================================
3) Python Provides User-Friendly Syntaxes. So That Python
Programmer can develop Error-Free Programs in limited span of time.

=======================================
2. Freeware and Open Source
=======================================

Freeware:-

=>If we download any software Freely from Orginal Source then it is


called Freeware.
=>Since we download Python Software Freely from www.python.org and
hence Python is one of the Freeware.

Open Source:

=>When we download the python software and whose standard name is


"CPYTHON".
=>In Later days, some vendors came forward and Customized CPYTHON for
their inhouse tools develeopment and such customized versions of
CPYTHON and pYthon software is one of the Open Source and such
customized versions of CPYTHON are called Python Distributions.

4
=>Some of Python Distributions are

1) JPYTHON or JYTHON---->Used To run Java Based Applications


2) IRON PYTHON or IPYTHON-->Used to run C#.NET Applications
3) RUBY PYTHON---->Used to run Ruby Based Applications
4) Micro Python--->Used to develop Micro controller
Applications.
5) Stackless Python---->Used to develop Concurrency Based
Applications.
6) PYPY------>Just for using JIT Compiler....etc

=======================================
3. Platform Independent
=======================================
=>Platform is nothing Type of OS Being Used to run the Program/
Application.
=>" A Languiage is said be Platform Independent if and only if whose
application or programs runs on every OS"
=>Python is one of the Platform Independent bcoz In Python Programming
Execution Environment "ALL VALUES STORED IN THE FORM OF OBJECTS and
Objects are Indepenedent from OS ".

======================================
4. Dynamically Typed Programming
=======================================
=>In General we have two types of Programming Languages. They are
1) Static Typed Programming language
2) Dynamically Typed Programming language

1) Static Typed Programming language:

=>In This Programming languages, we Must declare the variables by using


Data Types otherwise we get Compile Time Errors
Examples: C,CPP,JAVA, .NET...etc

2) Dynamically Typed Programming language


=>In This Programming languages, we need not to declare the variables
explicitly by using data types. So Python Execution Environment decides
the data type depeends on type value we are using in python Program.

Examples: PYTHON

=>Hence In Python Programming, all values are stored in the form of


OBJECTS and behind of OBJECTS, there exists CLASSES.
==========================x=================================

5
===============================================
5. Interpreted Programming
===============================================
=>When we develop any python program, we must give some file name with
an extension .py (File Name.py).
=>When we execute python program, two process takem place internally
a) Compilation Process
b) Execution Process.
=>In COMPILATION PROCESS, The python Source Code submitted to Python
Compiler and It reads the source Code, Check for errors by verifying
syntaxes and if no errors found then Python Compiler Converts into
Intermediate Code called BYTE CODE with an extension .pyc
(FileName.pyc). If erros found in source code then we error displyed
on the console.
=>In EXECUTION PROCESS, The PVM reads the Python Intermediate Code(Byte
Code) and Line by Line and Converted into Machine Understable Code
(Executable or binary Code) and It is read by OS and Processer and
finally Gives Result.
=>Hence In Python Program execution, Compilation Process and Execution
Process is taking place Line by Line conversion and It is one of the
Interpretation Based Programming Language.

Definition of PVM ( Python Virtual Machine)

=>PVM is one program in Python Software and whose role is to read LINE
by LINE of Byte Code and Converted into Machine Understable Code
(Executable or binary Code)

6
================================================
6. High Level Programming
================================================
=>In general, we have two types of Programming languages. They are
a) Low Level Programming Languages.
b) High Level Programming Languages.

a) Low Level Programming Languages:

=>In These Programming Languages, we represent the data in lower level


data like Binary, Octal and Hexa decimal and This type data is not by
default understanble by Programmers and end users.

Examples: - a=0b1111110000111101010---binary data


b=0o23-----octal
c=0xface----Hexa Decimal

b) High Level Programming Languages.

=>In These Programming Languages, Eeve we represent the data in lower


level data like Binary, Octal and Hexa decimal , the High Level
Programming Languages automatically converts into Decimal number System
data, which is understanble by Programmers and end-users and python
is one High Level Programming Language.

Example : Python
=================================x==================================

============================================
7. Robust (Strong )
============================================
=>Python is one of the Robust Programming language bcoz of Python
provides
" Exception Handling " Facility.

Exception:- Every Runtime Error is called Exception


All exceptions by default gives technical Error
Messages

Exception Handling:- The Process of Converting Technical Error


Messages into User-freindly Error
Messages is know as Exception Handling
=>In Real Time Project, to do the above process of we use Exception
handling to make real projects as Robust.

NOTE:

In Real Time Application development, to develop any project, choose


certain programming language.

7
=>Using that programming language, we develop, compile and execute and
during process, we get Various types of Errors.
1) Compile Time Errors( due to syntaxes are not followed)
.py------>.pyc
2) Logical Errors-------(due to wrong representation of
Logic--exeution time)

3) Runtime Errors:

Runtime Errors are those which are occuring during implementation


level.
Runtime Errors occurs due invalid input entered by End User /
Application user

Example : ATM Project----Inserrting card in reverse order


----Invalid PIN
---Invalid Amount --- etc

Python program for validation of Name or Place or thing

Enter Ur Name : rajesh--valid


Enter Ur Name : 123---Invalid
Enter Ur Name: 123abc--inavldi
Enter Ur Name: #4abc%^&*--Invalid
Enter Ur Name: ---invalid

===================================
9. Extensible
===================================

=>The Python programming giving its programming facilities to other


languages and hence Python is one of the extensible Programming
language.

===================================
10. Embedded
===================================
=>Python Programming can call other languages coding segments for
fastest execution

Example: Python code can call C programming Code.


==========================X========================================

=========================================================

8
11. Supports Third party APIs---Numpy, Pandas, Scipy, Scikit,
matplotlib
=============================================================
=>The traditional Python Programming Projects efficiency increased by
Third party APIs like numpy, pandas, matplotlib, scipy, scikit..etc

=>To use Third party APIs , we must install them by using a tool called
PIP PIP3 PIP3.10

==========================================
Data Representation
==========================================
=>Data Representation in Python Programming is nothing storing the
data in main memory of computer.
=>To store the data in main memory of computer, we need Three things.
They are
a) Literals or Values
b) Identifiers or Variables
c) Data Types

a) Literals or Values:

=>Literals are the values entered by Programmer or end user or


application user to real time applications. They are classfied into .
1) Integer Literals (Ex: stno, HTNO, empno,
adhar card no.....etc)
2) Float Literals ( Ex: Marks, percentage , gdp
of india...etc)
3) String Literals (Ex : Names, Places,
Description....etc )
4) Boolean Literals ( Examples: True False)
5) Date Literals.....etc

b) Identifiers or Variables:

=>Once the application user enters the data from Key board to program,
It is the responsibility of Programmer to store data in the form of
Literals or variables
=>hence all Literals or Values or Data must stored in main memory in
the form of Identifiers or Variables otherwise we can't process the
data.

Examples: >>> a=10


>>> b=20
>>> c=a+b
>>> print(a,b,c)-----------------10 20 30

Def. of Variable:

=>A Variable is an Identifier , whose values are changingor Variying


during the exeuction of the Program.

================================================================
Rules for using Variables in Python
================================================================
=>To use variables in python programming, we have the following rules.

9
1) The Variable Name is combination of Alphabets, Digits and Special
Symbol ( _ ).
2) The Varaible Name must starts with either Alphabet or Special
Symbol Under
Score( _ ).
Examples: 123sal=4.5----invalid
-sal=56.56- -invalid
sal=5.6- - -valid
_sal=67.89--valid
sal123=6.7--valid
sal12_=7.8--valid
name="Rossum"---valid
_=46----valid
3) Within Variable Name, special symbols are not allowed exception
underscore ( _ ).

Examples: emp$sal=5.6---invalid
emp-sal=5.6---invalid
emp sal=6.7--invalid
emp_sal=6.7---valid
_emp_sal_ibm=7.8--valid
sal=34- -valid
sal#emp=56------valid bcoz the
symbol # is used in python as commenting
Symbol.

4) No Keywords to be used Variables Names ( Keywords are reserved words


which will have some special meaning to the language compilers).

Examples:
if=34----inavlid
else=5.6---inavlid
if1=34--valid
_else=5.6--valid
int=23---valid---bcoz all the class
names are not keywords
5) All the variable in Python are Case Sensitive.

EXAMPLES:
>>> age=99----valid
>>> AGE=98---valid
>>> Age=97---valid
>>> aGe=96--valid
>>> print(age,AGE,Age,aGe)----99 98 97 96
==============================X====================================

==================================================
Data Types in Python
==================================================
=>The purpose of Data Types in Python is that "To allocate memory space
in main memory of computer".
=>In Python Programming , we have 14 data types and they classified
into 6 types.

I ) Fundamental Catagery Data Types

10
1) int
2) float
3) bool
4) complex
II ) Sequence Catagery Data Types
1) str
2) bytes
3) bytearray
4) range
III) List Catagery Data Types ( Collection Data Types or
Data Structures)
1) list
2) tuple
IV ) Set Catagery Data Types ( Collection Data Types or
Data Structures)
1) set
2) frozenset
V ) dict Catagery Data Types ( Collection Data Types or
Data Structures)
1) dict
VI ) NoneType Catagery Data Types
1) NoneType

11
==================================================
I ) Fundamental Catagery Data Types
==================================================
=>The purose of Fundamental Catagery Data Types is that "To allocate memory
space
space for storing single value:"
=>In Python Programming, we have 4 types in Fundamental Catagery. They are
1) int
2) float
3) bool
4) complex

12
===========================================
1) int
===========================================
=>'int' is one of the pre-defined class
=>The purpose of int data type is that "To store Integer or Intergral
values(Number
without any decimal values) in main memory of computer".

Examples:

Instructions in Pytrhon Outputs


>>> a=123
>>> print(a) 123
>>> print( type(a) ) <class 'int'>
>>> print(a, type(a))---------------------------------- 123 <class
'int'>
>>> print(a, type(a), id(a))-------------------------123 <class 'int'>
2076700446768

>>> a=12
>>> b=13
>>> c=a*b
>>> print(a, type(a))---------------------------- 12 <class 'int'>
>>> print(b, type(b))---------------------------13 <class 'int'>
>>> print(c, type(c))---------------------------156 <class 'int'>

=>With 'int' data type, we can also store Different type of Number
System values.
=>In Programming Languages , we have 4 types of Number Systems. They
are
1) Decimal Number System.
2) Binary Number System.
3) Octal Number System.
4) Hexa Decimal Number System.

1) Decimal Number System(Default Number System)

=> Decimal Number System contains


digits: 0 1 2 3 4 5 6 7 8 9
Total Number of Digits= 10
Base = 10

2) Binary Number System

=> Binary Number System contains


digits: 0 , 1
Total Number of Digits= 2
Base = 2
=>To store Binary Data in Python Programming, Binary data must be
preceded either with 0b or 0B
=>Syntax: varname=0b Binary data
(OR)
varname=0B Binary data
Examples:

>>> a=0b1111

13
>>> print(a) 15
>>> a=0B1101
>>> print(a, type(a))------------13 <class 'int'>
>>> a=0b100
>>> print(a, type(a))------------4 <class 'int'>

3) Octal Number System

=> Octal Number System contains


digits: 0 , 1, 2 3, 4, 5 6,7
Total Number of Digits= 8
Base = 8
=>To store Octal Data in Python Programming, Octal data must be
preceded either with 0o or 0O
=>Syntax: varname=0o Octal data
(OR)
varname=0O Octal data

Examples:

>>> a=0o22
>>> print(a, type(a))----------------18 <class 'int'>
>>> a=0o34
>>> print(a, type(a))-------------- 28 <class 'int'>
>>> a=0o123
>>> print(a) 83

4) Hexa Decimal Number System

=> Hexa Decimal System contains


digits: 0 , 1, 2 3, 4, 5 6,7,8,9
A(10) , B(11) , C(12) , D(13) ,
E(14) , F(15)
Total Number of Digits= 16
Base = 16
=>To store Hexa Decimal Data in Python Programming, Hexa Decimal data
must be preceded either with 0x or 0X
=>Syntax: varname=0x Hexa Decimal Data
(OR)
varname=0X Hexa Decimal Data
Examples:

>>> x=0xBEE
>>> print(x, type(x) )-----------------3054 <class 'int'>
>>> x=0xACC
>>> print(x, type(x))----------------2764 <class 'int'>
>>> x=0xACCER-------------SyntaxError: invalid hexadecimal literal
>>> x=0xFaCe
>>> print(x, type(x))------------64206 <class 'int'>
===========================x==================================
===================================================
2) float
===================================================
=>'float' is one of the pre-defined class and treated as Fundamental data
type.
=>The purpose of float data is that "To store floating point values or real
constant values
(Numbers with deciaml places) "

14
=>float data type also stores the floating point values in the form of
Scientific
Notation(Mantisa e Exponent ). The advantage of representing Floating
point values in the form of Scientific Notation(Mantisa e Exponent ) is to
reduce memory space.
=>float data type does not support Binary, Octal and Hexa Decimal Number
System representation. But It supports only default number called Decimal
Number System.

Examples:

>>> a=12.34
>>> print(a,type(a))-----------------12.34 <class 'float'>
>>> a=0.99
>>> print(a,type(a))----------------0.99 <class 'float'>
>>> a=1.2
>>> b=3.5
>>> c=a+b
>>> print(a,type(a))---------------1.2 <class 'float'>
>>> print(b,type(b))--------------3.5 <class 'float'>
>>> print(c,type(c))--------------4.7 <class 'float'>

Examples:

>>> a=3e2
>>> print(a,type(a))--------------300.0 <class 'float'>
>>> a=10e-3
>>> print(a,type(a))--------------0.01 <class 'float'>
>>> a=0.00000000000000000000000000000001
>>> print(a,type(a))------------1e-32 <class 'float'>

Invalid Examples

>>> a=0b1010.0b1111-------------------SyntaxError: invalid decimal literal


>>> a=0b10101.0xAC--------------SyntaxError: invalid decimal literal
>>> a=0o23.0xBEE----------------SyntaxError: invalid decimal literal

=============================================
3) bool
=============================================
=>'bool' is one of the pre-defined class and treated as Fundamental
data type.
=>The purpose of bool data type is that " To store True and False Value
(logical values) ".
=>Internally , the value True is 1 and the value of False is 0

Examples:

>>> a=True
>>> b=False
>>> print(a,type(a))--------------True <class 'bool'>
>>> print(b,type(b))-------------False <class 'bool'>

Invalid Examples:

>>> x=true-------------NameError: name 'true' is not defined.


>>> y=false------------NameError: name 'false' is not defined.

15
Examples:

-
>>> print(True+False)----------------1
>>> print(True+True)-----------------2
>>> print(True-True)-----------------0
>>> print(True*True*False)-----------0
>>> print(0b1111+True)---------------16
>>> print(0xAC+True)-----------------173
>>> print(2*True+2*False+3)-----------5

=============================================
4) complex
=============================================
=>'complex' is one of the pre-defined class and treated as Fundamental
data type.
=>The purpose of complex data type is that " To store Complex Numbers
".
=>The General format of Complex Numbers in Python programming is shown
bellow.

a+bj or a-bj

Here 'a' is called Real Part


'b' is called Imaginary Part
'j' represents sqrt(-1)

=>To extract or retrieve the real and imaginary parts of compex


numbers, we have two pre-defined attributes present in complex object.
They are
a) real
b) imag
=>Syntax: complexobj.real ------------> Gives Real part of Complex
Object
complexobj.imag-----------> Gives Imaginary part
of Complex Object
=>Internally Real and Imagiary Parts are treated as Floating point
values.

Examples:

>>> a=2+3j
>>> print(a, type(a))--------------------(2+3j) <class 'complex'>
>>> b=2-4j
>>> print(b, type(b))------------------(2-4j) <class 'complex'>
>>> c=2.3+4.5j
>>> print(c, type(c))-----------------(2.3+4.5j) <class 'complex'>
>>> d=-12.3-4.8j
>>> print(d, type(d))---------------(-12.3-4.8j) <class 'complex'>
>>> e=2+3.4j
>>> print(e, type(e))--------------(2+3.4j) <class 'complex'>

16
Examples:

>>> a=2+3j
>>> print(a,type(a))-----------------------(2+3j) <class 'complex'>
>>> print(a.real) 2.0
>>> print(a.imag) 3.0
>>> b=-2.3+4.5j
>>> print(b,type(b))---------------------(-2.3+4.5j) <class 'complex'>
>>> print(b.real) -2.3
>>> print(b.imag)------------------------4.5
>>> c=4j
>>> print(c,type(c))-------------------- 4j <class 'complex'>
>>> print(c.real) 0.0
>>> print(c.imag) 4.0

Complex Numbers Operations

>>> a=2+3j
>>> b=3+4j
>>> print(a+b) (5+7j)
>>> print(a-b) (-1-1j)
>>> print(a*b)--------------------(-6+17j)

>>> print((2+3.4j).imag)---------3.4
>>> print((2+3.4j).real)---------2.0
=========================================

=============================================
II ) Sequence Catagery Data Types
============================================
=>The purpose of Sequence Catagery Data Types is that " To store
sequence of values. "
=>In Python Programming, we have 4 types of Sequence Data Types. They
are
1) str
2) bytes
3) bytearray
4) range

========================================
1) str (Part-1 )
========================================
Index

=>What is str
=>Purpose of str
=>Types of str
=>Organization of str
=>Memory Management of Str
=>Operations on Str
a) Indexing
b) Slicing
=>Programming Examples

17
========================================
1) str (Part-1 )
========================================
=>"str" is one of the pre-defined class and treated as sequence data
type.
=>The purpose of str is that "To store sequence of alphabets / symbols
/ numerics" within single Quotes or double quotes or tripple single
Quotes or tripple double quotes.

=>Types of String:

=>In Python Programming, we have two types of Strings. They are


a) Single Line String Data
b) Multi Line String Data

a) Single Line String Data

=>Single Line String Data must enclosed with Single or Double Quotes.
=>Syntax:-
strobj =" Single Line String Data "
(OR)
strobj = ' Single Line String Data '

Examples:

>>> s1="Guido Van Rossum"


>>> s2='Dennis Ritche'
>>> print(s1,type(s1)) ------------Guido Van Rossum <class 'str'>
>>> print(s2,type(s2))-------------Dennis Ritche <class 'str'>

=>Hence Single or double quotescan used for storing Single Line string
data but we can't use for storing Multi Line String Data

Invalid Examples:

>>> s3= " GUIDO VAN ROSSUM

SyntaxError: unterminated string


literal (detected at line 1)
>>> s4= ' GUIDO VAN ROSSUM

SyntaxError: unterminated string literal


(detected at line 1)

b) Multi Line String Data

=>Multi Line String Data must be enclosed with Tripple Single or


Tripple Double Quotes.
=>Syntax:-
strobj =" " "
String data-1
String data-2

18
String data-n " " "

(OR)

strobj = ' ' 'String data-1


String data-2

String data-n ' ' '

Examples:

>>> s3="""GUIDO VAN ROSSUM


... HNO:3-4 red sea side
... Python software Foundation
... Nether Lands-51 """

>>> print(s3,type(s3))----
GUIDO VAN ROSSUM
HNO:3-4 red sea side
Python software Foundation
Nether Lands-51
<class 'str'>

>>> s4=' ' 'Dennis Ritche


... 34-56 Hill Side
... Bell Labs
... United States-67 ' ' '

>>> print(s4,type(s4))
Dennis Ritche
34-56 Hill Side
Bell Labs
United States-67
<class 'str'>

>>> s1="Python Programming"


>>> print(s1,type(s1))-------------Python Programming <class 'str'>
>>> s2='Guido Van Rossum'
>>> print(s2,type(s2))-------------Guido Van Rossum <class 'str'>
>>> s3="P"
>>> print(s3,type(s3))---------- P <class 'str'>
>>> s4='P'
>>> print(s4,type(s4))----------- P <class 'str'>

>>> s1="python3.10"
>>> print(s1,type(s1))----------------python3.10 <class 'str'>
>>> s2="123456"
>>> print(s2,type(s2))---------------123456 <class 'str'>
>>> s3="#$%@^&*"
>>> print(s3,type(s3))----------------#$%@^&* <class 'str'>

19
========================================
Operations on Str Data
========================================
=>On str data, we can perform 2 types of Operations. They are

1. Indexing
2. Slicing

1. Indexing

=>The purpose of Indexing Operation is that " To get a perticular


Character from str data or object".
=>Syntax: strobj [ Index ]
=>Here Index can be either +ve or -ve
=>If we enter valid index then we get a character from strobj
=>If we enter invalid index then we get IndexError.

Examples:

>>> s="PYTHON"
>>> print(s)--------------PYTHON
>>> print(s[0])-------------P
>>> print(s[1])------------Y
>>> print(s[-1])------------N
>>> print(s[-6])-----------P
>>> print(s[-2])-----------O
>>> print(s[3])------------H
>>> print(s[30])--------------IndexError: string index out of range
>>> print(s[-10])------------IndexError: string index out of range

2. Slicing:

=>The process of obtaining range of characters or sub string from given


str object is called Slicing.
=>Slicing Operation can be obtained with Various Syntaxes.

Syntax-1: strobj[ BEGIN : END ]

=>This Syntax gives range of characters or sub string from given strobj
from BEGIN Index
to END Index-1 provide BEGIN < END otherwise we never get result ( '
')

=>Examples:

>>> s="PYTHON"
>>> print( s[0:4] )--------------PYTH
>>> print( s[3:6] )--------------HON
>>> print( s[2:5] )-------------THO
>>> print( s[3:5] )-------------HO
>>> print( s[4:2] )------------ No Answer
>>> s[4:2] ' '
>>> print( s[-5:-2] )-------------------YTH
>>> print( s[-3:-1] )------------------HO

20
>>> print( s[-6:-3] )------------------PYT
>>> print( s[-3:-4] )--------------No Answer
>>> s[-3:-4]-------------' '

>>> s="PYTHON"
>>> print( s[-5:-2] )--------------YTH
>>> print( s[-3:-1] )-------------HO
>>> print( s[-6:-3] )-------------PYT
>>> print( s[-3:-4] )------------No Ans
>>> s[-3:-4] ' '

>>> s="PYTHON"
>>> print(s[2:-2])----------------TH
>>> print(s[0:-2] )--------------PYTH
>>> print(s[-4:4] )-------------TH
>>> print(s[-6:6] )-------------PYTHON

Rough Work----Monday

strobj[ Begin : End]-----completed

strobj[ Begin : ]
strobj[ : End ]
strobj[ : ]
strobj[ Begin : End : Step ]-----5 rules

Syntax-2: strobj[ Begin : ]

21
=>This Syntax obtains range of charaters from Begin Index to Last
Character
(OR)
=>This Syntax obtains range of charaters from Begin Index to
Len(strobj)-1
=>In This Syntax , we specify Begin Index and End Index not specified.
If the End Index not specified by Programmer then PVM Takes End Index
as len(strobj)-1

Examples:

>>> s="PYTHON"
>>> len(s) 6
>>> print(s[2:])---------THON
>>> print(s[1:])---------YTHON
>>> print(s[4:])---------ON
>>> print(s[3:])---------HON
>>> print(s[0:])------PYTHON
>>> print(s[-4:])-----THON
>>> print(s[-3:])------HON
>>> print(s[-6:])------PYTHON
>>> print(s[-1:])-----N

Syntax-3 : strobj[ : End ]

=>This Syntax obtains Range of Characters from First Character to End


Index-1 Charaters.
=>In This Syntax, Begin Index we are not specifing and and Index Index
is Specified.
=>If we don't specify Begin index Then PVM Takes First Character as
Begin Index Character and takes upto End Index -1

Examples:

>>> s="PYTHON"
>>> print(s)--------------PYTHON
>>> print(s[:4])-------------PYTH
>>> print(s[:5])----------PYTHO
>>> print(s[:3])---------PYT
>>> print(s[:2])----------PY
>>> print(s[:-4])--------PY
>>> print(s[:-3])--------PYT
>>> print(s[:-1])--------PYTHO

Syntax-4: strobj[ : ]

=>In This Syntax , we did't specify the Begin Index and End Index
=>This Syntax always First Charater to last character as output.
=>In Otherwords, PVM Takes First Character Index as Begin Index and
Last Character Index as End Index or len(strobj)-1

Examples:

>>> s="PYTHON"

22
>>> print(s) PYTHON
>>> print(s[ : ] )-------------PYTHON
>>> s="PYTHON PROGRAMMING LANG"
>>> print(s)--------------PYTHON PROGRAMMING LANG
>>> print(s[:])-------------PYTHON PROGRAMMING LANG

NOTE: ALL THE ABOVE SYNTAXES works in FORWARD DIRECTION.

Syntax-5 : strobj[ Begin : End : Step ]

The Rules for This syntax are

Rule-1:- Here Begin Index , End Index and Step are either +ve
or -ve
Rule-2: If STEP value is POSITIVE then PVM takes the characters
from Begin Index to
End Index-1 in foward Direction by maintaining
equal Interval (Step) Provided Begin Index < End Index Otherwise we
never get any output ( ' ' )
Rule-3: If STEP value is NEGATIVE then PVM takes the characters
from Begin Index to End Index+1 in backward Direction
by maintaining equal Interval (Step) Provided Begin Index >
End Index Otherwise we never get any output ( ' ' )
Rule-4: In Forward Direction if the End Index Value is 0 then we
never get any output
Rule-5:In Backword Direction if the End Index is -1 then we
never get any output
=======================================================================
=
Examples:

>>> s="PYTHON"
>>> print(s) PYTHON
>>> print(s[::])----------------PYTHON
>>> print(s[::-1])--------------NOHTYP
>>> print(s[2:5:2])-------------TO
>>> print(s[1:6:3])-----------YO
>>> print(s[::3])---------------PH
>>> print(s[::-3])---------------NT
>>> print(s[::-2])-----------NHY
>>> print(s[-1:-7:-3])----------NT
>>> print(s[::-4])-------------NY
>>> print(s[3:0:-1])---------HTY
>>> print(s[3:-1:-1])---------- No Answer or ' '
>>> print(s[3:0:1])------------ No Answer or ' '

Special Examples:

>>> S="LIRIL"
>>> S==S[::-1]-------------True
>>> "PYTHON"=="PYTHON"[::-1]---------False
>>> "MADAM"=="MADAM"[::-1]----------------True
>>> "MALAYALAM"=="Malayalam"[::-1]--------False

23
>>> "MALAYALAM"=="MALAYALAM"[::-1]----------True

=============================================
Type Casting Techniques in Python
=============================================
=>The purpose of Type Casting Techniques in Python is that " To Convert
One Possible
Value into another Possible Value. "
=>In Python Programming, we have 5 types of Fundamental Type casting
Techniques.
They are

1) int()
2) float()
3) bool()
4) complex()
5) str()

=====================================
1) int()
=====================================
=>int() is used for converting "One Type of Possible Value into
Integer Value."

=>Syntax:- varname=int( float / bool / complex / str )

Examples: float type value------>int type value--Possible

>>> a=12.34
>>> print(a,type(a))---------------------------12.34 <class 'float'>
>>> b=int(a)
>>> print(b, type(b))-------------------------12 <class 'int'>
>>> a=0.9999
>>> print(a,type(a))-------------------------0.9999 <class 'float'>
>>> b=int(a)
>>> print(b, type(b))----------------------0 <class 'int'>

Example: bool type value------>int type value--Possible

>>> a=True
>>> print(a,type(a))--------------True <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------1 <class 'int'>
>>> a=False
>>> print(a,type(a))--------------False <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------0 <class 'int'>

Examples: complex type value------>int type value--Not Possible

24
>>> a=2+3j
>>> print(a,type(a))-------------(2+3j) <class 'complex'>
>>> b=int(a)-----TypeError: int() argument must be a string, a bytes-
like object or a real
number, not 'complex'

Examples:

>>> a="12" # int str to int Possible


>>> print(a,type(a))-------------------12 <class 'str'>
>>> b=int(a)
>>> print(b,type(b))--------------12 <class 'int'>

>>> a="12.34" # float str to int Not Possible


>>> print(a,type(a))----------12.34 <class 'str'>
>>> b=int(a)-------ValueError: invalid literal for int() with base 10:
'12.34'

>>> a="True" # Bool Str to int Not Possible


>>> print(a,type(a))--------------True <class 'str'>
>>> b=int(a)---------ValueError: invalid literal for int() with base
10: 'True'

>>> a="2+3.5j" # complex str


>>> print(a,type(a))------------2+3.5j <class 'str'>
>>> b=int(a)------------ValueError: invalid literal for int() with base
10: '2+3.5j'

>>> a="Python" # Pure Str


>>> print(a,type(a))------------Python <class 'str'>
>>> b=int(a)-----------ValueError: invalid literal for int() with base
10: 'Python'
==================================X==================================

=====================================
2) float()
=====================================
=>float() is used for converting "One Type of Possible Value into
float Value."

=>Syntax:- varname=float( int / bool / complex / str )

Examples: int type value --------> float type value ---> Possible

>>> a=12
>>> print(a,type(a))--------------12 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))-------------12.0 <class 'float'>

Examples: bool type value --------> float type value ---> Possible

>>> a=True
>>> print(a,type(a))----------True <class 'bool'>

25
>>> b=float(a)
>>> print(b,type(b))-------------- 1.0 <class 'float'>

Examples: complex type value --------> float type value --->Not


Possible

>>> a=2+3.5j
>>> print(a,type(a))------------------(2+3.5j) <class 'complex'>
>>> b=float(a)----TypeError: float() argument must be a string or a
real number, not 'complex'

Examples:

a="123" # int str to float Possible


>>> print(a,type(a))---------------123 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))------------- 123.0 <class 'float'>
>>> a="34.56" # float str to float Possible
>>> print(a,type(a))------------34.56 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))-------------34.56 <class 'float'>
>>> a="True" # bool str to float Not Possible
>>> print(a,type(a))---------------True <class 'str'>
>>> b=float(a)------------ValueError: could not convert string to
float: 'True'
>>> a="2+3.5j" # complex str to float Not Possible
>>> print(a,type(a))--------------2+3.5j <class 'str'>
>>> b=float(a)---------ValueError: could not convert string to float:
'2+3.5j'
>>> a="Python.Java" Pure Str to float Not Possible
>>> print(a,type(a))--------Python.Java <class 'str'>
>>> b=float(a)----------ValueError: could not convert string to float:
'Python.Java'
==============================X===================================

==============================================
3) bool()
==============================================
=>bool() is used for converting "One Type of Possible Value into bool
Value."

=>Syntax:- varname=bool( int / float / complex / str )


=>ALL TYPES OF NON-ZERO VALUES are Treated as TRUE
=>ALL TYPES OF ZERO VALUES are Treated as FALSE

Examples:

>>> a=123-------int to bool Possible


>>> print(a,type(a))--------------123 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))-----------True <class 'bool'>
>>> a=-456

26
>>> print(a,type(a))--------------456 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))----------True <class 'bool'>
>>> a=0
>>> print(a,type(a))-----------0 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))---------False <class 'bool'>

Examples:

>>> a=12.34 # float type to bool Possible


>>> print(a,type(a))-----------------12.34 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a=0.0000000000000000000000000000000000000000000001
>>> b=bool(a)
>>> a=0.0000000000000000000000000000000000000000000001
>>> print(a,type(a))-----------1e-46 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>

Examples:

>>> a=2+3j # complex to bool possible


>>> print(a,type(a))------------(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))-----------0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))-----------False <class 'bool'>

Examples:

>>> a="123"
>>> print(a,type(a))
123 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a="12.34"
>>> print(a,type(a))
12.34 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a="0"
>>> print(a,type(a))
0 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))

27
True <class 'bool'>
>>> len(a)
1
>>> a="00000000000000"
>>> print(a,type(a))
00000000000000 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> len(a)
14
>>> a="False"
>>> print(a,type(a))
False <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a=" "
>>> print(a,type(a))
<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> len(a)
4
>>> a=""
>>> print(a,type(a))
<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
False <class 'bool'>
>>> len(a)
0
>>> a="KVR"
>>> print(a,type(a))
KVR <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
>>> a="123abc%$"
>>> print(a,type(a))
123abc%$ <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
True <class 'bool'>
=======================X===================================

=====================================
4) complex()
=====================================
=>complex() is used for converting "One Type of Possible Value into
Complex Value."

=>Syntax:- varname=complex( int / float / bool / str )

Examples: int type value into complex type value Possible

28
>>> a=123
>>> print(a,type(a))----------------123 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))--------------(123+0j) <class 'complex'>

Examples: float type value into complex type value Possible

>>> a=10.5
>>> print(a,type(a))--------------10.5 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))----------(10.5+0j) <class 'complex'>

Examples: Bool type value into complex type value Possible

>>> a=True
>>> print(a,type(a))
True <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))
(1+0j) <class 'complex'>
>>> a=False
>>> print(a,type(a))
False <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))
0j <class 'complex'>

Examples:

>>> a="12"
>>> print(a,type(a))
12 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))
(12+0j) <class 'complex'>
>>> a="12.34"
>>> print(a,type(a))
12.34 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))
(12.34+0j) <class 'complex'>
>>> a="True"
>>> print(a,type(a))
True <class 'str'>
>>> b=complex(a)-------------ValueError: complex() arg is a malformed
string
>>> a="Python"
>>> print(a,type(a))
Python <class 'str'>

29
>>> b=complex(a)-------------ValueError: complex() arg is a malformed
string
===========================X==================

=====================================
5) str()
=====================================
=>str() is used for converting "All types of Values into str Value."

=>Syntax:- varname=str( int / float / bool / complex )

>>> a=123
>>> print(a,type(a))------------------------------123 <class 'int'>
>>> b=str(a)
>>> print(b,type(b))----------------------------123 <class 'str'>
>>> b '123'
>>> b=12.34
>>> print(b,type(b))---------12.34 <class 'float'>
>>> a=str(b)
>>> print(a,type(a))----------12.34 <class 'str'>
>>> a '12.34'
>>> a=True
>>> print(a,type(a))-----------------True <class 'bool'>
>>> b=str(a)
>>> print(b,type(b))-----------------True <class 'str'>
>>> b 'True'
>>> a=2+3j
>>> print(a,type(a))-------------------(2+3j) <class 'complex'>
>>> b=str(a)
>>> print(b,type(b))--------------------------(2+3j) <class 'str'>
>>> b '(2+3j)'
==============================X=================================

==============================================
Mutability and Immutability
==============================================

=>Mutability:

=>A mutable object is one, whose content can be changed during program
execution
at Same Address

30
=>Examples: list

=>Immutability:

=>A immutable object is one, which will satisfy the following


properties.
1) Content Can't be Changed at same address
(Content can be changed and changed values kept in
another memory address by removing existing memory space)
2) Item Assigment is Not Possible

Examples: int, tuple


=============================X=====================================

==============================================
2) bytes
==============================================
=>'bytes' is one the pre-defined class and treated as sequence data
type
=>The purpose of bytes data type is that " To organize the Possitive
Numerical Values
from 0 to 256. "
=>There is no symbolic Notation for oraganizing the data in bytes data.
But we can convert
or type cast any other kind of values into bytes data types by
using bytes().
=>On the object of bytes, we can perform Both Indexing and Slicing
Operations.
=>An object of bytes belongs to immutable( bcoz 'bytes' object does not
support item
assignment)
=>An object of bytes maintains Insertion Order. In Otherwords, In
whichever order, we
insert the data , in the same order elements will be displayed.
Note:- the real time implementation of bytes data type is that to
transmit the data between
to remote machines in the form end-end encryption.

Examples:

>>> l1=[100,200,45,67,256]
>>> print(l1, type(l1))-----------------------[100, 200, 45, 67, 256]
<class 'list'>
>>> b=bytes(l1)---------ValueError: bytes must be in range(0, 256)
>>> l1=[100,0,-200,45,67,255]
>>> print(l1, type(l1))------------[100, 0, -200, 45, 67, 255] <class
'list'>
>>> b=bytes(l1)-------------ValueError: bytes must be in range(0, 256)
>>> l1=[100,0,200,45,67,255]
>>> print(l1, type(l1))----------[100, 0, 200, 45, 67, 255] <class
'list'>
>>> b=bytes(l1)

31
>>> print(b, type(b), id(b))---b'd\x00\xc8-C\xff' <class 'bytes'>
2432798685152
>>> print(b[0])----100
>>> print(b[-1])----255
>>> b[0]=123-------TypeError: 'bytes' object does not support item
assignment
>>> for kvr in b:
... print(kvr)
...
100
0
200
45
67
255
>>> print(b[0:4])---------------b'd\x00\xc8-'
>>> for x in b[0:4]:
... print(x)
...
100
0
200
45
=================================X===========================

==============================================
3) bytearray
==============================================
=>'bytearray' is one the pre-defined class and treated as sequence data
type
=>The purpose of bytearray data type is that " To organize the
Possitive Numerical Values
from 0 to 256. "
=>There is no symbolic Notation for oraganizing the data in bytearray
data. But we can convert or type cast any other kind of values into
bytearray data types by using bytearray().
=>On the object of bytearray, we can perform Both Indexing and Slicing
Operations.
=>An object of bytearray belongs to mutable( bcoz 'bytebytearray'
object allows or support item assignment)
=>An object of bytearray maintains Insertion Order. In Otherwords, In
whichever order, we
insert the data , in the same order elements will be displayed.
Note:- the real time implementation of bytearray data type is that to
transmit the data between to remote machines in the form end-end
encryption.

Note: The Functionality of bytearray is extractly similar to bytes but


an object of bytes
belongs to immutable where as an object of bytearray is
mutable.

Examples:

>>> l1=[100,200,45,67,256]

32
>>> print(l1, type(l1))------------------------[100, 200, 45, 67, 256]
<class 'list'>
>>> ba=bytearray(l1)-----------ValueError: byte must be in range(0,
256)

>>> l1=[100,0,-200,45,67,255]
>>> print(l1, type(l1))------------[100, 0, -200, 45, 67, 255] <class
'list'>
>>> ba=bytearray(l1)---------ValueError: byte must be in range(0, 256)

>>> l1=[100,200,45,0,67,255]
>>> print(l1, type(l1))-----------------[100, 200, 45, 0, 67, 255]
<class 'list'>
>>> ba=bytearray(l1)
>>> print(ba,type(ba),id(ba))---bytearray(b'd\xc8-\x00C\xff') <class
'bytearray'>
>>> print(ba[0])-------------100
>>> print(ba[-2])------------67
>>> ba[0]=125 # Updation
>>> for x in ba:
... print(x)
...
125
200
45
0
67
255
>>> print(ba,type(ba),id(ba))----bytearray(b'}\xc8-\x00C\xff') <class
'bytearray'>
>>> for x in ba[::-1]:
... print(x)
...
255
67
0
45
200
125
>>> for x in ba[::2]:
... print(x)
...
125
45
67
===================================X=================================

====================================
4) range
====================================
=>"range" is one of the pre-defined class and treated as Sequence Data
type.
=>The purpose of range data type is that " To organize sequence or
range of Integer values by maintaining equal interval of value"
=>On the object range , we can perform Indexing and Slicing Operations.
=>An object of range belongs to immutable bcoz 'range' object does not
support item

33
assignment
=>An object of rannge maintains Insertion Order.
=>range data type contains 3 syntaxex. They are

Syntax-1: varname=range(value)

=>This syntax generates range of values from 0 to value-1

>>> print(r, type(r))------------range(0, 6) <class 'range'>


>>> for v in r:
... print(v)
...
0
1
2
3
4
5
>>> for v in range(10):
... print(v)
...
0
1
2
3
4
5
6
7
8
9

Syntax-2 range(start,stop)

=>This syntax generates range of values from start to stop-1


Examples:

>>> x=range(100,106)
>>> print(x,type(x))-----------------range(100, 106) <class 'range'>
>>> for val in x:
... print(val)
...
100
101
102
103
104
105
>>> for v in range(10,21):
... print(v,end=" ")
...
10 11 12 13 14 15 16 17 18 19 20
>>> r=range(100,106)
>>> for v in r:
... print(v)
...

34
100
101
102
103
104
105
>>> print(r[0])-------------100
>>> print(r[-1])-------------105
>>> print(r[-2])-------------104
>>> print(r[2:5])--------------range(102, 105)
>>> for v in r[2:5]:
... print(v)
...
102
103
104
>>> r[3]=1000-------TypeError: 'range' object does not support item
assignment
=>Note: Syntax1 and Syntax2 always looks in forward direction with Unit
(One) Interval Value

Syntax-3: varname=range(start,stop,step)

=>This generates range of values from start to stop by maintaining


equal Interval of value(step)

Examples:

>>> print(r,type(r))
range(10, 17, 2) <class 'range'>
>>> for v in r:
... print(v)
...
10
12
14
16
>>> for v in range(100,501,100):
... print(v)
...
100
200
300
400
500

Q1) Generate 0 1 2 3 4 5 6 7 8 9------range(10)

>>> for v in range(10):


... print(v)
...
0
1
2
3

35
4
5
6
7
8
9

Q2) 100 101 102 103 104 105------range(100,106)

>>> for v in range(100,106):


... print(v)
...
100
101
102
103
104
105

Q3) Generate 10 9 8 7 6 5 4 3 2 1-----range(10,0,-


1)

>>> for v in range(10,0,-1):


... print(v)
...
10
9
8
7
6
5
4
3
2
1

Q4) Generate -1 -2 -3 -4 -5 -6 -7 -8 -9 -10-----range(-


1,-11,-1)

>>> for v in range(-1,-11,-1):


... print(v)
...
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10

36
Q5)Generate 1000 1005 1010 1015 1020-------------
range(1000,1021,5)

>>> for v in range(1000,1021,5):


... print(v)
...
1000
1005
1010
1015
1020

Q6) Generate 100 80 60 40 20 0--------range(100,-1,-20)

>>> for v in range(100,-1,-20):


... print(v)
...
100
80
60
40
20
0

Q7) Generate -5 -4 -3 -2 -1 0 1 2 3 4 5 -----


range(-5,6,1)
>>> for v in range(-5,6,1):
... print(v)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5

Q8) Generate 100 50 0 ---range(100,-1,-50)

>>> for v in range(100,-1,-50):


... print(v)
...
100
50
0
=============================x=========================================
>>> n=9
>>> for i in range(1,11):
... print(n,"x",i,"=",n*i)
...
9 x 1 = 9

37
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
>>> n=19
>>> for i in range(1,11):
... print(n,"x",i,"=",n*i)
...
19 x 1 = 19
19 x 2 = 38
19 x 3 = 57
19 x 4 = 76
19 x 5 = 95
19 x 6 = 114
19 x 7 = 133
19 x 8 = 152
19 x 9 = 171
19 x 10 = 190
==================================X===================================

Examples:

Q1) 0 1 2 3 4 5 6 7 8 9

Q2) 100 101 102 103 104 105

Q3) 10 9 8 7 6 5 4 3 2 1

Q4) -1 -2 -3 -4 -5 -6 -7 -8 -9 -10

Q5) 1000 1005 1010 1015 1020

Q6) 100 80 60 40 20 0

Q7) -5 -4 -3 -2 -1 0 1 2 3 4 5

=============================================================
III) List Catagery Data Types ( Collection Data Types or Data
Structures)

=============================================================
=>The purpose of List Catagery Data Types is that " To store multiple
values of either of same type or different type or both types with
Unique or Duplicates Values in single object."
=>List Catagery Data Types contains 2 data types. They are
a) list (mutable)
b) tuple (immutable)

38
===============================================
1) list
===============================================
=>'list' is one of the pre-defined class and treated as List Data
Types.
=>The purpose of list data is that " To store multiple values of either
of same type or
different type or both types with Unique or Duplicates Values in
single object."
=>The elements of list must be organized within Square Brackets [ ]
=>On the object of list we can perform Indexing and Slicing Operations.
=>An object of List belongs to Mutable
=>An object of list maintains Insertion Order
=>In Python Programming, we can create two objects of list.
a) empty list
b) non-empty list

=>empty list:

=>An empty list is one which does not contain any elements and whose
length is 0
=>Syntax:- listobj=[]
(or)
listobj=list()

=>Non-empty list:

=>An Non-empty list is one which contains elements and whose length
is >0

=>Syntax:- listobj=[val1,val2......val-n]
================================================================
Examples:

>>> l1=[10,20,10,40,15,46,20,300,-456]
>>> print(l1,type(l1))----[10, 20, 10, 40, 15, 46, 20, 300, -456]
<class 'list'>
>>> l2=[100,"Rossum",45.44,True,2+3j,"TCS","Rossum"]
>>> print(l2,type(l2))----[100, 'Rossum', 45.44, True, (2+3j), 'TCS',
'Rossum'] <class 'list'>
>>>
>>> len(l1)------------9
>>> len(l2)-----------7
>>> l3=[] # empty list
>>> print(l3,type(l3))--------------- [] <class 'list'>
>>> len(l3) 0
>>> l4=list() # empty list
>>> print(l4,type(l4))-------------- [] <class 'list'>
>>> len(l4) 0
>>>
>>> l2=[100,"Rossum",45.44,True,2+3j,"TCS"]
>>> print(l2)--------------[100, 'Rossum', 45.44, True, (2+3j), 'TCS']

39
>>> print(l2,type(l2))-----[100, 'Rossum', 45.44, True, (2+3j), 'TCS']
<class 'list'>
>>> print(l2[0])-------------100
>>> print(l2[-1])-------------TCS
>>> print(l2[2])-------------45.44
>>> print(l2[1:4])------------------['Rossum', 45.44, True]
>>> print(l2[1:4][::-1])--------------[True, 45.44, 'Rossum']
>>> print(l2,id(l2))-----[100, 'Rossum', 45.44, True, (2+3j), 'TCS']
2735455617984
>>> l2[0]=123 # upodating the value of list
>>> print(l2,id(l2))-----------[123, 'Rossum', 45.44, True, (2+3j),
'TCS'] 2735455617984
====================================X=================================

========================================
Operations on list object
========================================
=>On The object of list we can perform various operations along with
indexing and slicing
=>To do various operation on list object, we use the following pre-
defined functions.

1) append()

=>This Function is used for adding an element at end of existing


elements of list obj.
=>Syntax: listobj.append(Value)

Examples:

>>> l1=[]
>>> print(l1,type(l1), len(l1))-----------------[] <class 'list'> 0
>>> l1.append(10)
>>> print(l1) [10]
>>> l1.append("Rossum")
>>> l1.append(34.56)
>>> print(l1)----------------[10, 'Rossum', 34.56]
>>> l1.append(True)
>>> print(l1)---------------[10, 'Rossum', 34.56, True]
>>> l2=[10,"Travis",56.78]
>>> print(l2,id(l2))-------------- [10, 'Travis', 56.78] 2142698161280
>>> l2.append("Numpy")
>>> print(l2,id(l2))---------- [10, 'Travis', 56.78, 'Numpy']
2142698161280

2) insert():

=>This Function is used for inserting an element at specified existing


Index.
=>Syntax: listobj.insert(index,Value)
Examples:

>>> l2=[10,"Travis",56.78]

40
>>>print(l2) [10,"Travis",56.78]
>>> l2.insert(1,"Numpy")
>>> print(l2)-----------------------------[10, 'Numpy', 'Travis',
56.78]
>>> l2.insert(2,2003)
>>> print(l2)------------------------[10, 'Numpy', 2003, 'Travis',
56.78]

3) remove():----Based on Content

=>This Function is used for removing the First occurence of element


from list.
=>Syntax: listobj.remove(Value)
=>If the Value does not exists then we get ValueError

Examples

>>> l1=[10,20,30,10,20,40]
>>> print(l1)-------------------------------[10, 20, 30, 10, 20, 40]
>>> l1.remove(10)
>>> print(l1)------------------------------[20, 30, 10, 20, 40]
>>> l1.remove(10)
>>> print(l1)----------------------[20, 30, 20, 40]
>>> l1.remove(20)
>>> print(l1)-------------------------[30, 20, 40]
>>> l1.remove(100)----------------ValueError: list.remove(x): x not in
list

4) pop(index): Based on Index

=>This Function is used for removing the elements of list object based
on Index.
=>Syntax:- listobj.pop(Index)
=>Here the Index value can be either +ve or -ve
=>If the Index is valid then It removes corresponding elements and
returned
=>If the Index is invalid then It gives IndexError

Examples:

>>> l1=[10,20,30,10,20,40]
>>> print(l1)--------------------------[10, 20, 30, 10, 20, 40]
>>> l1.pop(3) 10
>>> print(l1)----------------[10, 20, 30, 20, 40]
>>> l1.pop(-4)-----------------20
>>> print(l1)------------- [10, 30, 20, 40]
>>> l1.pop(12)---------IndexError: pop index out of range

5) pop():

=>This Function is used for removing last element from list object
=>Syntax:- listobj.pop()
=>When we call pop() upon empty list then we get IndexError.

Examples:

41
>>> l1=[10,20,30,10,20,40]
>>> print(l1)---------------------------------[10, 20, 30, 10, 20, 40]
>>> l1.pop() 40
>>> print(l1)------------[10, 20, 30, 10, 20]
>>> l1.pop()--------------20
>>> print(l1)-----------[10, 20, 30, 10]
>>> l1.insert(1,200)
>>> print(l1)-------------[10, 200, 20, 30, 10]
>>> l1.pop()-----------10
>>> print(l1)-----------[10, 200, 20, 30]
>>> [].pop()--------------IndexError: pop from empty list
>>> list().remove(100)----------ValueError: list.remove(x): x not in
list
>>> list().pop(0)-------------IndexError: pop from empty list
>>> list().pop()-------------IndexError: pop from empty list

NOTE: del
=>'del' is an operator which is used 3 purposes
a) Remove the element based Index
b) Remove the elements based Slicing
c) Remove the complete object
Syntax1: del object[Index]

Syntax2: del object[Begin : End : Step]

Syntax3: del object

EXAMPLES:

>>> l1=[10,20,30,10,20,40,50,60]
>>> print(l1)
[10, 20, 30, 10, 20, 40, 50, 60]
>>> del l1[3]
>>> print(l1)
[10, 20, 30, 20, 40, 50, 60]
>>> del l1[-2]
>>> print(l1)
[10, 20, 30, 20, 40, 60]
>>> del l1[1:4]
>>> print(l1)
[10, 40, 60]
>>> l1=[10,20,30,10,20,40,50,60]
>>> print(l1)
[10, 20, 30, 10, 20, 40, 50, 60]
>>> del l1[::2]
>>> print(l1)
[20, 10, 40, 60]
>>> del l1
>>> print(l1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'l1' is not defined. Did you mean: 'l2'?

6) copy():

42
=>This Function is used for Copying the content of one object into
another object
(Implements Shallow Copy)
=>Syntax:- listobj2=listobj1.copy()

Examples:

>>> l1=[10,"Rossum",34.56]
>>> l2=l1.copy() # Shallow Copy
>>> print(l1,id(l1))-------------------[10, 'Rossum', 34.56]
2142698161216
>>> print(l2,id(l2))------------------[10, 'Rossum', 34.56]
2142698168000
>>> l1.append("Python")
>>> l2.append("Django")
>>> print(l1,id(l1))-------------[10, 'Rossum', 34.56, 'Python']
2142698161216
>>> print(l2,id(l2))-------------[10, 'Rossum', 34.56, 'Django']
2142698168000

Note: Deep Copy:

Examples:

>>> l1=[10,"Rossum",34.56]
>>> print(l1,id(l1))-----------[10, 'Rossum', 34.56] 2142698161280
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))---------------[10, 'Rossum', 34.56] 2142698161280
>>> l1.append("Python")
>>> print(l1,id(l1))------------[10, 'Rossum', 34.56, 'Python']
2142698161280
>>> print(l2,id(l2))-------------[10, 'Rossum', 34.56, 'Python']
2142698161280
>>> l2.insert(2,"Django")
>>> print(l1,id(l1))------------[10, 'Rossum', 'Django', 34.56,
'Python'] 2142698161280
>>> print(l2,id(l2))------[10, 'Rossum', 'Django', 34.56, 'Python']
2142698161280

7) index():

=>This Function is used for finding Index of Specified Value.


=>Syntax: listobj.index(Value)
=>If the value does not exists in list object then we get ValueError.

Examples:

>>> l1=[10,"Rossum",34.56,10,"Rossum"]
>>> print(l1)-------------[10, 'Rossum', 34.56, 10, 'Rossum']
>>> l1.index(10) 0
>>> l1.index("Rossum")---------1
>>> l1.index("Rossum1")----------ValueError: 'Rossum1' is not in list

8) count():

43
=>This function is used for counting all the occurences of specified
Value.
=>Syntax: listobj.count(Value)
=>If the values does not exists then we get its count as 0.

Examples:

>>> l1=[10,"Rossum","Python",10,20,10,"Rossum"]
>>> print(l1)------------[10, 'Rossum', 'Python', 10, 20, 10, 'Rossum']
>>> l1.count(10)------------3
>>> l1.count("Rossum")---------2
>>> l1.count(100)-------------0
>>> list().count(5)----------0
>>> [10,10,10,20,20].count(10)-----------3

9) reverse():

=>This Function is used for obtaining the reverse of given elements of


list ( Front element to Back and Vice-Versa)
=>Syntax: listobj.reverse()

Examples:

>>> l1=[10,"Rossum",34.56,"Python",True,2+3j]
>>> print(l1,id(l1))----------[10, 'Rossum', 34.56, 'Python', True,
(2+3j)] 2142694134976
>>> l1.reverse()
>>> print(l1,id(l1))-------[(2+3j), True, 'Python', 34.56, 'Rossum',
10] 2142694134976
>>> l1=[10,"Rossum",34.56,"Python",True,2+3j]
#OR
>>> l1[::-1]-----[(2+3j), True, 'Python', 34.56, 'Rossum', 10]

sort()
extend()
==================================================
Copy Techniques
==================================================
=>In Python Programming, we have two types of Copy Techniques. They are
1) Shallow Copy
2) Deep Copy

1) Shallow Copy:

=>The properties of Shallow Copy are


a) Initial Content of Both Objects are Same
b) Memory Addresses of Both the Objects are Different
c) Modification / Updations are Indepenedent ( Whatever
the modifications we do

44
on one object , such modifications are not
refelecting to another object)
=>Programtically to implement Shallow Copy, we must use copy()

Syntax: object2=object1.copy()
Examples:

>>> l1=[10,"Rossum",34.56]
>>> l2=l1.copy() # Shallow Copy
>>> print(l1,id(l1))-------------------[10, 'Rossum', 34.56]
2142698161216
>>> print(l2,id(l2))------------------[10, 'Rossum', 34.56]
2142698168000
>>> l1.append("Python")
>>> l2.append("Django")
>>> print(l1,id(l1))-------------[10, 'Rossum', 34.56, 'Python']
2142698161216
>>> print(l2,id(l2))-------------[10, 'Rossum', 34.56, 'Django']
2142698168000
=======================================================================
2) Deep Copy:

=>The properties of Deep Copy are


a) Initial Content of Both Objects are Same
b) Memory Addresses of Both the Objects are Same
c) Modification / Updations are depenedent ( Whatever the
modifications we do
on one object , such modifications are refelecting
to another object)
=>Programtically to implement Deep Copy, we must use assigment
operator ( = )
=>Syntax:- object1 = object2

Examples:

>>> l1=[10,"Rossum",34.56]
>>> print(l1,id(l1))-----------[10, 'Rossum', 34.56] 2142698161280
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))---------------[10, 'Rossum', 34.56] 2142698161280
>>> l1.append("Python")
>>> print(l1,id(l1))------------[10, 'Rossum', 34.56, 'Python']
2142698161280
>>> print(l2,id(l2))-------------[10, 'Rossum', 34.56, 'Python']
2142698161280
>>> l2.insert(2,"Django")
>>> print(l1,id(l1))------------[10, 'Rossum', 'Django', 34.56,
'Python'] 2142698161280
>>> print(l2,id(l2))------[10, 'Rossum', 'Django', 34.56, 'Python']
2142698161280
=============================X======================================

===================================================
tuple
===================================================

45
=>tuple' is one of the pre-defined class and treated as List Data
Types.
=>The purpose of tuple data is that " To store multiple values of
either of same type or
different type or both types with Unique or Duplicates Values in
single object."
=>The elements of tuple must be organized within barces ( )
=>On the object of tuple we can perform Indexing and Slicing
Operations.
=>An object of tuple belongs to Immutable
=>An object of tuple maintains Insertion Order
=>In Python Programming, we can create two objects of tuple.
a) empty tuple
b) non-empty tuple

=>empty tuple:

=>An empty tuple is one which does not contain any elements and whose
length is 0
=>Syntax:- tplobj=()
(or)
tplobj=tuple()

=>Non-empty tuple:

=>An Non-empty tuple is one which contains elements and whose length
is >0
=>Syntax:- tplobj=(val1,val2 val-n)
(OR)
tplobj=val1,val2.....val-n

Note: The Functionality of tuple is exactly similar to list but an


object of list belongs to mutable and an object tuple belongs to
immutable.

>>> t1=(10,20,30,10,20,10)
>>> print(t1,type(t1),id(t1))-----------(10, 20, 30, 10, 20, 10) <class
'tuple'> 1595807983520
>>> t2=(10,"Ram",45.67,True)
>>> print(t2,type(t2),id(t2))-----------(10, 'Ram', 45.67, True) <class
'tuple'> 1595808321024
>>> print(t1[0])-----------10
>>> print(t1[-1])----------10
>>> print(t1[0:4])---------(10, 20, 30, 10)
>>> t1[0]=100--------TypeError: 'tuple' object does not support item
assignment
>>>
>>> t3=()
>>> print(t3,type(t3),len(t3))---------------() <class 'tuple'> 0
>>> t4=tuple()
>>> print(t4,type(t4),len(t4))--------------() <class 'tuple'> 0
>>>
>>> t5=10,"KVR",44.44, "Hyd", True
>>> print(t5,type(t5),len(t5))-----------------(10, 'KVR', 44.44,
'Hyd', True) <class 'tuple'> 5

46
Note: tuple object contains the following functions only
a) count()
b) index()

=>One can defined tuple in tuple, tuple in list and list in tuple

Examples:

>>> l1=[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77, 58], 'OUCET']
>>> print(l1)--------[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77, 58],
'OUCET']
>>> l1=[10, 'Rossum', (14, 18, 15, 16), [66, 78, 77, 58], 'OUCET']
>>> print(l1)----[10, 'Rossum', (14, 18, 15, 16), [66, 78, 77, 58],
'OUCET']

>>> t2=(10, 'Rossum', (14, 18, 15, 16), [66, 78, 77, 58], 'OUCET')
>>> print(t2,type(t2))---(10, 'Rossum', (14, 18, 15, 16), [66, 78, 77,
58], 'OUCET') <class

'tuple'>
>>> print(t2[3], type(t2[3]) )----------- [66, 78, 77, 58] <class
'list'>

>>> t2=(10, 'Rossum', (14, 18, 15, 16), [66, 78, 77, 58], 'OUCET')
>>> print(t2)-----------(10, 'Rossum', (14, 18, 15, 16), [66, 78, 77,
58], 'OUCET')
>>> t2[-2].append(55)
>>> print(t2)---------(10, 'Rossum', (14, 18, 15, 16), [66, 78, 77, 58,
55], 'OUCET')
>>> t2[-2].sort()
>>> print(t2)---------(10, 'Rossum', (14, 18, 15, 16), [55, 58, 66, 77,
78], 'OUCET')
=============================X========================================

47
==========================================
Inner or nested list
==========================================
=>The process of defining one list inside of another list is called
Inner or nested list.
=>On Inner List objects we can perform Both Indexing and Slicing
Operations.
=>On the inner list objects we can apply all pre-defined functions of
list for performing
Various operations.
=>Syntax:
listobj=[ Val1, Val2, [ Val11,Val12...Val1n], [Val
21,Val22....Val2n], .... Val-n ]

=>Here [ Val11,Val12...Val1n] is called one inner list


[Val 21,Val22....Val2n] is called another inner list.

Examples:

>>> l1=[10, "Rossum", [14,18,17], [66,77,58],"OUCET"]


>>> print(l1,type(l1))-----------[10, 'Rossum', [14, 18, 17], [66, 77,
58], 'OUCET'] <class 'list'>
>>> print(l1[0])--------------10
>>> print(l1[1])----------Rossum
>>> print(l1[2])-----------[14, 18, 17]
>>> print(l1[-2])-----------[66, 77, 58]
>>> print(l1[-1])----------OUCET
>>> print(l1[2][1])--------18
>>> print(l1[2][-2])------18
>>> print(l1[-3][-1])------17
>>> l1[2][-1]=15

48
>>> print(l1)-------------[10, 'Rossum', [14, 18, 15], [66, 77, 58],
'OUCET']
>>> l1[2].append(16)
>>> l1[-2].insert(1,78)
>>> print(l1)------------[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77,
58], 'OUCET']
>>> l1.pop(2)-----------[14, 18, 15, 16]
>>> print(l1)---------[10, 'Rossum', [66, 78, 77, 58], 'OUCET']
>>> l1.pop(-2)--------[66, 78, 77, 58]
>>> print(l1)--------[10, 'Rossum', 'OUCET']
>>> l1=[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77, 58], 'OUCET']

>>> print(l1)
[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77, 58], 'OUCET']
>>> del l1[2:4]
>>> print(l1)--------------[10, 'Rossum', 'OUCET']
>>> l1=[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77, 58], 'OUCET']
>>> print(l1)---------[10, 'Rossum', [14, 18, 15, 16], [66, 78, 77,
58], 'OUCET']
>>> l1[2].sort(reverse=True)
>>> print(l1)----[10, 'Rossum', [18, 16, 15, 14], [66, 78, 77, 58],
'OUCET']
>>> l1[-2].sort()
>>> print(l1)---------[10, 'Rossum', [18, 16, 15, 14], [58, 66, 77,
78] , 'OUCET']

-
>>> matrix=[[10,20,30], [40,50,60], [70,80,90] ]
>>> print(matrix,type(matrix))-----[[10, 20, 30], [40, 50, 60], [70,
80, 90]] <class 'list'>
>>> for row in matrix:
... print(row)
...
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]

>>> matrix=[[10,20,30], [40,50,60], [70,80,90] ]


>>> print(matrix[0])------------[10, 20, 30]
>>> print(matrix[-2])-----------[40, 50, 60]
>>> print(matrix[-1])----------[70, 80, 90]
>>> for val in matrix[1]:
... print(val)
...
40
50
60
================================X===============================

49
========================================================
Set Catagery Data Types ( Collection Data Types or Data
Structures)
========================================================
=>The purpose of Set Catagery Data Types is that " To store multiple
values of either of same type or different type or both types with
Unique Values in single object."
=>>Set Catagery Data Types contains 2 data types. They are
1. set (mutable and immutable)
2. frozenset (immutable)

===================================================
1. set
====================================================
=>'set' is one of the pre-defined class and treated as set data type.
=>The purpose of set data type is that To store multiple values of
either of same type or
different type or both types with Unique Values in single object."
=>The elements set must organized with curly braces {} and values must
separated by
comma.
=>An object of set does not maintain insertion Order bcoz PVM displays
any possibility of
elements of set
=>Since set object does not maintain insertion order, we can't perform
Indexing and
Slicing Operations ( set' object is not subscriptable)
=>We have two types of set objects
a) empty set
b) non-empty set
=>An empty set is one which does not contain any elements and whose
length is 0
Syntax:- setobj=set()
=>A non-empty set is one which contains any number elements and whose
length is >0
Syntax:- setobj={val1,val2.....val-n}
=>An object of set belongs both immutable (in the case set' object does
not support item assignment) and mutable in the case add()

Examples:

>>> s1={10,20,30,40,50,10,10}
>>> print(s1,type(s1))------------------{50, 20, 40, 10, 30} <class
'set'>
>>> s2={10,"Rossum",34.56,True,"Python","Rossum"}
>>> print(s2,type(s2))--------------{True, 34.56, 10, 'Rossum',
'Python'} <class 'set'>
>>> len(s1)---------5
>>> len(s2)---------5
>>> s={}
>>> print(s,type(s))----------{} <class 'dict'>
>>> s=set() # empty set
>>> print(s,type(s))------------ set() <class 'set'>

50
---
>>> s1={10,20,30,40,50,10,10}
>>> print(s1)----------------{50, 20, 40, 10, 30}
>>> s1[0]------------TypeError: 'set' object is not subscriptable
>>> s1[0:5]---------TypeError: 'set' object is not subscriptable

>>> s1={10,20,30,40,50,10,10}
>>> print(s1)-----------------{50, 20, 40, 10, 30}
>>> s1[0]=100---------TypeError: 'set' object does not support item
assignment

>>> s1={10,20,30,40,50,10,10}
>>> print(s1)-------------------{50, 20, 40, 10, 30}
>>> s1[0]=100----------------TypeError: 'set' object does not support
item assignment
>>> s1={10,20,30,40,50,10,10}
>>> print(s1,type(s1),id(s1))----------{50, 20, 40, 10, 30} <class
'set'> 1946235969024
>>> s1.add(100)
>>> print(s1,type(s1),id(s1))-----------{50, 20, 100, 40, 10, 30}
<class 'set'> 1946235969024

===============================================
Pre-defined Function in set
===============================================
=>On the object set we can various operations by using the following
pre-defined
functions.

1) add():

=>This function is used for adding the lements to set.


=>Syntax:- setobj.add(Value)

Examples:

>>> s1=set()
>>> print(s1,type(s1),len(s1))----------------set() <class 'set'> 0
>>> s1.add(10)
>>> s1.add("Rossum")
>>> s1.add(11.22)
>>> print(s1,type(s1),len(s1))-----------{'Rossum', 10, 11.22} <class
'set'> 3

2)clear():
=>This function removes all the elements of set object
=>syntax: setobj.clear()

Examples:

>>> s1={'Rossum', 10, 11.22}

51
>>> print(s1)-------------{'Rossum', 10, 11.22}
>>> s1.clear()
>>> print(s1)-------------set()

3) remove():

=>This function is used for removing the element from set object.
=>Syntax:- setobj.remove(value)
=>If the value does not exists then we get KeyError.

Examples:

>>> s2={10,"Rossum",34.56,True,"Python","Rossum"}
>>> print(s2)--------------{True, 34.56, 10, 'Rossum', 'Python'}
>>> s2.remove(10)
>>> print(s2)-------------{True, 34.56, 'Rossum', 'Python'}
>>> s2.remove("Rossum")
>>> print(s2)------------{True, 34.56, 'Python'}
>>> s2.remove(10)-----------KeyError: 10
>>> set().remove(100)------------KeyError: 100

4) discard():

=>This function is used for removing the element from set object.
=>Syntax:- setobj.discardvalue)
=>If the value does not exists then we never get any error.

Examples:

>>> s2={10,"Rossum",34.56,True,"Python","Rossum"}
>>> print(s2)--------------{True, 34.56, 10, 'Rossum', 'Python'}
>>> s2.discard(10)------------
>>> print(s2)----------{True, 34.56, 'Rossum', 'Python'}
>>> s2.discard("Python")
>>> print(s2)-----------------{True, 34.56, 'Rossum'}
>>> s2.discard(34.56)
>>> print(s2)--------------{True, 'Rossum'}
>>> s2.discard("Python") # No Error will come

5)pop()

=>This function is used for removing any arbitrary element of set


object
=>Syntax: setobj.pop()
=>When we call pop() upon empty set object then we get KeyError.

Examples:

>>> s1={10,200,100,30,40,500,55,23,45}
>>> s1.pop()---------------100
>>> s1.pop()--------------200
>>> s1.pop()--------------40
>>> s1.pop()--------------10

52
>>> s1.pop()--------------45
>>> s1.pop()-------------500

Examples:

>>> s2={10,"Rossum",34.56,True,"Python","Rossum"}
>>> print(s2)-------------------{True, 34.56, 10, 'Rossum', 'Python'}
>>> s2.pop()---------True
>>> print(s2)--------{34.56, 10, 'Rossum', 'Python'}
>>> s2.pop()---------34.56
>>> s2.pop()--------10
>>> s2.pop()--------'Rossum'
>>> s2.pop()---------'Python'
>>> print(s2)-------set()
>>> s2.pop()----------KeyError: 'pop from an empty set'

6) copy()

=>This function is used for copying the content of one set object into
another set object (implementing shallow copy)
=>Syntax:- setobj2=setobj1.copy()

Example:

>>> s2={10,"Rossum",34.56,True,"Python","Rossum"}
>>> print(s2,id(s2))-------------{True, 34.56, 10, 'Rossum', 'Python'}
1946235582080
>>> s3=s2.copy()
>>> print(s3,id(s3))-----------{True, 34.56, 10, 'Rossum', 'Python'}
1946235969472
>>> s2.add("Django")
>>> s3.add("Data Scienece")
>>> print(s2,id(s2))---{True, 34.56, 10, 'Rossum', 'Python', 'Django'}
1946235582080
>>> print(s3,id(s3))---{True, 34.56, 10, 'Data Scienece', 'Rossum',
'Python'} 1946235969472

7) union()

=>This function is used for taking all the elements of setobj1 and
setobj2 by taking only unique elements from both setobj1 and setobj2
=>Syntax:- Setobj3=setobj1.union(setobj2)

Examples:

>>> s1={10,20,30,40}
>>> s2={30,40,50,60}
>>> s3=s1.union(s2)
>>> print(s3)------------{40, 10, 50, 20, 60, 30}

8) intersection()

53
=>This function is used for taking common elements of setobj1 and
setobj2
=>Syntax:- Setobj3=setobj1.intersection(setobj2)
Examples:

>>> s1={10,20,30,40}
>>> s2={30,40,50,60}
>>> s4=s1.intersection(s2)
>>> print(s4)------------{40, 30}

9) difference()

=>Syntax:- setobj3=setobj1.difference(setobj2)
=>This function removes common elements from both setobj1 and setobj2
and finally takes remaing elements from setobj1.

Examples:

>>> s1={10,20,30,40}
>>> s2={30,40,50,60}
>>> s3=s1.difference(s2)
>>> print(s3)-----------{10, 20}
>>> s4=s2.difference(s1)
>>> print(s4)---------{50, 60}

10)symmetric_difference()

=>Syntax: setobj3=setobj3=setobj1.symmetric_difference(setobj2)
=>This function removes common elements from both setobj1 and setobj2
and finally takes remaing elements from both setobj1 and setobj2.
Examples:

>>> s1={10,20,30,40}
>>> s2={30,40,50,60}
>>> s5=s1.symmetric_difference(s2)
>>> print(s5)------------{10, 50, 20, 60}

Use Case:

>>> cp={"Kohli","Rohit","Sachin"}
>>> tp={"Rossum","Gosling","Kohli"}
>>> bothpl=cp.union(tp)
>>> print(bothpl)----------------{'Rossum', 'Gosling', 'Rohit',
'Sachin', 'Kohli'}
>>> compl=cp.intersection(tp)
>>> print(compl)-------------{'Kohli'}
>>> onlycp=cp.difference(tp)
>>> print(onlycp)---------------{'Rohit', 'Sachin'}
>>> onlytp=tp.difference(cp)
>>> print(onlytp)-------------------{'Rossum', 'Gosling'}
>>> excptp=cp.symmetric_difference(tp)
>>> print(excptp)------------{'Rossum', 'Rohit', 'Gosling', 'Sachin'}

54
update():

=>This Function is used for updating the elements of one set by the
elements of another set.
=>Syntyax: setobj1.update(setobj2)
=>Here setobj1 values updated with setobj2 values

Examples:

>>> s1={10,20,30,40}
>>> s2={"Java","python","Dj"}
>>> s1.update(s2)
>>> print(s1)-----------{'Java', 'python', 20, 40, 'Dj', 10, 30}
>>> print(s2)----------{'Java', 'Dj', 'python'}

==================================
2. frozenset
==================================
=>'frozenset' is one of the pre-defined class and treated as set data
type.
=>The purpose of frozenset data type is that To store multiple values
of either of same type or different type or both types with Unique
Values in single object."
=>The elements set must organized with curly braces {} and values must
separated by comma and those values can converted into frozenset by
using frozenset()

Syntax:- frozensetobj1=frozenset(setobj)
frozensetobj1=frozenset(listobj)
frozensetobj1=frozenset(tupleobj)

=>An object of frozenset does not maintain insertion Order bcoz PVM
displays any possibility of elements of frozenset

55
=>Since frozenset object does not maintain insertion order, we can't
perform Indexing and Slicing Operations ( set' object is not
subscriptable)
=>An object of frozenset belongs both immutable (in the case frozenset'
object does not support item assignment and adding elements also not
possible)

Note:-The Functionality of frozenset is similar to set but an object of


set belongs to both immutable ( in case of item assigment) and mutable
(in the case of add()) where as an object frozenset belongs to
immutbale

Examples:

l1=[10,20,30,40,10]
fs=frozenset(l1)
print(fs,type(fs))----------------frozenset({40, 10, 20, 30}) <class
'frozenset'>
fs.add(100)------------AttributeError: 'frozenset' object has no
attribute 'add'
fs[0]=345------------TypeError: 'frozenset' object does not support
item assignment

Pre-defined functions in frozenset

1) copy()
2) union()
3) intersection()
4) difference()
5) symmetric_difference()

Examples:

>>> s1={10,20,30,40}
>>> s2={15,25,30,40}
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1)
frozenset({40, 10, 20, 30})
>>> print(fs2)
frozenset({40, 25, 30, 15})
>>> fs3=fs1.union(fs2)
>>> print(fs3)
frozenset({40, 10, 15, 20, 25, 30})
>>> fs4=fs1.intersection(fs2)
>>> print(fs4)
frozenset({40, 30})
>>> fs5=fs1.difference(fs2)
>>> print(fs5)
frozenset({10, 20})
>>> fs6=fs2.difference(fs1)
>>> print(fs6)
frozenset({25, 15})
>>> fs7=fs2.symmetric_difference(fs1)

56
>>> print(fs7)
frozenset({10, 15, 20, 25})
>>> fs7=fs1.symmetric_difference(fs2)
>>> print(fs7)
frozenset({10, 15, 20, 25})

>>> s1={10,20,30,40}
>>> fs1=frozenset(s1)
>>> fs2=fs1.copy()
>>> print(fs1,id(fs1))-----------------frozenset({40, 10, 20, 30})
2299638113984
>>> print(fs2,id(fs2))-----------------frozenset({40, 10, 20, 30})
2299638113984
============================X=================================

================================================================
dict Catagery Data Type ( Collection Data Types or Data Structures)
================================================================
=>The purpose of dict Catagery Data Type is the "To organize the data
in the form of
(Key,Value)"
=>To organize the data in the form (key,value), we use a pre-defined
class called "dict".
=>"dict" is one of the pre-defined class and treated as dict Catagery
Data Type
=>The elements of dict must be organized in the form curly braces { }
and (key,value) must separated by comma.
=>An object of dict maintains insertion Order.
=>On the object of dict, we can't perform Indexing and Slicing
Operations.
=>An object of dict belongs to mutable. In otherwords , The Values of
Key are belongs to immutable and Values of Value are belongs to mutable
=>By using dict class , we can create two types of dict objects. They
are
a) empty dict
b) non-empty dict
a) An empty dict is one, which does not contains any elements and whose
length is 0.
Syntax:- dictobj={}
(or)
dictobj=dict()

=>Syntax for adding (Key,value) to empty dict object

dictobj[Key1]=Value1
dictobj[Key2]=Value2

dictobj[Key-n]=Value-n

b) A non-empty dict is one, which contains elements and whose length


is >0.
Syntax:- dictobj={Key1:Val1,
Key2:Val2.......Key-n:Val-n}
Here Key1,Key2...Key-n are called Keys and They are
Unique and they can be either Strs or Numerics

57
Here Val1,Val2...val-n are called Values and They may be
Unique or duplicate and they can be either Strs or Numerics

Examples:

>>> d1={}
>>> print(d1,type(d1))---------------{} <class 'dict'>
>>> len(d1) 0
>>> d2={10:1.2,20:2.5,30:2.5,40:4.5}
>>> print(d2,type(d2))-----------{10: 1.2, 20: 2.5, 30: 2.5, 40: 4.5}
<class 'dict'>
>>> len(d2)------------4
>>> d3=dict()
>>> print(d3,type(d3), len(d3))-------- {} <class 'dict'> 0
>>> d1={"Rossum":"Python","Ritche":"C", "Gosling":"Java"}
>>> print(d1,type(d1))----{'Rossum': 'Python', 'Ritche': 'C',
'Gosling': 'Java'} <class
'dict'>
>>> d2={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d2)-----{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'}
>>> print(d2[0])--------KeyError: 0
>>> print(d2[10])---------Apple
>>> print(d2[40])--------Sberry
>>> print(d2[400])--------KeyError: 400

>>> d1={}
>>> print(d1,type(d1),len(d1), id(d1))----{} <class 'dict'> 0
2299637840384
>>> d1[100]="Rossum"
>>> d1[101]="Ritche"
>>> d1[102]="Travis"
>>> d1[103]="MCKinney"
>>> print(d1,type(d1),len(d1), id(d1))----{100: 'Rossum', 101:
'Ritche', 102: 'Travis', 103:

>>> d1[100]="Guido"
>>> print(d1,type(d1),len(d1), id(d1))-----{100: 'Guido', 101:
'Ritche', 102: 'Travis', 103:
==============================X================================

========================================
Pre-defined Functions in dict
========================================
=>On the object of dict, we can perform various operations by using
pre-defined functions presents in dict and they are given bellow.

1) clear():

58
=>This Function is used for removing all elements of dict object.
=>Syntax:- dictobj.clear()

=>Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1)---{10: 'Python', 20: 'Django', 30: 'data science', 40:
'ML'}
>>> print(len(d1))----4
>>> d1.clear()
>>> print(d1,len(d1))-------{} 0

2) copy() :

=>This function is used for copying the content of one dict object into
another dict object content.(Implementation of shallow copy)
=>Syntax:- dictobj2=dictobj1.copy()

Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1,id(d1))--{10: 'Python', 20: 'Django', 30: 'data science',
40: 'ML'} 1744081404928
>>> d2=d1.copy() # shallow copy
>>> print(d2,id(d2))--{10: 'Python', 20: 'Django', 30: 'data science',
40: 'ML'} 1744081404544
>>> d1[50]="DL"
>>> d2[45]="C"
>>> print(d1,id(d1))--{10: 'Python', 20: 'Django', 30: 'data science',
40: 'ML', 50: 'DL'} 1744081404
>>> print(d2,id(d2))---{10: 'Python', 20: 'Django', 30: 'data science',
40: 'ML', 45: 'C'} 1744081404

3) pop():

=>Syntax: dictobj.pop(Key)
=>This Function is used for deleting the (Key,value) from dict object
by passing value of Key.
=>If the Value of Key does not exists then we get KeyError.

Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1,id(d1))-----{10: 'Python', 20: 'Django', 30: 'data
science', 40: 'ML'}
1744081419840
>>> d1.pop(10)----------'Python'
>>> print(d1,id(d1))-----{20: 'Django', 30: 'data science', 40: 'ML'}
1744081419840
>>> d1.pop(40)----'ML'
>>> print(d1,id(d1))---{20: 'Django', 30: 'data science'} 1744081419840
>>> d1.pop(100)----KeyError: 100
>>> d1.pop("Django")---KeyError: 'Django'

4) popitem()

59
=>Syntax:- dictobj.popitem()
=>This function is used for removing last (key,value) entry from dict
obj.
=>Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1,id(d1))---{10: 'Python', 20: 'Django', 30: 'data science',
40: 'ML'} 1744081404928
>>> d1.popitem()-----(40, 'ML')
>>> print(d1,id(d1))---{10: 'Python', 20: 'Django', 30: 'data science'}
1744081404928
>>> d1.popitem()----(30, 'data science')
>>> print(d1,id(d1))----{10: 'Python', 20: 'Django'} 1744081404928
>>> d1.popitem()----(20, 'Django')
>>> print(d1,id(d1))----{10: 'Python'} 1744081404928
>>> d1.popitem()-----(10, 'Python')
>>> print(d1,id(d1))----{} 1744081404928
>>> d1.popitem()-----KeyError: 'popitem(): dictionary is empty'

5) get()

Syntax:- valueobj=dictobj.get(key)
=>This Function is used for obtaining value of Value by passing Value
of Key.
=>If the Value of key does not exists then we get None.
Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1,id(d1))--{10: 'Python', 20: 'Django', 30: 'data science',
40: 'ML'} 1744081419840
>>> d1[10]-----'Python'
(OR)
>>> value=d1.get(10)
>>> print(value)----Python
>>> value=d1.get(20)
>>> print(value)-----Django
>>> value=d1.get(30)
>>> print(value)----data science
>>> value=d1.get(400)
>>> print(value)-----------None

>>> states={"TS":"HYD","KAR":"BANG","TN":"CHE"}
>>> print(states, type(states))---{'TS': 'HYD', 'KAR': 'BANG', 'TN':
'CHE'} <class 'dict'>
>>> states.get("TS")---'HYD'
>>> states.get("KAR")----'BANG'
>>> states.get("TN")----'CHE'
>>> val=states.get("ammerpet")
>>> print(val)----------None

6) keys():

60
=>Syntax:- dictobj.keys()
=>This function obtains list of Keys

Examples:

>>> states={"TS":"HYD","KAR":"BANG","TN":"CHE"}
>>> states.keys()-----------dict_keys(['TS', 'KAR', 'TN'])
(OR)
>>> sts=states.keys()
>>> print(sts)---------dict_keys(['TS', 'KAR', 'TN'])
>>> for state in sts:
... print(state)
...
TS
KAR
TN
>>> for st in states.keys():
... print(st)
...
TS
KAR
TN

--

7) values():

Syntax:- dictobj.values()
=>This function obtains list of Values.
Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1,id(d1))----{10: 'Python', 20: 'Django', 30: 'data
science', 40: 'ML'}
1744081404928
>>> d1.values()---dict_values(['Python', 'Django', 'data science',
'ML'])
(OR)
>>> vals=d1.values()
>>> print(vals)----dict_values(['Python', 'Django', 'data science',
'ML'])
>>> for val in vals:
... print(val)
...
Python
Django
data science
ML
>>> for val in d1.values():
... print(val)
...
Python
Django
data science
ML

61
8)items():

=>Syntax:- dictobj.items()
=>This Function gives set of (Key,Value)

Examples:

>>> d1={10:"Python",20:"Django",30:"data science",40:"ML"}


>>> print(d1)----{10: 'Python', 20: 'Django', 30: 'data science', 40:
'ML'}
>>> d1.items()---dict_items([(10, 'Python'), (20, 'Django'), (30, 'data

science'),(40,'ML')])
(OR)
>>> kv=d1.items()
>>> print(kv)---dict_items([(10, 'Python'), (20, 'Django'), (30, 'data
science'), (40, 'ML')])
(OR)
>>> for entry in d1.items():
... print(entry)
...
(10, 'Python')
(20, 'Django')
(30, 'data science')
(40, 'ML')
(OR)
>>> for k,v in d1.items():
... print(k,"--->",v)
...
10 ---> Python
20 ---> Django
30 ---> data science
40 ---> ML

update():

=>Syntax:- dictobj1.update(dictobj2)
=>This functions updates ( Modify, Insert) dictobj1 values with
dictobj2 values.

Examples:

>>> d1={10:2.3,20:3.4}
>>> d2={30:3.4,40:5.6,50:1.2}
>>> d1.update(d2)
>>> print(d1)-----------{10: 2.3, 20: 3.4, 30: 3.4, 40: 5.6, 50: 1.2}
>>> d1={10:2.3,20:3.4}
>>> d2={10:13.4,20:44.44,50:1.2}
>>> d1.update(d2)
>>> print(d1)-------------{10: 13.4, 20: 44.44, 50: 1.2}

Special Case:

62
>>> for x in d1:
... print(x)
...
10
20
30
40

Special Case:
>>> d1={"sno":10,"sname":"Ram",
"IntMarks":[18,19,17],"ExtMarks":[78,77,66],"cname":"OUCET"}
>>> print(d1, type(d1))
{'sno': 10, 'sname': 'Ram', 'IntMarks': [18, 19, 17], 'ExtMarks': [78,
77, 66], 'cname': 'OUCET'} <class 'dict'>
>>> for k,v in d1.items():
... print(k,v)
...
sno 10
sname Ram
IntMarks [18, 19, 17]
ExtMarks [78, 77, 66]
cname OUCET

>>> d1.get("IntMarks")---------[18, 19, 17]


>>> d1.get("ExtMarks")-----------[78, 77, 66]
Note: For keys in dict, we can have list or tuple or set of Values .

Special Case:

>>> l1=[("sno",10),("sname","Rossum"),("Marks",55.55),("cname","OUCET")
]
>>> print(l1,type(l1))
[('sno', 10), ('sname', 'Rossum'), ('Marks', 55.55), ('cname',
'OUCET')] <class 'list'>
>>> for val in l1:
... print(val)
...
('sno', 10)
('sname', 'Rossum')
('Marks', 55.55)
('cname', 'OUCET')
>>> l1[0]
('sno', 10)

>>> d2=dict(l1) # Converting list of tuples into dict object.

>>> print(d2)--{'sno': 10, 'sname': 'Rossum', 'Marks': 55.55, 'cname':


'OUCET'}
>>> for k,v in d2.items():
... print(k,v)
...
sno 10
sname Rossum
Marks 55.55
cname OUCET

63
>>> l1=[10,20,30,40,50]
>>> d1=dict(l1)-- TypeError: cannot convert dictionary update sequence
element #0
to a sequence

=======================================
NoneType data type
=======================================
=>'NoneType' is one the pre-defined class and treated as None type Data
type
=> "None" is keyword acts as value for <class,'NoneType'>
=>The value of 'None' is not False, Space , empty , 0
=>An object of NoneType class can't be created explicitly.

Examples:

>>> a=None
>>> print(a,type(a))------------None <class 'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType' is not defined

==============================================
Batch Mode Programming
==============================================
=>In real time, to develop any python program, we have two approaches.
they are
a) Interactive Mode
b) Batch Mode

a) Interactive Mode:

=>In this mode of Development, Python Programmer can issue a single


statement and obtains single result
=>This Mode of development is most useful for testing one Instruction
at a time.
=>This Mode of development is not recommended for Big Problem Solving
bcoz Big Problem solving statements are possible to to save and more
over re-using the statements of Interactive mode on other parts of the
projects is not possible.
=>hence To solve Big Problems we must go for Batch Mode Programming.

Example softwares Interative Mode: Python Command Prompt, Python IDLE

b) Batch Mode:

=>In This Mode of Development, Python Progammer develops or writes


batch or group of Optimized Instructions and saved on file name with an
extension .py (Source Code).

Examples Softwares

64
1) Python IDLE

2) EDIT PLUS
3) Pycharm
4) VS Code
5) Jupiter Note Book
6) atom
7) spider
8) sub lime text etc

#Program mul of two numbers


a=float(input("Enter First value:"))
b=float(input("Enter Second Value:"))
c=a*b
print("="*50)
print("Val of a=",a)
print("Val of b=",b)
print("Mul=",c)
print("="*50)

#This program accepts two numbers and find sum


a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
c=a+b
print("Val of a=",a)
print("Val of b=",b)
print("Sum=",c)

#This Program performs sum of two numbers


a=100
b=200
c=a+b
print("Val of a=",a)
print("Val of b=",b)
print("Val of c=",c)

=======================================================
Displaying the result of python Program on the console
=======================================================
=>To Display the result of python Program on the console, we use a pre-
defined Function called print().
=>In Otherwords, print() is used for displaying the result of python on
the console.
=>We can use print() in various ways :

Syntax1: print(val1,val2......val-n)
=>This syntax displays only values on the console.

Example:

65
>>> a=10
>>> print(a)------------10
>>> b="Python Prog"
>>> print(b)-----------Python Prog
>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)------------10 20 30

Syntax2: print(message)
=>This syntax display only messages , which are nothing but str

Examples:

>>> print("Hello PYTHON World")-----------------Hello PYTHON World


>>> print('Hello PYTHON World')------------------Hello PYTHON World
>>> print('''Hello PYTHON World''')---------------Hello PYTHON World
>>> print("""Hello PYTHON World""")-----------Hello PYTHON World

Syntax3: print(Messages cum Value)


(OR)
print(Value Cum Messages)

=>This syntax displays Message cum Values OR Values cum Messages.

>>> a=10
>>> print("Val of a=",a)------------------Val of a= 10
>>> print(a," is the val of a")---------10 is the val of a
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum=",c)-----------sum= 30
>>> print(c,"is the sum")---------30 is the sum
>>> print("sum of ",a," and ",b,"=",c)--------sum of 10 and 20 = 30
>>> a=10
>>> b=20
>>> c=30
>>> d=a+b+c
>>> print("sum of ",a,",",b," and ",c,"=",d)----sum of 10 , 20 and
30 = 60

Syntax4: print(Messages cum Value with format() )


(OR)
print(Value Cum Messages with format() )
Examples:

>>> a=10
>>> print("Val of a={}".format(a) )---------------Val of a=10
>>> print("{} is the val of a".format(a))---------10 is the val of a
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum={}".format(c))----------sum=30
>>> print("{} is the sum".format(c))--------30 is the sum

66
>>> print("Sum of {} and {}={}".format(a,b,c) )-----Sum of 10 and 20=30

>>> a=1
>>> b=2
>>> c=3
>>> d=a+b+c
>>> print("sum of {},{} and {}={}".format(a,b,c,d))---------sum of 1,2
and 3=6

Syntax5: print(Messages cum Value with format Specifiers )


(OR)
print(Value Cum Messages with format Specifiers )

Examples:

>>> a=10
>>> print("Val of a=%d" %a)-------------Val of a=10
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum of %d and %d=%d" %(a,b,c))-----------Sum of 10 and 20=30
>>> print("Sum of %f and %f=%f" %(a,b,c))---Sum of 10.000000 and
20.000000=30.000000
>>> print("Sum of %0.2f and %0.3f=%0.4f" %(a,b,c))----Sum of 10.00 and
20.000=30.0000
>>> print("Sum of %0.2f and %d=%0.2f" %(a,b,c))---Sum of 10.00 and
20=30.00
>>> sno=10
>>> sname="Rossum"
>>> marks=34.56
>>> print("My Number is %d and Name is %s and Marks is %f"
%(sno,sname,marks))
My Number is 10 and Name is Rossum and
Marks is 34.560000

Special Case:

>>> sno=100
>>> sname="Ram"
>>> print("%s 's Roll Number is %d" %(sname,sno))-------Ram 's Roll
Number is 100
>>> print("Roll Number is {} and Name is '{}' ".format(sno,sname))--
Roll Number is 100 and
>>> print("Roll Number is %d and Name is '%s' "%(sno,sname))
Roll Number
is 100 and Name is 'Ram'

=======================================================
Reading the data Dynamically from Key Board
=======================================================
=>To read the data dynamically from Key Board, we use two pre-defined
Functions. They are
1) input()

67
2) input(Message)

1) input():

=>This Function is used for Reading Any Type of Data from Key Board
in the form str only.
=>Programatically, to convert str type into other types, we use Type
Casting Techniques.

=>Syntax:- varname=input()
=>here varname is an object of type <class,'str'>
=>input() is one of the pre-defined Function

Examples:

#Program for sum of two numbers


print("Enter First Value:")
a=input()
print("Enter Second Value:")
b=input()
#convert str data into
x=float(a)
y=float(b)
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

(OR)
#Program for sum of two numbers
print("Enter Two Values:")
a=input()
b=input()
#convert str data into
x=float(a)
y=float(b)
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

(OR)
#Program for sum of two numbers
print("Enter Two Values:")
x=float(input())
y=float(input())
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

=======================================================
Reading the data Dynamically from Key Board
=======================================================
=>To read the data dynamically from Key Board, we use two pre-defined
Functions. They are

68
1) input()
2) input(Message)

1) input():

=>This Function is used for Reading Any Type of Data from Key Board
in the form str only.
=>Programatically, to convert str type into other types, we use Type
Casting Techniques.

=>Syntax:- varname=input()
=>here varname is an object of type <class,'str'>
=>input() is one of the pre-defined Function

Examples:

#Program for sum of two numbers


print("Enter First Value:")
a=input()
print("Enter Second Value:")
b=input()
#convert str data into
x=float(a)
y=float(b)
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

(OR)
#Program for sum of two numbers
print("Enter Two Values:")
a=input()
b=input()
#convert str data into
x=float(a)
y=float(b)
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

(OR)
#Program for sum of two numbers
print("Enter Two Values:")
x=float(input())
y=float(input())
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))
=====================================x=================================
==
2) input(Message):

=>This Function is used for reading any type value from Key Board in
the form of str type additionally with this function we can give User-
Prompting Message.
=>Programatically, to convert str type into other types, we use Type
Casting Techniques.

69
=>Syntax: varname=input(Message)

=>here varname is an object of type <class,'str'>


=>input() is one of the pre-defined Function
=>"Message" represents User-Prompting Message.

Examples:

r=float(input("Enter Radious:"))
ac=3.14*r*r
pc=2*3.14*r
print("Area of Circle={}".format(ac))
print("Perimeter of Circle=%0.2f" %pc)

#Program for sum of two numbers


print("Enter First Value:")
a=input()
print("Enter Second Value:")
b=input()
#convert str data into
x=float(a)
y=float(b)
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

#Program for sum of two numbers


print("Enter Two Values:")
a=input()
b=input()
#convert str data into
x=float(a)
y=float(b)
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

#Program for sum of two numbers


print("Enter Two Values:")
x=float(input())
y=float(input())
#add x and y
z=x+y
print("Sum of {} and {}={}".format(x,y,z))

70
#This program calculates Area and Perimeter if Circle
r=float(input("Enter Radious:"))
ac=3.14*r*r
pc=2*3.14*r
print("Area of Circle={}".format(ac))
print("Perimeter of Circle=%0.2f" %pc)

#program for cal area of Triangle


b=float(input("Enter Base:"))
h=float(input("Enter Height:"))
at=1/2*b*h
print("Area of Triangle={}".format(at) )

===========================================
Operators and Expressions in Python
===========================================
=>An Operartor is symbol which is used to perform certain operations on
the objects.
=>If any operator connected with two or more object or variables then
it is called Expression.
=>In Python Programming, we have 7 operators. They are

1. Arithmetic Operators.
2. Assigment Operator
3. Relational Operators
4. Logical Operators
5. BitWise Operators (Most Imp )
6. Membership Operators
a) in
b) not in
7. Identity Operators
a) is
b) is not

Note: Python does not contain


a) Pre / Post Increment , Decrement ( ++
-- )
b) Ternary Operator ( ? : )

=>Note That Python contains " if else Operator " instead of Ternary
Operator

===================================================
1. Arithmetic Operators.
===================================================
=>The purpose of Arithmetic Operators is that " To Perform Arithmetic
Operations such as

71
Addition, Substraction, multiplication..etc".
=>If two or more variables or objects connected with Arithmetic
Operators then it is called
Arithmetic Expression.
=>In Python Programm, we have 7 Arithmetic Operators and they are given
following Table .
=======================================================================
=====
SlNo Symbol Meaning Example
=======================================================================
=====
1 + Addition pri

2 - Substraction print(a-b)

3 * Multiplication print(a *

4 / Division print(a/b) (floating point


Quotient)
5 // floor Division print(a//b (Integer Quotient)
6 % Modulo Division print(a%b) (Remainder)
7 ** Exponentiation print(a**b) 1000
=======================================================================
=====

#program for demonstrating Arithemtic Operators


a=int(input("Enter Value a:"))
b=int(input("Enter Value b:"))
print("*"*40)
print("Arithmetic Operators")
print("*"*40)
print("sum({},{})={}".format(a,b,a+b))
print("sub({},{})={}".format(a,b,a-b))
print("mul({},{})={}".format(a,b,a*b))
print("div({},{})={}".format(a,b,a/b))
print("floor Div({},{})={}".format(a,b,a//b))
print("mod({},{})={}".format(a,b,a%b))
print("pow({},{})={}".format(a,b,a**b))
print("*"*40)

#program for cal square root of n


n=float(input("Enter value of n:"))
res=n**0.5
print("SquareRoot({})={}".format(n,res))

==================================================
2. Assigment Operator
==================================================
=>The purpose of assignment operator is that " To assign or transfer
Right Hand Side (RHS)

72
Value / Expression Value to the Left Hand Side (LHS) Variable "
=>The Symbol for Assigment Operator is single equal to ( = ).
=>In Python Programming,we can Assigment Operator in two ways.
1. Single Line Assigment
2. Multi Line Assigment

1. Single Line Assigment:

=>Syntax: LHS Varname= RHS Value


LHS Varname= RHS Expression

=>With Single Line Assigment at a time we can assign one RHS Value /
Expression to the single LHS Variable Name.

Examples:

>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)------------10 20 30

2. Multi Line Assigment:

=>Syntax: Var1,Var2.....Var-n= Val1,Val2....Val-n

Var1,Var2.....Var-n= Expr1,Expr2...Expr-n

Here The values of Val1, Val2...Val-n are assigned to Var1,Var2. Var-n


Respectively.
Here The values of Expr1, Expr2...Expr-n are assigned to
Var1,Var2...Var-n Respectively.

Examples:

>>> a,b=10,20
>>> print(a,b)------------10 20
>>> c,d,e=a+b,a-b,a*b
>>> print(c,d,e)-------------30 -10 200
===================================X===================================
===

#Program for swapping of any two values by using Multi line assingment
#Swap.py
a,b=input("Enter Value of a:"), input("Enter Value of b:")
print("="*40)
print("Original Value of a={}".format(a))
print("Original Value of b={}".format(b))
print("="*40)
#swapping Logic
a,b=b,a # Multi line assigment.
print("Swapped Value of a={}".format(a))
print("Swapped Value of b={}".format(b))
print("="*40)

73
===================================================
3. Relational Operators
===================================================
=>The purpose of Relational Operators is that " To compare two or more
values".
=>If two or more objects or variables connected with Relatioal
Operators then it is called
"Relation Expression".
=>The result of Relational Expression is either True or False and
Relation Expression is called
Test Condition.
=>The following table list of Relational Operators
=======================================================================
===
SLNO Symbol Meaning
Examples
=======================================================================
===
1 > Greater Than pri

2 < Less Than pri

3. == Equality

4. != Not Equal to pri

5. >= Greater Than pri


or Equal to pri

6. <= Less Than pri


or Equal to pri
====================================X==================================
=
#Program for demonstating Relational Operators
#rop.py
a,b=int(input("Enter Value of a:")), int(input("Enter Value of b:"))
print("="*50)
print("\tRelational Operators")
print("="*50)
print("\t\t{} > {}={}".format(a,b,a>b))
print("\t\t{} < {}={}".format(a,b,a<b))
print("\t\t{} == {}={}".format(a,b,a==b))
print("\t\t{} != {}={}".format(a,b,a!=b))
print("\t\t{} >= {}={}".format(a,b,a>=b))
print("\t\t{}<= {}={}".format(a,b,a<=b))
print("="*50)
======================================X==============================

===================================================
4. Logical Operators

74
===================================================
=>The purpose of Logical Operators is that "To compare the result of
two or more Relations
Expressions".
=>If two or more Relational Expressions connetced with Logical
Operators then It is called
Logical Expression or Compund Condition and it can evaluate either
to be True or False.

=>We have 3 types of Logical Operators and They are given the following
Table
====================================================================
SLNO Symbol Meaning
====================================================================
1. and Physical ANDing
2. or Physical ORing
3. not -------------------------
====================================================================

1) 'and' Operator:

=>The Funtionality of 'and' operator can be expressed by using


following Truth Table

=================================================
Rel Expr1 Rel Expr2 RelExpr1 and RelExpr2
=================================================
True False False
False True False
False False False
True True True
=================================================

Examples:-

1. print( 10>2 and 10>8 )---------------True


2. print( 10>3 and 20>4 and 100>300)------False
3. print(100>200 and 20>3 and 10>2)----False----Called Short Circuit
Evaulation

Short Circuit Evaulation in "and" Operator:

=>If "and" operator connected with two or more Relational Expressions


and if First Relational Expression False then PVM will not evaluate
Second and Sub sequeent Relational Expression and result of entire
Logical Expression is False. This Process of evaluation of "and"
operator is called Short Circuit Evaulation.
=======================================================================
=====

2) 'or' Operator:

=>The Funtionality of 'or' operator can be expressed by using following


Truth Table

=================================================
Rel Expr1 Rel Expr2 RelExpr1 or RelExpr2
=================================================

75
True False True
False True True
False False False
True True True
=================================================

Examples:

1. print( 10<20 or 10<3 or 20<3 )--------------True---Called Short


Circuit Evaulation
2. print( 10>20 or 10<3 or 20>3 )--------------True
3. print( 10>20 or 10<3 or 20>300 )--------------False
>>> print(10>2 or 10>100 or 20>300 or 40>34)---------True---Called
Short Circuit Evaulation
>>> print(10>20 or 10>100 or 20>300 or 40>340)-----False
>>> print(10>20 or 10>100 or 20<300 or 40>340)-----True--Called Short
Circuit Evaulation

Short Circuit Evaulation in "or" Operator:

=>If "or" operator connected with two or more Relational Expressions


and if First Relational Expression True then PVM will not evaluate
Second and Sub sequeent Relational Expressions and result of entire
Logical Expression is True. This Process of evaluation of "or" operator
is called Short Circuit Evaulation.
==============================X========================================
3) 'not' Operator:

=>The Funtionality of 'not' operator can be expressed by using


following Truth Table

=================================================
Rel Expr1 ! Rel Expr1
=================================================
True False
False True

=================================================

=>The 'not' operator the express the opposite result of Existing Result
of Relation Expression or Logical Expression.

Examples:

>>> print(100>20)--------------True
>>> print(not 100>20)-----------False
>>> print(100>20 and 100>34)------True
>>> print(not (100>20 and 100>34) )---------False
>>> print(100<20 or 100<34 )-----------False
>>> print( not(100<20 or 100<34 ) )----------True
================================X======================================
=====

76
#Program for demonstating Relational Operators
#rop.py
a,b=int(input("Enter Value of a:")), int(input("Enter Value of b:"))
print("="*50)
print("\tRelational Operators")
print("="*50)
print("\t\t{} > {}={}".format(a,b,a>b))
print("\t\t{} < {}={}".format(a,b,a<b))
print("\t\t{} == {}={}".format(a,b,a==b))
print("\t\t{} != {}={}".format(a,b,a!=b))
print("\t\t{} >= {}={}".format(a,b,a>=b))
print("\t\t{}<= {}={}".format(a,b,a<=b))
print("="*50)

#Program for swapping of any two values by using Multi line assingment
#Swap.py
a,b=input("Enter Value of a:"), input("Enter Value of b:")
print("="*40)
print("Original Value of a={}".format(a))
print("Original Value of b={}".format(b))
print("="*40)
#swapping Logic
a,b=b,a # Multi line assigment.
print("Swapped Value of a={}".format(a))
print("Swapped Value of b={}".format(b))
print("="*40)

=============================================
5. Bitwise Operators ( Most Imp )
=============================================
=>The purpose of Bitwise operators is that "To perform the operations
on Integer data
in the fiorm bit by bit".
=>Bitwise Operators applicable on Integer Data but not on floating
point values.
=>Bitwise operators First converts Integer data into Binary format ,
performs the
operation on binary data in the form of bit by bit and gives the
finaly result in the decimal number system.
=>In Python programming, we have the following Bitwise Operators.

1) Bitwise Left Shift Operator( << )


2) Bitwise Right Shift Operator( >> )
3) Bitwise OR Operator ( | )
4) Bitiwse AND Operator ( & )
5) Bitwise NOT or Complement Operator ( ~ )
6) Bitwise XOR Operator ( ^ )

1) Bitwise Left Shift Operator( << ):

Stnyax:-
------------ varname = GivenNumber << No.of Bits

77
=>This Operator is Flipping-off the number of bits from left side and
adding number of zeros ( depending on number of Bits ) at Right Side.

Examples:

>>> print(10<<3)---------------80
>>> print(20<<2)--------------80
>>> print(12<<3)-------------96
>>> print(2<<2)--------------8

2) Bitwise Right Shift Operator( >> ):

Stnyax:-
------------ varname =GivenNumber >> No.of Bits
=>This Operator is Flipping-off the number of bits from right side and
adding number of zeros ( depending on number of Bits ) at Left Side.

Examples:

>>> print(10>>3)---------------1
>>> print(23>>2)--------------5
>>> print(16>>3)--------------2
=================================================================
3) Bitwise OR Operator ( | ):

=>The Fuunctionality of Bitwise OR Operator ( | ) is shown in the


following truth table.
=>Syntax: resultvar = Var1 | Var2

=============================
Var1 Var2 Var1 | Var2
=============================
0 1 1
1 0 1
0 0 0
1 1 1
=============================

Example:-

>>>a=4 > 0100


>>>b=5 > 0101

>>>c=a|b > 0101 >5


>>>print(c)-------5

>>> print(4|3) 7
>>> print(15|3)--------------15
>>>print(10|15)------------15

Special Case of Bitwise OR (|):

>>> s1={10,20,30,40}
>>> s2={30,40,50,60}
>>> s3=s1.union(s2)

78
>>> print(s3)-------------------{40, 10, 50, 20, 60, 30}
>>>
>>>
>>> s1={10,20,30,40}
>>> s2={30,40,50,60}
>>> s3=s1|s2
>>> print(s3)------------------{40, 10, 50, 20, 60, 30}
===========================X==================================
4) Bitiwse AND Operator ( & ):

=>The Fuunctionality of Bitwise AND Operator ( & ) is shown in the


following truth table.
=>Syntax: resultvar = Var1 & Var2
=============================
Var1 Var2 Var1 & Var2
=============================
0 1 0
1 0 0
0 0 0
1 1 1
=============================

Examples:

>>>a=4 > 0100


>>>b=3 > 0011

>>>c=a&b > 0000 Result


>>>print(c)-----------0

>>>print(15&4)-----------> 4
>>> print(10&15)----------->10

Special Examples:

>>>s1={10,20,30,40}
>>>s2={15,25,30,35,40}
>>> s3=s1.intersection(s2)
>>> print(s3)-----------{40, 30}

>>> s4=s1&s2
>>> print(s4)----------{40, 30}
>>> s1={"Python","Java","Django"}
>>> s2={"Data Scienece","Python","Pyramid"}
>>> s3=s1&s2
>>> print(s3)----------{'Python'}
====================================================================
5) Bitwise NOT or Complement Operator ( ~ )

Syntax:-

79
=> varname= ~Value
=>The formula for Bitwise Complement Operator is - ( Given Value +
1 )

Examples:

>>>n=10
>>>res= ~n ------------------ -(1010+1)----> -(1011)--->result
is -11
>>>print(res)--------11
>>> n=98
>>> print( ~n )---------------------99
>>> n= -102
>>> print(~n)------------ 101
================================================================
6) Bitwise XOR Operator ( ^ ):

=>The Fuunctionality of Bitwise XOR Operator ( ^ ) is shown in the


following truth table.
=>Syntax: resultvar = Var1 ^ Var2
=============================
Var1 Var2 Var1 ^ Var2
=============================
0 1 1
1 0 1
0 0 0
1 1 0
=============================

Examples:

>>>a=4 >0100
>>>b=5 > 0101

>>>c=a^b >0001 Result is 1


>>>print(c)
>>> print(15^10)------------5

-
Special Cases:

>>> s1={"Apple","banana","Mango"}
>>> s2={"Kiwi","Apple","Guava"}
>>> s3=s1^s2
>>> print(s3)---------------{'banana', 'Guava', 'Mango', 'Kiwi'}
>>>
>>> s4=s1.symmetric_difference(s2)
>>> print(s4)-------------------{'banana', 'Guava', 'Mango', 'Kiwi'}

>>> s1={10,20,30,40}
>>> s2={40,50,10,20}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3)------------------{50, 30}
>>>
>>> s4=s1^s2
>>> print(s3)------------------{50, 30}

80
Special logic

>>> a=4
>>> b=3
>>> print(a,b)------------4 3----original values
>>> a=a^b
>>> b=a^b
>>> a=a^b
>>> print(a,b)------------3 4-----Swapped values.

================================
6. Membership Operators
================================
=>The purpose of Membership operators is that " To check wether the
specified value present in Iterabale object or not ".
=>An Iterable object is one, which contains Multiple Values (Sequence,
List, Set and Dict type ).
=>We have two type of Membership Operators. They are
a) in
b) not in

a) in:

=>Syntax: Value in Iterable_Object


=>"in" operator returns True provided "value" present in Iterable
object.
=>"in" operator returns False provided "value" not present in Iterable
object.

b) not in:

=>Syntax: Value not in Iterable_Object


=>"not in" operator returns True provided "value" not present in
Iterable object.
=>"not in" operator returns False provided "value" present in Iterable
object.

Examples:

>>> s="PYTHON"
>>> print(s)------------------PYTHON
>>> "P" in s True
>>> "K" in s----------------False
>>> "PYT" in s-------------True
>>> "pyt" in s--------------False
>>> "HON" in s--------------True
>>> "NOH" in s----------------False
>>> "NOH" in s[::-1]------------True
>>> s in s[::-1]---------------False

81
>>> s in s True
>>> "k" not in s---------------True
>>> "P" not in s------------------False
>>> "HON" not in s---------------False
>>> "HON"[::-1] not in s-----------------True

>>> l1=[10,"ROSSUM",45.67,True]
>>> 10 in l1 True
>>> 45.66 not in l1----------------True
>>> 45.67 not in l1-----------------False
>>> False not in l1---------------True
>>> False in l1-------------------False
>>> "ROSSUM" in l1----------------True
>>> "ROSSUM" not in l1---------------False
>>> "ROSsum" not in l1----------------True
>>> "ROSsum" in l1----------------------False
>>> l1=[10,"ROSSUM",45.67,True]
>>> "Biswajit" in l1--------------------False
>>> "Biswajit" not in l1-----------------True

>>> l1=[10,"ROSSUM",45.67,True]
>>> "ROS" in l1-----------------False
>>> "ROS" in l1[1]----------------True
>>> "Ros" not in l1[1]-------------True
>>> "SOR" not in l1[1]---------------True
>>> "SOR"[::-1] in l1[1]----------------True
>>> "SOR"[::-1] in l1[1][::-1]------------------False

>>> a=10
>>> 10 in a------------------------TypeError: argument of type 'int' is
not iterable

#Searchex1.py
lst=[10,20,30,40,50,15,25,35]
val=int(input("Enter the value for searching:") ) # 400
res=val in lst
result="Search is Sucessful" if res else "Search is Un-successful"
print(result)

#Program for swapping of two numbers by using XOR


#swap.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*40)
print("Original Value of a:{}".format(a))
print("Original Value of b:{}".format(b))
#swapping logic
a=a^b
b=a^b

82
a=a^b
print("-"*40)
print("Swapped Value of a:{}".format(a))
print("Swapped Value of b:{}".format(b))
print("-"*40)

============================================
7. Identity Operators
============================================
=>The purpose of Identity Operators is that " To Compare the Memory
Address of Two objects".
=>We have two types of Identity Operators. They are
1) is
2) is not

1) is

Syntax: Object1 is Object2


=>"is" operator returns True provided "Object1" and "Object2" contains
Same memory
Address
=>"is" operator returns False provided "Object1" and "Object2" contains
Different memory
Address

-
2) is not

Syntax: Object1 is not Object2


=>"is not " operator returns True provided "Object1" and "Object2"
contains Different memory Address
=>"is not " operator returns False provided "Object1" and "Object2"
Same memory
Address

Examples:

>>> a=None
>>> b=None
>>> print(a,type(a),id(a))
None <class 'NoneType'> 140720057120760
>>> print(b,type(b),id(b))
None <class 'NoneType'> 140720057120760
>>> a is b
True
>>> a is not b
False

>>> d1={10:"Apple",20:"Mango"}
>>> d2={10:"Apple",20:"Mango"}
>>> print(d1,type(d1), id(d1))
{10: 'Apple', 20: 'Mango'} <class 'dict'> 1974138484864

83
>>> print(d2,type(d2), id(d2))
{10: 'Apple', 20: 'Mango'} <class 'dict'> 1974138484992
>>> d1 is d2
False
>>> d1 is not d2
True

>>> s1={10,20,30}
>>> s2={10,20,30}
>>> print(s1,type(s1),id(s1))
{10, 20, 30} <class 'set'> 1974142731648
>>> print(s2,type(s2),id(s2))
{10, 20, 30} <class 'set'> 1974142732096
>>> s1 is s2
False
>>> s1 is not s2
True
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1,type(fs1),id(fs1))
frozenset({10, 20, 30}) <class 'frozenset'> 1974142732320
>>> print(fs2,type(fs2),id(fs2))
frozenset({10, 20, 30}) <class 'frozenset'> 1974142733664
>>> fs1 is fs2
False
>>> fs1 is not fs2
True

>>> l1=[10,"Rossum"]
>>> l2=[10,"Rossum"]
>>> print(l1,type(l1),id(l1))
[10, 'Rossum'] <class 'list'> 1974139251520
>>> print(l2,type(l2),id(l2))
[10, 'Rossum'] <class 'list'> 1974139251456
>>> l1 is l2
False
>>> l1 is not l2
True
>>> t1=(10,20,"Python")
>>> t2=(10,20,"Python")
>>> print(t1,type(t1),id(t1))
(10, 20, 'Python') <class 'tuple'> 1974139158336
>>> print(t2,type(t2),id(t2))
(10, 20, 'Python') <class 'tuple'> 1974139073920
>>> t1 is t2
False
>>> t1 is not t2
True

>>> s1="INDIA"
>>> s2="INDIA"
>>> print(s1,type(s1),id(s1))
INDIA <class 'str'> 1974142763632
>>> print(s2,type(s2),id(s2))
INDIA <class 'str'> 1974142763632

84
>>> s1 is s2
True
>>> s1 is not s2
False
>>> s1="PYTHON"
>>> s2="PYTHOn"
>>> print(s1,type(s1),id(s1))
PYTHON <class 'str'> 1974139253168
>>> print(s2,type(s2),id(s2))
PYTHOn <class 'str'> 1974142763184
>>> s1 is s2
False
>>> s1 is not s2
True

>>> b1=bytes([10,20,30])
>>> b2=bytes([10,20,30])
>>> print(b1,type(b1),id(b1)) b'\n\x14\
x1e' <class 'bytes'> 1974138659936
>>> print(b2,type(b2),id(b2)) b'\n\x14\
x1e' <class 'bytes'> 1974138662432
>>> b1 is b2
False
>>> b1 is not b2
True
>>> ba1=bytearray((10,20,30))
>>> ba2=bytearray((10,20,30))
>>> print(ba1,type(ba1),id(ba1))
bytearray(b'\n\x14\x1e') <class 'bytearray'> 1974142763760
>>> print(ba2,type(ba2),id(ba2))
bytearray(b'\n\x14\x1e') <class 'bytearray'> 1974142763952
>>> ba1 is ba2
False
>>> ba1 is not ba2
True
>>> r1=range(10,21)
>>> r2=range(10,21)
>>> print(r1,type(r1),id(r1))
range(10, 21) <class 'range'> 1974138662528
>>> print(r2,type(r2),id(r2))
range(10, 21) <class 'range'> 1974138660224
>>> r1 is r2
False
>>> r1 is not r2
True
>>>

>>> a=2+3j
>>> b=2+3j
>>> print(a,id(a))
(2+3j) 1842747529136
>>> print(b,id(b))
(2+3j) 1842747532624
>>> a is b
False
>>> a is not b

85
True

>>> a=True
>>> b=True
>>> print(a,id(a))
True 140707876940648
>>> print(b,id(b))
True 140707876940648
>>> a is b
True
>>> a is not b
False
>>> c=False
>>> print(c,id(c))
False 140707876940680
>>> a is c
False
>>> a is not c
True

>>> a=1.2
>>> b=1.2
>>> print(a,id(a))
1.2 1842747529424
>>> print(b,id(b))
1.2 1842747529136
>>> a is b
False
>>> a is not b
True

>>> a=0
>>> b=0
>>> print(a,id(a))
0 1842746491088
>>> print(b,id(b)) # 0 to 256-----same Address
0 1842746491088
>>> a is b
True
>>> a is not b
False
>>> a=10
>>> b=10
>>> print(a,id(a))
10 1842746491408
>>> print(b,id(b)) # 0 to 256-----same Address
10 1842746491408
>>> a is b
True
>>> a is not b
False
>>> a=256
>>> b=256
>>> print(a,id(a))
256 1842746499280

86
>>> print(b,id(b)) # 0 to 256-----same Address
256 1842746499280
>>> a is b
True
>>> a is not b
False

>>> a=257
>>> b=257
>>> print(a,id(a))
257 1842747532624
>>> print(b,id(b)) # 0 to 256 same address and after-Different Address
257 1842747529296
>>> a is b
False
>>> a is not b
True

>>> a=-1
>>> b=-1
>>> print(a,id(a))
-1 1842746491056
>>> print(b,id(b))# from -1 to -5 contains same address
-1 1842746491056
>>> a is b
True
>>> a is not b
False
>>> a=-5
>>> b=-5
>>> print(a,id(a))
-5 1842746490928
>>> print(b,id(b))# from -1 to -5 contains same address
-5 1842746490928
>>> a is b
True
>>> a is not b
False
>>> a=-12
>>> b=-12
>>> print(a,id(a))
-12 1842746506384
>>> print(b,id(b))# from -1 to -5 contains same address and leter
contains different address
-12 1842747532624
>>> a is b
False
>>> a is not b
True
==========================X============================================
======

87
==========================================
String Handling in Python(part-2)
==========================================
=>We know that a String is a collection / sequence of Characters
enclosed within single / double Quotes (or) triple single / double
Quotes.
=>String data is of type <class,'str'>
=>To do various opereations on String data, we have to use the
following the functions.

1) capitalize():

=>This function is used for capitalizing the given str data


=>Syntax: varname=strobj.capitalize()

Examples:

>>> s="python is an oop lang"


>>> print(s,type(s))---------python is an oop lang <class 'str'>
>>> cs=s.capitalize()
>>> print(cs,type(cs))---- Python is an oop lang <class 'str'>
>>> print(s,type(s))---- python is an oop lang <class 'str'>

2) title():

=>This Function is used for getting all words First Characters as


capital.
=>Syntax:- varname=strobj.title()
Examples:

>>> s="python is an oop lang"


>>> ts=s.title()
>>> print(ts,type(ts))--------Python Is An Oop Lang <class 'str'>
>>> print(s,type(s))-----python is an oop lang <class 'str'>

3) find():

=>This function is used for finding an index of the first occurance of


specified str data in the given str data.
=>If the data found then it returns Its +ve index value
=>If the data not found then it returns -1

Syntax:- varname=strobj.find(str data)

Examples:

>>> s="python is an oop lang"

88
>>> print(s,type(s))
python is an oop lang <class 'str'>
>>> ind=s.find("python")
>>> print(ind)------0
>>> ind=s.find("n")
>>> print(ind)------5
>>> ind=s.find("k")
>>> print(ind)-------------1
>>> ind=s.find("o")
>>> print(ind)-------4
Examples:

for let in s:
ind=s.find(let)
print(ind)

Examples:

#Indexex.py
line=input("Enter a line of text:")
print("Given Data={}".format(line))
for ch in line:
print("\tCharacter: {} Index={}".format(ch,line.find(ch)))

#indexex.pt
line=input("Enter line of text:") # Python
i=0
for ch in line:
print("Character :{}--->Index:{} and orginal Index={}".format(
ch, line.index(ch),i ))
i=i+1

4) isalnum():

=>This Function returns True Provided str data contains "Alphabets with
digits or only with digits or only with alphabets"
=>This Function returns False Provided str data is a combination of
"Alphabets and numbers with any special Symbols"

Syntax:- varname=strobj.isalnum()
(or)
strobj.isalnum()

Examples:

>>> s="12345"
>>> b=s.isalnum()
>>> print(b)------------True
>>> s="python12345"
>>> s.isalnum()----------True
>>> s="python12345#"
>>> s.isalnum()---------False
>>> s="python 12345"
>>> s.isalnum()----------False
>>> s="Python is an oop lang"

89
>>> s.isalnum()-----------False
>>> s="python"
>>> s.isalnum()--------True
>>>s="-123"
>>> s.isalnum()-----------False

5) isalpha():

=>This Function returns True provided str data contains only


Alphabets otherwise it returns False.

=>Syntax:- varname=strobj.isalpha()

Examples:

>>> s="Python"
>>> b=s.isalpha()
>>> print(b)------------True
>>> s="1234"
>>> print(s.isalpha())--------False
>>> s="python1234"
>>> print(s.isalpha())-------False
>>> s="python_1234"
>>> print(s.isalpha())-------False

6) isdigit():

=>This Function returns True provided str data contains only purly
digits(0-9) otherwise it returns False.
Syntax:- varname=strobj.isdigit()
or
strobj.isdigit()
Examples:

>>> a="1234"
>>> print(a.isdigit())------------True
>>> a="pyth1234"
>>> print(a.isdigit())--------False
>>> a="python"
>>> print(a.isdigit())------False
>>> a="pyth#$123"
>>> print(a.isdigit())---------False

7) islower() :

=>This Function returns True provided the str data is completely


available in lowercase otherwise it returns False.

Syntax:- varname=strobj.islower()
or
strobj.islower()
Examples:

90
>>> s="python"
>>> print(s.islower())----------True
>>> s="Python"
>>> print(s.islower())---------False
>>> s="python is an oop lang"
>>> print(s.islower())----True
>>> s="python is An oop lang"
>>> print(s.islower())-------False
8) isupper() :

=>This Function returns True provided the str data is completely


available in upper case otherwise it returns False.

Syntax:- varname=strobj.isupper()
or
strobj.isupper()

Examples:

>>> s="Python"
>>> print(s.isupper())----------False
>>> s="PYTHON"
>>> print(s.isupper())-------True
>>> s="python is an oop lang"
>>> print(s.isupper())---------False
>>> s="PYTHON IS AN OOP LANG"
>>> print(s.isupper())-------True

9) isspace()

=>This Function returns True provided str data contains purely space(s)
otherwise it returns False.
=>Syntax:- varname=strobj.issapce()
(or)
strobj.isapce()

Examples:

>>> s="Python is an oop"


>>> print(s.isspace())--------False
>>> s=" "
>>> print(s.isspace())--------True
>>> s=" "
>>> print(s.isspace())--------True
>>> s="123 345"
>>> print(s.isspace())---False
>>> s="" # empty string
>>> s.isspace()-----------False

10) upper():

=>This Function is used for converting lower case data into upper case
data.
Syntax:- varname=strobj.upper()

11) lower():

91
=>This Function is used for converting upper case data into lower case
data.
Syntax:- varname=strobj.lower()

Examples:

>>> s="python is an oop lang"


>>> uc=s.upper()
>>> print(uc)-------PYTHON IS AN OOP LANG
>>> print(s)-------python is an oop lang
>>> print(uc)---- PYTHON IS AN OOP LANG
>>> lc=uc.lower()
>>> print(lc)-------- python is an oop lang

12) join():

=>This Function is used concatinating all the sequence of values which


are available in the form str
Syntax:- varname=strobj1.join(iterable obj)
=>Here iterable obj contains multiple values in the form of str
Examples-:

>>>tpl=('java', 'python', 'Data Science')


>>> print(tpl, type(tpl))--('java', 'python', 'Data Science') <class
'tuple'>
>>> s2=""
>>> s3=s2.join(tpl)
>>> print(s3)---->javapythonData Science

>>> lst=["Apple","Mango","Kiwi","Guava"]
>>> frs=""
>>> frs=frs.join(lst)
>>> print(frs)-------------------AppleMangoKiwiGuava
>>> lst=["Apple","Mango","Kiwi","Guava"]
>>> frs=" "
>>> frs=frs.join(lst)
>>> print(frs)--------------Apple Mango Kiwi Guava

13) split():

=>This function is used for splitting the given str data into different
tokens based spitting value. The default splitting value is space
=>This Function returns splitting values in the form of list.

Syntax:- listobj=strobj.split()

listobj=strobj.split("spliting value")
Examples:

>>> s="Python is an oop lang"


>>> s.split()--------- ['Python', 'is', 'an', 'oop', 'lang']
>>> s="9-11-2021"
>>> l=s.split("-")
>>> print(l)----------['9', '11', '2021']
>>> s="apple#kiwi#guava-banana"

92
>>> l=s.split("#")
>>> print(l)----------['apple', 'kiwi', 'guava-banana']
>>> l[2].split("-")--------['guava', 'banana']
============================X====================================

============================================
Flow Control Statements in Python
(OR)
Control Structures in Python
============================================
Index

=>Purpose of Flow Control Statements in Python


=>Types of Flow Control Statements in Python
I ) Conditional or Branching or Selection Statements
a) Simple if Statements
b) if..else statement
c) if..elif..else statement
d) match case statement ( Python 3.10 Version
newly added)
=>Programming Examples
II) Looping or Iterative or Repetative Statements
a) while loop or while .. else loop
b) for loop or for...else loop
=>Programming Examples
III) Misc. Flow Control Statements in Python
(Transfer Control Statements in Python)
a) break
b) continue
c) pass
=>Programming Examples
=>Nested ot Inner Loops
=>=>Programming Examples

============================================
Flow Control Statements in Python
(OR)
Control Structures in Python ===
=>The Purpose of Flow Control Statements in Python is that " To perform
Ceratin Operation only once depends on Condition Evalution (True Or
False) or perform Ceratin Operation repeatedly for finite number of
times until Condition becomes False. "
=>In Python Programming, Flow Control Statements are classified into 3
types

I ) Conditional or Branching or Selection Statements


II ) Looping or Iterative or Repetative Statements
III) Misc. Flow Control Statements in Python
(Transfer Control Statements in Python)

93
=====================================================
I ) Conditional or Branching or Selection Statements
=====================================================
=>The purpose of Conditional or Branching or Selection Statements is
that "To perform Certain Operation (Say X -Operation when the condition
is true OR Y-Operation When the condition is False) depends on
Condition Evaluation ".
=>In Python Conditional or Branching or Selection Statements are
classified into 4 types. They are
a) Simple if Statements
b) if..else statement
c) if..elif..else statement
d) match case statement ( Python 3.10 Version
newly added)

Program
tkt=input("Do u have Ticket(yes/no):")
if(tkt.lower()=="yes"):
print("Enter into threater")
print("Watch Moviee")
print("Enjoy!")
print("\nGoto Home and read python notes")
print("Program exeuction completed")

94
program
#Program accepting two integer values and find big along with equality
#bigex1.py
a=int(input("Enter Value of a:")) # a=100
b=int(input("Enter Value of b:"))# b=10
if (a==b) :
print("Both the Values are equal")
if(a>b):
print("Big={}".format(a))
if(b>a):
print("Big={}".format(b))

program
#Program for accepting an integer value decide +ve or -ve or 0
#posnegzeroex1.py
n=int(input("Enter a number:")) # n= -123
if n>0:
print("{} is +Ve".format(n))
if n<0:
print("{} is -Ve".format(n))
if n==0:
print("{} is Zero".format(n))
print("Program execution completed")

2.if…elif..statement

95
==========================================
match .. case statement (Python 3.10)
==========================================
=>It is one of new Feature in Python 3.10
=>This features is also known as Multi way decision making statement.
=>Syntax:

match Choice Expression:

96
case label1:
block of statements-I
case label2:
block of statements-II

case label-n:
block of statements-n
case _ : # default case block
default block of statements

Other statements in Program

Explanation:

1) here 'match' and 'case' are the keywords


2) here 'expression' can be any data type value except float.
3) here the value of choice expression is comparing with case label1 .
If it is True then execute Block of statements-I and also execute other
statements in Program. Choice expression is not matching with case
label1 then it compares with case label2 and it it matches then execute
Block of statements-II and also execute other statements in Program and
so on.
4) In general if the value of choice expression is matching with any
case label then PVM executes corresponding block of statements and also
executes Other statements in the program.
5)if value of choice expression is not matching with any case labels
then PVM executes block of statements written under default case block
and also executes Other statements in the program.
6) Writting default case label is optional.

program
#Program accepting 3 values from KBD and find biggest among them
#bigex2.py
a=int(input("Enter First Value:"))# a=10
b=int(input("Enter Second Value:")) # b=30
c=int(input("Enter Third Value:"))#=c=200
if(a==b) and (b==c) :
print("ALL VALUES ARE EQUAL")
else:
if(a>b) and (a>c):
print("big({},{},{})={}".format(a,b,c, a))
else:
if(b>a) and (b>c):
print("big({},{},{})={}".format(a,b,c, b))
else:
print("big({},{},{})={}".format(a,b,c,c))

program
#Program accepting 3 values from KBD and find biggest among them
#bigex3.py
a=int(input("Enter First Value:"))# a=10
b=int(input("Enter Second Value:")) # b=30

97
c=int(input("Enter Third Value:"))#=c=200
if(a==b) and (b==c) :
print("ALL VALUES ARE EQUAL")
elif(a>b) and (a>c):
print("big({},{},{})={}".format(a,b,c, a))
elif(b>a) and (b>c):
print("big({},{},{})={}".format(a,b,c, b))
elif(c>a) and (c>b):
print("big({},{},{})={}".format(a,b,c,c)

Program

#digitex1.py
d=int(input("Enter a digit:")) # d=1
if(d==0):
print("{} is ZERO".format(d))
elif(d==1):
print("{} is ONE".format(d))
elif(d==2):
print("{} is TWO".format(d))
elif(d==3):
print("{} is THREE".format(d))
elif(d==4):
print("{} is FOUR".format(d))
elif(d==6):
print("{} is SIX".format(d))
elif(d==7):
print("{} is SEVEN".format(d))
elif(d==5):
print("{} is FIVE".format(d))
elif(d==8):
print("{} is EIGHT".format(d))
elif(d==9):
print("{} is NINE".format(d))
elif(d==-1):
print("{} is ONE".format(d))
elif(d==-2):
print("{} is TWO".format(d))
elif(d==-3):
print("{} is THREE".format(d))
elif(d==-4):
print("{} is FOUR".format(d))
elif(d==-6):

98
print("{} is SIX".format(d))
elif(d==-7):
print("{} is SEVEN".format(d))
elif(d==-5):
print("{} is FIVE".format(d))
elif(d==-8):
print("{} is EIGHT".format(d))
elif(d==-9):
print("{} is NINE".format(d))
else:
print("{} is a Number:".format(d))

Program

#PaySlip.py
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
basicsal=float(input("Enter Employee Basic Salary:"))
if(basicsal<=0):
print("\tInvalid Salary, plz enter +ve Sal:")
else:
if(basicsal>=10000):
ta=basicsal*(10/100)
da=basicsal*(20/100)
hra=basicsal*(15/100)
cca=basicsal*(2/100)
gpf=basicsal*(2/100)
lic=basicsal*(2/100)
else:
ta=basicsal*(15/100)
da=basicsal*(25/100)
hra=basicsal*(20/100)
cca=basicsal*(3/100)
gpf=basicsal*(1/100)
lic=basicsal*(1/100)
#calculate netsal
netsal=(basicsal+ta+da+hra+cca)-(gpf+lic)
#display employee pay slip
print("-"*50)
print("\tE m p l o y e e P a y S l i p ")
print("-"*50)
print("\tEmployee Number:{}".format(eno)) print("\
tEmployee Name:{}".format(ename)) print("\tEmployee
Basic Salary:{}".format(basicsal)) print("\tEmployee
TA:{}".format(ta))

99
print("\tEmployee DA:{}".format(da))
print("\tEmployee HRA:{}".format(hra))
print("\tEmployee CCA:{}".format(cca))
print("\tEmployee GPF:{}".format(gpf))
print("\tEmployee LIC:{}".format(lic))
print("-"*50)
print("\tEmployee Net Salary={}".format(netsal))
print("-"*50)

==========================================
match .. case statement (Python 3.10)
==========================================
=>It is one of new Feature in Python 3.10
=>This features is also known as Multi way decision making statement.
=>Syntax:

match Choice Expression:


case label1:
block of statements-I
case label2:
block of statements-II

case label-n:
block of statements-n
case _ : # default case block
default block of statements

Other statements in Program

100
Explanation:

1) here 'match' and 'case' are the keywords


2) here 'expression' can be any data type value except float.
3) here the value of choice expression is comparing with case label1 .
If it is True then execute Block of statements-I and also execute other
statements in Program. Choice expression is not matching with case
label1 then it compares with case label2 and if it matches then execute
Block of statements-II and also execute other statements in Program and
so on.
4) In general if the value of choice expression is matching with any
case label then PVM executes corresponding block of statements and also
executes Other statements in the program.
5)if value of choice expression is not matching with any case labels
then PVM executes block of statements written under default case block
and also executes Other statements in the program.
6) Writting default case label is optional.

=======================================================================

#program implementing Arityhmetic Operations by using Menu Driven


Approach.
#matchcaseex1.py
print("="*50)
print("\tA r i t h m e t i c O p e r a t i o n")
print("="*50)
print("\t1.Addition")
print("\t2. Substraction")
print("\t3. Multiplication")
print("\t4. Division")
print("\t5. Modulo Division")
print("\t6.Exponentiation")
print("\t7. Exit")
print("="*50)
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
a=float(input("Enter First Value for Addition:"))
b=float(input("Enter Second Value for Addition:"))
print("sum({},{})={}".format(a,b,a+b))
case 2:
a=float(input("Enter First Value for Substract:"))
b=float(input("Enter Second Value for Substract:"))
print("sub({},{})={}".format(a,b,a-b))
case 3:
a=float(input("Enter First Value for Multiplication:"))
b=float(input("Enter Second Value for Multiplication:"))
print("Mul({},{})={}".format(a,b,a*b))
case 4:
a=float(input("Enter First Value for Division:"))
b=float(input("Enter Second Value for Division:"))
print("Div({},{})={}".format(a,b,a/b))
print("Floor Div({},{})={}".format(a,b,a//b))
case 5:
a=float(input("Enter First Value for Modulo Division:"))
b=float(input("Enter Second Value Modulo for Division:"))
print("mod({},{})={}".format(a,b,a%b))

101
case 6:
a=float(input("Enter Base:"))
b=float(input("Enter Power:")) print("pow({},
{})={}".format(a,b,a**b))
case 7:
exit() # It is used Terminating the program execution
without executing rest of the
#statements in program
case _:
print("Ur Choice of Operation is invalid-try again:")
#program implementing Area of Different Fig by using Menu Driven
Approach.
#matchcaseex2.py
print("="*50) print("\
tArea of Figures")
print("="*50) print("\
tC.Circle") print("\
tR.Rectangle") print("\
tS.Square") print("\
tT.Triangle") print("\
tE.Exit") print("="*50)
ch=input("Enter Ur Choice:")
match(ch.upper()):
case "C":
r=float(input("Enter Radious:"))
ac=3.14*r**2
print("Area of Circle={}".format(ac))
case "S":
s=float(input("Enter Side:"))
sa=s**2
print("Area of Square={}".format(sa))
case "R":
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
ar=l*b
print("Area of Rectangle={}".format(ar))
case "T":
a=float(input("Enter Value of Side1 :"))
b=float(input("Enter Value of Side2 :"))
c=float(input("Enter Value of Side3 :"))
s=(a+b+c)/2
at=(s*(s-a)*(s-b)*(s-c)) **0.5
print("Area of Triangle={}".format(at))
case "E":
exit() # It is used Terminating the program execution
without executing rest of the
#statements in program
case _:
print("Ur Choice of Operation is invalid-try again:")

102
#program implementing Area of Different Fig by using Menu Driven
Approach.
#matchcaseex3.py
print("="*50) print("\
tArea of Figures")
print("="*50) print("\
tC.Circle") print("\
tR.Rectangle") print("\
tS.Square") print("\
tT.Triangle") print("\
tE.Exit") print("="*50)
ch=input("Enter Ur Choice:")
match(ch):
case "C" | "c":
r=float(input("Enter Radious:"))
ac=3.14*r**2
print("Area of Circle={}".format(ac))
case "S"| "s":
s=float(input("Enter Side:"))
sa=s**2
print("Area of Square={}".format(sa))
case "R" | "r":
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
ar=l*b
print("Area of Rectangle={}".format(ar))
case "T" | "t":
a=float(input("Enter Value of Side1 :"))
b=float(input("Enter Value of Side2 :"))
c=float(input("Enter Value of Side3 :"))
s=(a+b+c)/2
at=(s*(s-a)*(s-b)*(s-c)) **0.5
print("Area of Triangle={}".format(at))
case "E" | "e":
exit() # It is used Terminating the program execution
without executing rest of the
#statements in program
case _:
print("Ur Choice of Operation is invalid-try again:")

#matchcaseex4.py
wd=input("Enter the week Name:")
match(wd.upper()):
case "MONDAY":
print("{} is Working Day:".format(wd))

103
case "TUESDAY":
print("{} is Working Day:".format(wd))
case "WEDNESDAY":
print("{} is Working Day:".format(wd))
case "THURSDAY":
print("{} is Working Day:".format(wd))
case "FRIDAY":
print("{} is Working Day:".format(wd))
case "SATURDAY":
print("{} is Week End:".format(wd))
case "SUNDAY":
print("{} is HolyDay:".format(wd))
case _:
print("{} is not a week Day:".format(wd))

#matchcaseex5.py
wd=input("Enter the week Name:")
match(wd.upper()):
case "MONDAY"| "TUESDAY" | "WEDNESDAY" | "THURSDAY" | "FRIDAY":
print("{} is Working Day:".format(wd))
case "SATURDAY":
print("{} is Week End:".format(wd))
case "SUNDAY":
print("{} is HolyDay:".format(wd))
case _:
print("{} is not a week Day:".format(wd))

======================================================
II ) Looping or Iterative or Repetative Statements
======================================================
=>The purpose of Looping or Iterative or Repetative Statements in is
that " To perform Certain
Operations repeatedly for finite number of times until Condition
Becomes False".
=>In Python Programming, we have 2 types of Looping Statements. They
are

1. while loop (or) while ... else loop

2. for loop (or) for ... else loop

=>When we dealing looping level program, we must ensure there must


exist 3 points.
a) Initlization Part ( From where u start )
b) Condition Part ( Where u stop )
c) Updation Part ( Move Forward or Backword to
meet the condition)

104
==========================================
for loop or for else concept
==========================================
Syntax1:

for varname in Iterable_object:

statement-1
statement-2

statement-n

Execute Other statements in program

======================================================

Syntax2:

for varname in Iterable_object:

statement-1
statement-2

statement-n
else:
else block of statements

Execute Other statements in program

Explanation:

=>here 'for' and 'else' are the keywords


=>An Interable object is one which contains multiple elements
(sequence,list,set and dict).
=>The execution process of for loop is that "Each Value of Iterabale
object taken by PVM and Place it into Varname and executes Indentation
Block of statements (statement-1,statement-2,...statement-n). This
process will continue Iteratively until all elements of Iterable object
completed. In otherwords, for loop execute Iteratively until
len(Iterable object) reached ".
=>Once for loop completed its execution then PVM will execute else
block of statements (if we write else block) and later execute other
statements in program.
=>Writing else block of statements is optional.

===============================================================

105
#program generates 1 to n where is n is +ve
n=int(input("Enter a number:")) # n=10
if(n<=0):
print("{} is Invalid Input".format(n))
else:
#logic for generating 1 to n
i=1 # Initlization part
while(i<=n): # Cond Part
print("\t{}".format(i),end="")
i=i+1 # Updation part

106
#program generates 1 to n where is n is +ve
n=int(input("Enter a number:")) # n=10
if(n<=0):
print("{} is Invalid Input".format(n))
else:
#logic for generating 1 to n
print("="*40)
print("Numbers within:{}".format(n))
print("=" * 40)
i=1 # Initlization part
while(i<=n): # Cond Part
print("\t{}".format(i),end="")
i=i+1 # Updation part
else:
print()
print("-" * 40)

#Program for generating N to 1 where N is +ve


n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
i=n
while(i>=1):
print("\t{}".format(i),end=",")
i=i-1

#Program for generating Even Numbers within N


n=int(input("Enter a number:")) # 11
if(n<=0):
print("{} is invalid input".format(n))
else:
#logic for even numbers
print("*"*50)
print("Even Numbers within:{}".format(n))
print("*"*50)
i=2 # Init Part
while(i<=n):
print("\t{}".format(i), end="" )
i=i+2
else:
print()
print("="*50)

107
#Program for finding sum of i to n
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("="*50)
print("Sum of {} Numbers".format(n))
print("="*50)
s=0
i=1
while(i<=n):
print("\t{}".format(i))
s=s+i
i=i+1
else:
print("=" * 50)
print("Sum={}".format(s))
print("=" * 50)

=======================================
#program for generating even numbers within n
#evengenex.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("="*50)
print("Even Numbers within:{}".format(n)) # 10
print("="*50)
for i in range(2,n+1,2):
print("\t{}".format(i))
else:
print("="*50)

"""
E:\KVR-PYTHON-7AM\LOOPS>py evengenex.py
Enter a number:15
==================================================
Even Numbers within:15
==================================================
2
4
6
8
10
12
14
==================================================
"""

108
#program for finding sum,squares and cubes of N natural number where
N>0
#findnumssum.py
n=int(input("Enter a number:")) # n=5
if(n<=0):
print("{} is invalid input".format(n))
else:
s=0
ss=0
cs=0
print("="*50)
print("NatNumsSum\tSquares Sum\tCubes Sum:")
print("="*50)
for i in range(1,n+1):
print("\t{}\t\t{}\t\t{}".format(i,i**2,i**3))
s=s+i
ss=ss+i**2
cs=cs+i**3
else:
print("="*50) print("\t{}\t\t{}\t\
t{}".format(s,ss,cs)) print("="*50)

""""
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125

X Y Z
"""

#program for finding sum,squares and cubes of N natural number where


N>0
#findnumssum1.py
n=int(input("Enter a number:")) # n=5
if(n<=0):
print("{} is invalid input".format(n))
else:
s=0
ss=0
cs=0
print("="*50)
print("NatNumsSum\tSquares Sum\tCubes Sum:")
print("="*50)
i=1
while(i<=n):
print("\t{}\t\t{}\t\t{}".format(i,i**2,i**3))
s=s+i
ss=ss+i**2

109
cs=cs+i**3
i=i+1
else:
print("="*50) print("\t{}\t\t{}\t\
t{}".format(s,ss,cs)) print("="*50)

#program for demonstarting for loop execution


#forloopex1.py
s="PYTHON"
print(" ")
print("By Using While Loop")
print(" ")
i=0
while(i<len(s)):
print("\t{}".format(s[i]))
i=i+1
print(" ")
print("By Using for Loop")
print(" ")
for v in s:
print("\t{}".format(v))
print(" ")

#program for demonstarting for loop execution


#forloopex2.py
lst=[10,"Rossum",23.45,"Python",True]
print(" ")
print("By Using While Loop")
print(" ")
i=0
while(i<len(lst)):
print("\t{}".format(lst[i]),end=" ")
i=i+1
else:
print()
print(" ")
print("By Using for Loop")
print(" ")
for k in lst:
print("\t{}".format(k),end=" ")
else:
print()
print(" ")

#program for demonstarting for loop execution


#forloopex3py

110
tpl=(10,"Rossum",23.45,"Python",True)
print(" ")
print("By Using While Loop")
print(" ")
i=0
while(i<len(tpl)):
print("\t{}".format(tpl[i]),end=" ")
i=i+1
else:
print()
print(" ")
print("By Using for Loop")
print(" ")
for k in tpl:
print("\t{}".format(k),end=" ")
else:
print()
print(" ")

#program for demonstarting for loop execution


#forloopex3py
tpl=(10,"Rossum",23.45,"Python",True)
print(" ")
print("By Using While Loop")
print(" ")
i=0
while(i<len(tpl)):
print("\t{}".format(tpl[i]),end=" ")
i=i+1
else:
print()
print(" ")
print("By Using for Loop")
print(" ")
for k in tpl:
print("\t{}".format(k),end=" ")
else:
print()
print(" ")

#Program generating multable for given number


#MulTable.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*50)
print("Mul Table for {}".format(n))

111
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
else:
print("-"*50)

#program for generating odd numbers within n


#oddgenex.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("="*50)
print("Odd Numbers within:{}".format(n)) # 10
print("="*50)
for i in range(1,n+1,2):
print("\t{}".format(i))
else:
print("="*50)

"""E:\KVR-PYTHON-7AM\LOOPS>py oddgenex.py
Enter a number:15
==================================================
Odd Numbers within:15
==================================================
1
3
5
7
9
11
13
15
=================================================="""

05-05-2022
break statement

=>break is a key word


=>The purpose of break statement is that "To terminate the execution of
loop logically when certain condition is satisfied and PVM control
comes of corresponding loop and executes other statements in the
prtogram".
=>when break statement takes place inside for loop or while loop then
PVM will not corresponding else block but it executes other statements
in the program

=>Syntax:

112
for var in Iterable_object:

if (test cond):
break

=>Syntax:

while(Test Cond-1):

if (test cond-2):
break

============================X================================

Break program
#breakex1.py
s="PYTHON"
print(" ")
for ch in s:
print("\t\t{}".format(ch))
print(" ")
for ch in s:
if(ch=="H"):
break
else:
print("\t\t{}".format(ch))
else:
print("i am from else part of for loop")
print("Other stmts in program")

=========================================
#breakex2.py
lst=[10,20,30,40,50,60,70]
print(" ")
for val in lst:
if(val==50):
break
else:
print("\t\t{}".format(val))
else:
print(" ")
print("*"*50)

#primeex1.py
n=int(input("Enter a number:"))
if(n<=1):
print("{} is invalid input".format(n))
else:
hyd=False
for i in range(2,n):
if(n%i==0):
hyd=True
break

113
if(hyd==True):
print("{} is Not Prime".format(n))
else:
print("{} is Prime".format(n))

#primeex2.py
n=int(input("Enter a number:"))
if(n<=1):
print("{} is invalid input".format(n))
else:
result="Prime"
for i in range(2,n):
if(n%i==0):
result="NotPrime"
break
if(result=="Prime"):
print("{} is Prime".format(n))
else:
print("{} is not Prime".format(n))

#factors.py
n=int(input("Enter a number:")) # 9
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("Given Number:{}".format(n))
for i in range(1,(n//2)+1):
if(n%i==0):
print("Factor={}".format(i))

#perfect.py
n=int(input("Enter a number:")) # 9
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("Given Number:{}".format(n))
s=0
for i in range(1,(n//2)+1):
if(n%i==0):
print("Factor={}".format(i))
s=s+i
else:
if(s==n):
print("{} is perfect".format(n))
else:
print("{} is not perfect".format(n))

114
continue statement

=>continue is a keyword
=>continue statement is used for making the PVM to go to the top of the
loop without executing the following statements which are written after
continue statement for that current Iteration only.
=>continue statement to be used always inside of loops.
=>when we use continue statement else part of corresponding loop also
executes provided loop condition becomes false.

=>Syntax:-

for varname in Iterable-object:

if ( Test Cond):
continue
statement-1 # written after continue
stateemnt
statement-2
statement-n

=>Syntax:-

while (Test Cond):

if ( Test Cond):
continue
statement-1 # written after continue
stateemnt
statement-2
statement-n

===========================X==================================
#continueex1.py
s="PYTHON"
print(" ")
for ch in s:
print("\t\t{}".format(ch))
else:
print(" ")
print("=======================================")
#display PYTON without H
s="PYTHON"
for ch in s:
if (ch=="H"):
continue
else:
print("\t\t{}".format(ch))
else:
print(" ")

115
#continueex2.py---want to display PTHN
s="PYTHON"
print(" ")
for ch in s:
if(ch=="Y") or (ch=="O"):
continue
else:
print("\t\t{}".format(ch))
else:
print(" ")

#continueex3.py---want to display PON


s="PYTHON"
print(" ")
for ch in s:
if(ch=="Y") or (ch=="T") or(ch=="H"):
continue
else:
print("\t\t{}".format(ch))
else:
print(" ")

#continueex4.py
numlist=[10,-20,0,-25,23,-67,34,-67,-4,45]
pslist=list() # create an empty list
for val in numlist:
if(val<=0):
continue
pslist.append(val)
else:
print("Given List={}".format(numlist))
print("Possitive List={}".format(pslist))
print(" ")
nslist=[] # create an empty list
for val in numlist:
if(val>=0):
continue
nslist.append(val)
else:
print("Negative List={}".format(nslist))

================================================
Nested or Inner Loop

116
================================================
=>The process of defining one loop inside of another loop is called
Nested or Inner Loop.
=>The execution process of inner loops concept is that " For Value of
Outer Loop, Inner loop
repeated its execution for finite number of times"
=>Inner loops can be used in the following four ways.

Syntax1:

for varnam1 in IterableObj1: # outer for loop

for varname2 in IterableObj2: # inner


for loop

else:

else:

--

***********************************************************************
*************************************
Syntax2:

while (Test Cond1): # outer while loop

while(Test Cond2): # inner while loop

else:

else:

***********************************************************************
*************************************
Syntax3:

while (Test Cond1): # outer while loop

for varname2 in IterableObj2: # inner for


loop

else:

else:

117
***********************************************************************
**************************************
Syntax4:
for varnam1 in IterableObj1: # outer for loop

while(Test Cond2): # inner while loop

else:

else:

--
#innerloopsex1.py----->for loop in for loop
for i in range(1,6):
print("Value of i--outer for loop: {}".format(i))
print("-"*50)
for j in range(1,4):
print("\tValue of j--inner for loop: {}".format(j))
else:
print("\tI am out of inner for loop")
print("-"*50)
else:
print("\tI am out of outer for loop")
#innerloopsex2.py----->while loop in while loop
i=1 # outer while loop Initlization
while(i<=5): # Outer while loop cond part
print("Value of i--outer while loop: {}".format(i))
print("-"*50)
j=1 # Inner while loop Initlization
while(j<=3): # inner while loop cond part
print("\tValue of j--inner while loop: {}".format(j))
j=j+1 # inner while loop updation
else:
print("\tI am out of inner while loop")
print("-"*50)
i=i+1 # outer while loop updation
#innerloopsex3.py----->for loop in while loop
i=5
while(i>0): # outer while loop
print("Value of i--outer while loop: {}".format(i))
print("-"*50)
for j in range(1,4): # inner for loop
print("\tValue of j--inner for loop: {}".format(j))
print("\tI am out of inner for loop")
print("-"*50)
i=i-1
print("\tI am out of while for loop")

#innerloopsex4.py----->while loop in for loop


for i in range(5,0,-1): # outer for loop

118
print("Value of i--outer for loop: {}".format(i))
print("-"*50)
j=3
while(j>0): # inner while loop
print("\tValue of j--inner while loop: {}".format(j))
j=j-1
else:
print("\ti am out of inner while loop")
print("-"*50)
else:
print("\ti am out of outer for loop")

#Programming reading the values from KBD and place them in list and
also find sum and avg
#SumListEx1.py
lst=[10,20,30]
s=0
print("+"*50)
for val in lst:
print("\t{}".format(val))
s=s+val
else:
print("+"*50)
print("Sum={}".format(s))
print("Avg={}".format(s/len(lst)))
print("+"*50)

#Programming reading the values from KBD and place them in list and
also find sum and avg
#SumListEx2.py
n=int(input("Enter How many numbers u want to find sum and avg:")) #5
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=list() # creating an empty list for adding dynamic values
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("="*50)
print("Given List Elements:{}".format(lst))
print("="*50)
#Sum and Avg Logic
s=0
print("+"*50)
for val in lst:
print("\t{}".format(val))
s=s+val
else:
print("+"*50)
print("Sum={}".format(s))
print("Avg={}".format(s/n))
print("+"*50)

119
#Programming reading the values from KBD and place them in list and
also find sum and avg
#SumListEx3.py
print("Enter Number of values separated by space:")
lst=[float(val) for val in input().split()]
print("+"*50)
print("Given List Elements:{}".format(lst))
print("+"*50)
s=0
for val in lst:
print("\t{}".format(val))
s=s+val
else:
print("+"*50)
print("Sum={}".format(s))
print("Avg={}".format(s/len(lst)))
print("+"*50)

#Program for accepting age of Citizen and Decide whether the citizen
eligible to vote or not\
#voterex1.py
age=int(input("Enter the age of Citizen"))
if(age>=18):
print("{} years Citizen is eligible to Vote:".format(age))
else:
print("Citizen not eligible to Vote:".format(age))

#Program for accepting age of Citizen and Decide whether the citizen
eligible to vote or not
#voterex2.py
while(True):
age=int(input("Enter the age of Citizen:")) # age--- 44
if(age>=18) and (age<=100):
print("{} years Citizen is eligible to
Vote:".format(age))
break

#StudentMarksReport.py

120
#validation of student number
while(True):
sno=int(input("Enter Student Number(200-300):"))
if(sno>=200) and (sno<=300):
break
print("Plz Enter Correct Student Number between 200 and 300")
#accept name of the student and college
sname=input("Enter Student Name:")
cname=input("Enter Student College Name:")
#validation of C Marks
while(True):
cm=int(input("Enter Marks in C:"))
if(cm>=0) and(cm<=100):
break
print("Plz Enter C Marks within 0 to 100")

#validation of CPP Marks


while(True):
cppm=int(input("Enter Marks in CPP:"))
if(cppm>=0) and(cppm<=100):
break
print("Plz Enter CPP Marks within 0 to 100")
#validation of Python Marks
while(True):
python=int(input("Enter Marks in PYTHON:"))
if(python>=0) and(python<=100):
break
print("Plz Enter Python Marks within 0 to 100")

#cauculate total marks and percentage


totmarks=cm+cppm+python
percent=(totmarks/300)*100
#decide the grade CM=60 CPPM=80 python 40
if((cm<40) or (cppm<40) or (python<40)):
grade="FAIL"
else:
if (totmarks>=250) and (totmarks<=300):
grade="DISTINCTION"
elif (totmarks>=200) and (totmarks<=249):
grade="FIRST"
elif (totmarks>=150) and (totmarks<=199):
grade="SECOND"
else:
grade="THIRD"

#display student marks report


print("*"*50)
print("\tS t u d e n t M a r k s R e p o r t")
print("*"*50)
print("\tStudent Number:{}".format(sno)) print("\
tStudent Name:{}".format(sname)) print("\tStudent
College Name:{}".format(cname)) print("\tStudent
Marks in C: {}".format(cm)) print("\tStudent Marks in
C++: {}".format(cppm)) print("\tStudent Marks in
Python: {}".format(python)) print("-"*50)
print("\tStudent Total Marks: {}".format(totmarks)) print("\
tStudent Percentage of Marks: {}".format(percent))

121
print("\tStudent Grade: {}".format(grade))
print("*"*50)

09/05/2022

===============================================
Functions in python
===============================================
Index

=>Purpose of Functions
=>Definition of Function
=>Parts of Functions
=>Phases in Functions
=>Syntax for Defining Functions
=>Number of Approaches to define Functions
=>Programming Examples

=>Arguments and Parameters


=>Types of Arguments or Parameters
1) Possitional Arguments
2) Default Arguments
3) Keyword Arguments
4) Variable Length Arguments
5) Keyword Variable Length Arguments
=>Local Vriables and Global Variables
=>global key word and globals()
=>Programming Examples

=>Anonymous Function or Lambda Functions


=>Programming Examples
=>Special Functions in Python
1) filter() with Normal and Anonymous Functions
2) map() with Functions and Anonymous Functions
3) reduce() with Functions and Anonymous Functions
=>Programming Examples
================================X==================================

===============================================
Types of Languages in the context of Functions
===============================================

=>In the context of Functions, we have two types of Programming


Languages. They are
1. Un-Structured Programming Languages.
2. Structured Programming Languages.

1. Un-Structured Programming Languages.:

122
=>In Un-Structured Programming Languages, there is no concept of
Functions.
=>Hence Re-using the common code is not possible in Un-Structured
Programming Languages and It has the following Limitations.
a) Application Development Time is More
b) Application Memory space is More
c) Application Execution Time is More
d) Application Performnace is reduced.
e) Redundency of the code is More
Examples:- GW-BASIC

2. Structured Programming Languages.:

=>In Structured Programming Languages, there is a concept of


Functions.
=>Hence the advantages of Structured Programming Languages are
a) Application Development Time is Less
b) Application Memory space is Less
c) Application Execution Time is Less
d) Application Performnace is Enhanced (Improved)
e) Redundency of the code is Minimized.

Examples:- C,CPP,PYTHON,JAVA,.NET...etc

===============================================
Functions in python
===============================================
=>The purpose of Functions concept is that "To perform an Operation and
Provides Code
Re-usability".

=>Definition of Function:

=>A part of main program is called Function


OR
=>A Sub Program of main program is called Function.

Parts of Functions:

=>At the time dealing with Functions, There must exists two aprts. They
are
1. Function Definition
2. Function Call
=>In Python Programming, a perticular Function Definition Exists only
once.
=>For Every Function Definition, there must exists one or more function
calls.

123
=>In Otherw ords, For Every Function call, There must exists Function
Definition otherwise
we get NameError.
=>Function Definition will be executed through Function Call only but
not by itself.

10/may/2022

124
#Defining a Function for calculating addition of two numbers.
#addopex1.py
def addop( a,b): # Here 'a' and 'b' are callled formal Parameters
print("i am from addop()")
c=a+b # Here 'c' is called local variable
return c

#main program
result=addop(10,20) # Function Call
print("Sum=",result)
result=addop(100,200) # Function Call
print("Sum=",result)
result=addop(-10,-20) # Function Call
print("Sum=",result)
#print(a,b,c)---------error bocz a,b are called formal params and c is
called local variable and they can't access outside of the Function.

#Defining a Function for calculating addition of two numbers.


#addopex1.py
def addop( a,b): # Here 'a' and 'b' are callled formal Parameters
print("i am from addop()")
c=a+b # Here 'c' is called local variable
return c

#main program
result=addop(10,20) # Function Call
print("Sum=",result)
result=addop(100,200) # Function Call
print("Sum=",result)
result=addop(-10,-20) # Function Call
print("Sum=",result)
#print(a,b,c)---------error bocz a,b are called formal params and c is
called local variable and they can't access outside of the Function.

125
===============================================================
#Defining a Function for calculating addition of two numbers.
#Approach2.py
# INPUT: Function Body
#PROCESS: Function Body
#RESULT: Function Body
def addop():
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:")) # here 'a' and 'b' are
called local variables
c=a+b # Here 'c' is local variable
print("sum({},{})={}".format(a,b,c))

#main program
addop() # Function call

#Defining a Function for calculating addition of two numbers.


#Approach3.py
# INPUT: Function Body
#PROCESS: Function Body
#RESULT: Function Call

def addop():
p=float(input("Enter First Value:"))
q=float(input("Enter Second Value:"))
r=p+q
return p,q,r # In Python, a retrurn statement can return one or
more number of values.

#main program
a,b,result=addop() # A Function call with multi line assigment
print("Sum({},{})={}".format(a,b,result))
print("==============================")
res=addop() # A Function call with single line assigment
# here res is an object of type
<class,tuple> print("sum({},
{})={}".format(res[0],res[1],res[2]))

#Defining a Function for calculating addition of two numbers.


#Approach4.py
# INPUT: Function Call
#PROCESS: Function Body
#RESULT: Function Body

def addop(k,v):
r=k+v
print("sum({},{})={}".format(k,v,r))

126
#main program
p=float(input("Enter First Value:"))
q=float(input("Enter Second Value:"))
addop(p,q)

===============================================
Functions in python
===============================================
=>The purpose of Functions concept is that "To perform an Operation and
Provides Code
Re-usability".

=>Definition of Function:

=>A part of main program is called Function


OR
=>A Sub Program of main program is called Function.

Parts of Functions:

=>At the time dealing with Functions, There must exists two parts. They
are
1. Function Definition
2. Function Call
=>In Python Programming, a perticular Function Definition Exists only
once.
=>For Every Function Definition, there must exists one or more function
calls.
=>In Otherwords, For Every Function call, There must exists Function
Definition otherwise
we get NameError.
=>Function Definition will be executed through Function Call only but
not by itself.

Phases in Function Definition:

=>When we define a Function Definition, we must ensure that there must


three phases. They are
1. Every Function Must take an INPUT
2. Every Function Must PROCESS the input
3. Evert Function Must give RESULT / OUTPUT.

=======================================================================

# This program displays the content of Collection objects


#collection.py
def disp(obj): # Function Definition

127
print("-"*50)
print("Type of obj=",type(obj))
for val in obj:
print("\t{}".format(val))
print("-"*50)

def show(obj): # Function Definition


print("-"*50)
print("Type of obj=",type(obj))
for k,v in obj.items():
print("\t{}--->{}".format(k,v))
print("-"*50)

#main program
lst=[10,20,30,40,10,20,30,60,70]
disp(lst) # Function Call
tpl=(10,"Rossum","python",34.56,True)
disp(tpl) # Function Call
st1={10,20,30,10,20,50,60}
disp(st1) # Function Call
d={10:"Python",20:"Django",30:"Data Sci",40:"ML",50:"DL"}
show(d) # Function Call

#Program for accepting list of values and find sum and average
#listsumavg.py
def readvalues():
n=int(input("Enter how many number sum and avg want to find:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=[] # creater an empty list
for i in range(1,n+1):
val=int(input("Enter {} Value:".format(i)))
lst.append(val)
return lst

def findsumavg(obj):
if(obj!=None):
s=0
for val in obj:
print("\t{}".format(val))
s=s+val
else:
print("Sum={}".format(s))
print("Average={}".format(s/len(obj)))

else: # in the case of None


print("\nWe don't have any values and can't find sum and
average")

#main program
result=readvalues() # Function Call
findsumavg(result) # Function Call

128
==========================================
List comprehension
==========================================
=>The purpose of List comprehension is that to read the values
dynamically from key board separated by a delimeter ( space, comma,
colon..etc)
=>List comprehension is the most effective way for reading the data for
list instead tradtional reading the data.
=>Syntax:- listobj=[ expression for varname in
Iterable_object ]
=>here expression represents either type cating or mathematical
expression

Examples:

print("Enter List of values separated by space:") #


[10,2,222,50,10,4,55,-3,0,22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst)

Examples:

lst=[4,3,7,-2,6,3]
newlst=[ val*2 for val in lst ]
print("new list=",newlst) # [ 8, 6, 14,-4,12,6 ]

#listcompre.py
print("Enter List of values separated by space:") #
[10,2,222,50,10,4,55,-3,0,22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst)
print("============OR================")
ls=[]
n=int(input("Enter how many values u want to be list:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("Enter {} values:".format(n))
for i in range(1,n+1):
val=int(input())
ls.append(val)
else:
print("content of lst",ls)

#listcompre1.py
print("Enter List of values separated by space:") #
[10,2,222,50,10,4,55,-3,0,22]

129
lst= [float(val) for val in input().split() ]
print("content of lst",lst) # [3.0, 5.0, 2.0, 7.0, 3.0, 9.0, 6.0]
print("-"*40)
newlst=[]
for val in lst:
newlst.append(val*2)
else:
print("new list=",newlst)
print("-"*40)
print("==============OR=================")
newlst=[ val*2 for val in lst]
print("new list=",newlst)

#This program accept list of values dynamically by using list


comprehension and sort them
#listsortcompre.py
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)

def sortelements(lst):
print("Original Elements")
disp(lst)
lst.sort()
print("Sorted Elements in Ascending Order")
disp(lst)
lst.reverse() # or lst.sort(reverse=True)
print("Sorted Elements in Decending Order")
disp(lst)

#main program
print("Enter List of values separated by space:") #
[10,2,222,50,10,4,55,-3,0,22]
lst= [ int(val) for val in input().split() ]
sortelements(lst)

====================================----------------------------------------------------------------

#This program accept list of names dynamically by using list


comprehension and sort them
#listsortcompre1.py
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)

def sortelements(lst):
print("Original Elements")
disp(lst)

130
lst.sort()
print("Sorted Elements in Ascending Order")
disp(lst)
lst.reverse() # or lst.sort(reverse=True)
print("Sorted Elements in Decending Order")
disp(lst)

#main program
print("Enter List of Names separated by comma:")
lst= [ str(val) for val in input().split(",") ]
sortelements(lst)

#Program for accepting list of values from kbd and get only +VE numbers
#listcomprehenex3.py
print("Enter list of values separated by comma")
lst=[ int(val) for val in input().split(",") ]
plst=list()
nlst=list()
for val in lst:
if val>0:
plst.append(val)
elif(val<0):
nlst.append(val)
else:
print("Given List={}".format(lst))
print("Possitive List={}".format(plst))
print("Negative List={}".format(nlst))

#listcomprex1.py
lst1=[2,4,5,-4,5,6]

lst2=[ val**2 for val in lst1]


lst3=[k**0.5 for k in lst1]

print("\nContent of lst1={}".format(lst1))
print("Content of lst2={}".format(lst2))
print("Content of lst3={}".format(lst3))

#listcomprex2.py
print("Enter list of values separated by space")
lst=[float(val) for val in input().split() ] # 10 20 30 40 50 60
70"
print("content of lst=",lst)

#Program for accepting list of values and find sum and average
#listsumavgcpmpre.py
def readvalues():
print("Enter Number of Value separated by space")
lst=[int(val) for val in input().split()]

131
return lst
def findsumavg(obj):
if(len(obj)!=0):
s=0
for val in obj:
print("\t{}".format(val))
s=s+val
else:
print("Sum={}".format(s))
print("Average={}".format(s/len(obj)))

else: # in the case of None


print("\nWe don't have any values and can't find sum and
average")

#main program
result=readvalues() # Function Call
findsumavg(result) # Function Call

#Program for accepting list of names from kbd and sort the names
#sortnames.py
def readnames():
print("Enter Names of People:")
lst=[str(val) for val in input().split()]
return lst

def sortnames(obj):
if(len(obj)==0 ):
print("No Need to sort any thing, bcoz list does not
contain any names:")
else:
print("-"*40)
print("List of Names in Original Order:")
print("-"*40)
for val in obj:
print("\t{}".format(val))
obj.sort() # Ascending Order
print("-"*40)
print("List of Names in Ascending Order:")
print("-"*40)
for val in obj:
print("\t{}".format(val))
obj.sort(reverse=True) # Decending Order
print("List of Names in Decending Order:")
print("-"*40)
for val in obj:
print("\t{}".format(val))

#main program
lst=readnames() # Function call
sortnames(lst)

132
12/May/2022
=============================================
Arguments and Parameters
=============================================
=>In Python, we have Two types of Parameters . They are
1) Formal Parameters
2) Local Parameters / Variables
=>Formal parameters are always used in Function Heading and they are
used for Holding or
storing Input values coming from Function Calls.
=>Local Parameters / Variables are those which are inside of Function
Body and they are used
for Storing Temporary Results.
=>Arguments are Variables (Global ) used as part of Function Call and
arguments always contains input of given problem.
=>Arguments are always called Actual Arguments.
=>Arguments can be available either in the form Values or Variables in
Function Call.
=>All Values of Arguments of Function Call are passing to Formal
Parameters of Function Heading.

Examples:

#ArgsParams.py

def show(a,b):
print("{}\t{}".format(a,b))

def disp(sno,sname,collname): print("{}\t{}\


t{}".format(sno,sname,collname))

#main program
show(10,20) # Function Call--here 10 and 20 are called Argument Values
print(" ")
sno=100
sname="Rossum"
cname="PSF"
disp(sno,sname,cname)#Function Call----sno,sname and cname are called
Argument Names

===================================================================
#ArgsParams.py
def show(a,b):
print("{}\t{}".format(a,b))
def disp(sno,sname,collname): print("{}\t{}\
t{}".format(sno,sname,collname))

#main program
show(10,20) # Function Call--here 10 and 20 are called Argument Values
print(" ")
sno=100
sname="Rossum"
cname="PSF"
disp(sno,sname,cname)#Function Call----sno,sname and cname are called
Argument Names

133
=========================================
1) Possitional Arguments (or) Parameters
=========================================
=>The Concept of Possitional Parameters (or) arguments says that "The
Number of Arguments(Actual arguments ) must be equal to the number of
formal parameters ".
=>This Parameter mechanism also recommends Order and Meaning of
Parameters for Higher accuracy.
=>To pass the Specific Data from Function Call to Function Definition
then we must take Possitional Argument Mechanism.
=>The default Argument Passing Mechanism is Possitional Arguments (or)
Parameters.

Syntax for Function Definition :

def functionname(parm1,param2.....param-n):

Syntax for Function Call:

functionname(arg1,arg2....arg-n)

=>Here the values of arg1,arg2...arg-n are passing to param-1,param-


2..param-n respectively.
========================x==============================================
========

======================================
2) Default Parameters (or) arguments
======================================
=>When there is a Common Value for family of Function Calls then Such
type of Common Value(s) must be taken as default parameter with common
value (But not recommended to pass by using Posstional Parameters)

Syntax: for Function Definition with Default Parameters

def functionname(param1,param2,....param-n-1=Val1, Param-n=Val2):

Here param-n-1 and param-n are called "default Parameters"


and param1,param-2... are called "Possitional parameters"

Rule-: When we use default parameters in the function definition, They


must be used as last Parameter(s) otherwise we get Error( SyntaxError:
non-default argument (Possitional ) follows default argument).

134
==========================================
#Program for demonstarting Possitional Arguments
#PossArgsEx1.py
def disp(x,y):
print("{}\t{}".format(x,y))

#main program
disp(10,20) # Function Call
disp(100,200) # Function call
disp(1000,2000) # Functio call

#Program for demonstarting Possitional Arguments


#PossArgsEx2.py
def showinfo(sno,sname,marks): print("\t{}\t{}\
t{}".format(sno,sname,marks))

#main program
print("-"*50)
print("\tStno\tName\tMarks")
print("-"*50)
showinfo(10,"RS",45.67)
showinfo(20,"JG",34.56)
showinfo(30,"DR",74.56)
showinfo(40,"TR",14.56)
print("-"*50)

#Program for demonstarting Default Arguments Mechanism


#DefArgsEx1.py
def showinfo(sno,sname,marks,crs="PYTHON"): print("\t{}\t{}\t{}\
t{}".format(sno,sname,marks,crs))

#main program
print("-"*50)
print("\tStno\tName\tMarks\tCourse")
print("-"*50)
showinfo(10,"RS",45.67) # Function call
showinfo(20,"JG",34.56) # Function call
showinfo(30,"DR",74.56) # Function call
showinfo(40,"TR",14.56) # Function call
showinfo(50,"AN",24.56,"JAVA") # Function call
showinfo(60,"BJ",44.56) # Function call
print("-"*50)

135
#Program for demonstarting Default Arguments Mechanism
#DefArgsEx2.py
def showinfo(sno,sname,marks,crs="PYTHON",cnt="INDIA"): print("\t{}\t{}\t{}\t{}\
t{}".format(sno,sname,marks,crs,cnt))

#main program
print("-"*50)
print("\tStno\tName\tMarks\tCourse\tCountry")
print("-"*50)
showinfo(10,"RS",45.67) # Function call
showinfo(20,"JG",34.56) # Function call
showinfo(30,"DR",74.56) # Function call
showinfo(40,"TR",14.56) # Function call
showinfo(50,"AN",24.56,"JAVA") # Function call
showinfo(60,"BJ",44.56) # Function call
showinfo(70,"TR",44.56,"PHP","USA") # Function call
print("-"*50)

============================================
3) Keyword Parameters (or) arguments
============================================
=>In some of the circumstances, we know the function name and formal
parameter names and we don't know the order of formal Parameter names
and to pass the data / values accurately we must use the concept of
Keyword Parameters (or) arguments.
=>The implementation of Keyword Parameters (or) arguments says that all
the formal parameter names used as arguments in Function call(s) as
keys.

Syntax for function definition:-

def functionname(param1,param2...param-n):

Syntax for function call:-

functionname(param-n=val-n,param1=val1,param-n-1=val-n-1,......)

Here param-n=val-n,param1=val1,param-n-1=val-n-1,...... are called


Keywords arguments
=>We must write or use Keyword arguments after Possitional Arguments
otherwise get SyntaxError: positional argument follows keyword argument
==========================X============================================
======

136
#Program for demostrating KeyWord Arguments (or) Parameters
#kwdargsex1.py
def showempinfo(eno,ename,sal,dsg): print("\t{}\t{}\t{}\
t{}".format(eno,ename,sal,dsg))

#main program
print("-"*50)
print("\tEno\tName\tSal\tDsg")
print("-"*50)
showempinfo(10,"RS",5.6,"SE") # Function Call--Possitional Args
showempinfo(dsg="TL",eno=30,ename="JG",sal=4.5)# Function Call--Keyword
Args
showempinfo(20,"DR",dsg="HR",sal=3.4) # Function Call--Possitional Args
& Keyword Args
#showempinfo(sal=7.8,dsg="PM",40,"TR") SyntaxError: positional argument
follows keyword

showempinfo(40,sal=4.5,dsg="TL",ename="DR")
print("-"*50)

#Program for demostrating KeyWord Arguments (or) Parameters


#kwdargsex2.py
def showempinfo(eno,ename,sal,dsg,crs="PYTHON",cnt="INDIA"): print("\
t{}\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,crs,cn
t))

#main program
print("-"*50)
print("\tEno\tName\tSal\tDsg\tCourse\tCountry")
print("-"*50)
showempinfo(10,"RS",5.6,"SE") # Function Call--Possitional Args
showempinfo(dsg="TL",eno=30,ename="JG",sal=4.5)# Function Call--Keyword
Args
showempinfo(20,"DR",dsg="HR",sal=3.4) # Function Call--Possitional Args
& Keyword Args
#showempinfo(sal=7.8,dsg="PM",40,"TR") SyntaxError: positional argument
follows keyword

showempinfo(40,sal=4.5,dsg="TL",ename="DR")
showempinfo(50,"MC",4.6,"TL","JAVA") # Function Call--Possitional Args
showempinfo(crs="Django",sal=3.4,eno=60,dsg="Sr.SE",ename="ST")##
Function Call--Keyword Args
#showempinto(sal=4.9,eno=70,"KN",dsg="Traine") SyntaxError: positional
argument follows keyword argument
showempinfo(crs="DS",cnt="USA",sal=6.7,ename="KR",dsg="RA",eno=80)##
Function Call--Keyword Args
print("-"*50)

================================================
4) Variables Length Parameters (or) arguments
================================================

137
=>When we have familiy of multiple function calls with Variable number
of values / arguments then with normal python programming, we must
define mutiple function defintions. This process leads to more
development time. To overcome this process, we must use the concept of
Variable length Parameters .
=>To Impelement, Variable length Parameters concept, we must define
single Function Definition and takes a formal Parameter preceded with a
symbol called astrisk ( * param) and the formal parameter with astrisk
symbol is called Variable length Parameters and whose purpose is to
hold / store any number of values coming from similar function calls
and whose type is <class, 'tuple'>.

Syntax for function definition with Variables Length Parameters:

def functionname(list of formal params, *param1,param2=value)


:

=>Here *param is called Variable Length parameter and it can hold any
number of argument values (or) variable number of argument values and
*param type is <class,'tuple'>

=>Rule:- The *param must always written at last part of Function


Heading and it must be only one (but not multiple)

=>Rule:- When we use Variable length and default parameters in


function Heading, we use default parameter as last and before we use
variable length parameter and in function calls, we should not use
default parameter as Key word argument bcoz Variable number of values
are treated as Posstional Argument Value(s)

#Program for demonstrating Variable Length Arguments (or) Parameters--


This Program will not execute as it is
#varargsex1.py
def disp(a): # Function Def-1
print(a)
def disp(a,b): # Function Def-2
print("{}\t{}".format(a,b))

def disp(a,b,c): # Function Def-3


print("{}\t{}\t{}".format(a,b,c))

def disp(a,b,c,d): # Function Def-4 print("{}\t{}\t{}\


t{}".format(a,b,c,d))

#main program
disp(10) # Function Call-1
disp(10,20) # Function Call-2
disp(10,20,30) # Function Call-3
disp(10,20,30,40) # Function Call-4
=============================
#Program for demonstrating Variable Length Arguments (or) Parameters--
This Program will execute as it is

138
#varargsex2.py
def disp(a): # Function Def-1
print(a)

disp(10) # Function Call-1

def disp(a,b): # Function Def-2


print("{}\t{}".format(a,b))

disp(10,20) # Function Call-2

def disp(a,b,c): # Function Def-3


print("{}\t{}\t{}".format(a,b,c))

disp(10,20,30) # Function Call-3

def disp(a,b,c,d): # Function Def-4 print("{}\t{}\t{}\


t{}".format(a,b,c,d))

disp(10,20,30,40) # Function Call-4

#purevarargsex1.py

def disp( *a ): # here * a is called Var length args or


Parameter and whose type is <class, tuple>
print("-"*50)
print("type of a=",type(a))
print("Number of value=",len(a))
for val in a:
print("{}".format(val),end=" ")
print()
print("-"*50)

#main program
disp(10) # Function Call-1
disp(10,20) # Function Call-2
disp(10,20,30) # Function Call-3
disp(10,20,30,40) # Function Call-4
disp()

#purevarargsex2.py

def disp( *a ): # here * a is called Var args Parameter and whose


type is <class, tuple>
for val in a:
print("{}".format(val),end=" ")
print()

#main program
disp(10) # Function Call-1

139
disp(10,20) # Function Call-2
disp(10,20,30) # Function Call-3
disp(10,20,30,40) # Function Call-4
disp("RS","KR","DR",23,45.67)
disp()

==============================================

#Program for demonstrating Variable Length Arguments (or) Parameters


#purevarargsex3.py
def showinfo(ssid,sname,*details):
print("-"*50) print("\tSSID:
{}".format(ssid))
print("\tName:{}".format(sname))
print("-"*50)
for val in details:
print("\t{}".format(val))
print("-"*50)

#main program
showinfo(111,"Rossum","Python","Django","Data Sci")
showinfo(222,"Travis","Num Lib","Numpy",34.56,True)
showinfo(333,"Ritche","B-Lang","C-lang")
showinfo(444,"Biswajit",12.3)
showinfo(555,"KInney")
print(" ")

#Program for demonstrating Variable Length Arguments (or) Parameters


#purevarargsex4.py
def showinfo(ssid,sname,*details,crs="PYTHON"):
print("-"*50) print("\tSSID:
{}".format(ssid))
print("\tName:{}".format(sname))
print("\tCourse:{}".format(crs))
print("-"*50)
for val in details:
print("\t{}".format(val))
print("-"*50)

#main program
showinfo(111,"Rossum","Ruby","Django","Data Sci")
showinfo(222,"Travis","Num Lib","Numpy",34.56,True)
showinfo(333,"Ritche","B-Lang","C-lang")
showinfo(444,"Biswajit",12.3)
showinfo(555,"KInney")
print(" ")
#showinfo(crs="JAVA",ssid=666,sname="Sanket",56,78,45) #SyntaxError:
positional argument follows keyword argument
#showinfo(sname="Sanket",ssid=666, 56,78,45) #SyntaxError: positional
argument follows keyword argument
#showinfo(56,78,45,ssid=666,sname="Sanket") TypeError: showinfo() got
multiple values for argument 'ssid'
showinfo(666,"Sanket",56,78,45,crs="JAVA")

140
#showinfo(666,"Sanket",crs="JAVA",56,78,45) SyntaxError: positional
argument follows keyword argument

=======================================================

#Program for demonstrating Variable Length Arguments (or) Parameters


#purevarargsex5.py
def findsum(sname,*nums,s=0):
print("-"*50)
print("Student Name:{}".format(sname))
print("-"*50)
for val in nums:
print("{}".format(val),end=" ")
s=s+val
print()
print("Sum={}".format(s))
print("-"*50)

#main program
findsum("RS",10,20,30)
findsum("DR",10.3,20.5)
findsum("TR",10,20,34.5,12.5)
findsum("JH")

================================================
5) Key Word Variables Length Parameters (or) arguments
================================================
=>When we have familiy of multiple function calls with Key Word
Variable number of values / arguments then with normal python
programming, we must define mutiple function defintions. This process
leads to more development time. To overcome this process, we must use
the concept of Keyword Variable length Parameters .
=>To Implement, Keyword Variable length Parameters concept, we must
define single Function Definition and takes a formal Parameter preceded
with a symbol called double astrisk ( ** param) and the
formal parameter with double astrisk symbol is called Keyword Variable
length Parameters and whose purpose is to hold / store any number of
(Key,Value) coming from similar function calls and whose type is
<class, 'dict'>.

Syntax for function definition with Keyword Variables Length


Parameters:

def functionname(list of formal params, **param) :

141
=>Here **param is called Keyword Variable Length parameter and it can
hold any number of Key word argument values (or) Keyword variable
number of argument values and **param type is <class,'dict'>

=>Rule:- The **param must always written at last part of Function


Heading and it must be only one (but not multiple)

Final Syntax:

def funcname(PosFormal parms, *Varlenparams, default params,


**kwdvarlenparams):

--
==============================X=======================================

#Program for demostrating KeyWord Arguments (or) Parameters


#kwdargsex1.py
def showempinfo(eno,ename,sal,dsg): print("\t{}\t{}\t{}\
t{}".format(eno,ename,sal,dsg))

#main program
print("-"*50)
print("\tEno\tName\tSal\tDsg")
print("-"*50)
showempinfo(10,"RS",5.6,"SE") # Function Call--Possitional Args
showempinfo(dsg="TL",eno=30,ename="JG",sal=4.5)# Function Call--Keyword
Args
showempinfo(20,"DR",dsg="HR",sal=3.4) # Function Call--Possitional Args
& Keyword Args
#showempinfo(sal=7.8,dsg="PM",40,"TR") SyntaxError: positional argument
follows keyword

showempinfo(40,sal=4.5,dsg="TL",ename="DR")
print("-"*50)

#Program for demostrating KeyWord Arguments (or) Parameters


#kwdargsex2.py
def showempinfo(eno,ename,sal,dsg,crs="PYTHON",cnt="INDIA"): print("\
t{}\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,crs,cn
t))

#main program
print("-"*50)
print("\tEno\tName\tSal\tDsg\tCourse\tCountry")
print("-"*50)
showempinfo(10,"RS",5.6,"SE") # Function Call--Possitional Args
showempinfo(dsg="TL",eno=30,ename="JG",sal=4.5)# Function Call--Keyword
Args
showempinfo(20,"DR",dsg="HR",sal=3.4) # Function Call--Possitional Args
& Keyword Args
#showempinfo(sal=7.8,dsg="PM",40,"TR") SyntaxError: positional argument
follows keyword

142
showempinfo(40,sal=4.5,dsg="TL",ename="DR")
showempinfo(50,"MC",4.6,"TL","JAVA") # Function Call--Possitional Args
showempinfo(crs="Django",sal=3.4,eno=60,dsg="Sr.SE",ename="ST")##
Function Call--Keyword Args
#showempinto(sal=4.9,eno=70,"KN",dsg="Traine") SyntaxError: positional
argument follows keyword argument
showempinfo(crs="DS",cnt="USA",sal=6.7,ename="KR",dsg="RA",eno=80)##
Function Call--Keyword Args
print("-"*50)

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex1.py--

def showinfo( **kvr): # here ** kvr is called is calle Keyword Var


length param--type is dict
print(kvr,type(kvr))

#main program
showinfo(sno=100,sname="TR") # Function Call-2
showinfo(eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo(ssid=1212,cname="MC",hobby1="Read",hobby2="Play") # Function
Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex2.py

def showinfo( **kvr): # here ** kvr is called is calle Keyword Var


length param--type is dict
print("-"*50)
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))

#main program
showinfo(sno=100,sname="TR") # Function Call-2
showinfo(eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo(ssid=1212,cname="MC",hobby1="Read",hobby2="Play") # Function
Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex3.py

def showinfo(city,**kvr): # here ** kvr is called is calle Keyword


Var length param--type is dict
print("-"*50)
print("Living City={}".format(city))
for k,v in kvr.items():

143
print("\t{}--->{}".format(k,v))

#main program
showinfo("HYD",sno=100,sname="TR") # Function Call-2
showinfo("MUM",eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo("Bang",ssid=1212,cname="MC",hobby1="Read",hobby2="Play") #
Function Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex4.py

def showinfo(city,crs="PYTHON",**kvr):
print("-"*50)
print("Living City={}".format(city))
print("Course:{}".format(crs))
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))

#main program
showinfo("HYD",sno=100,sname="TR") # Function Call-2
showinfo("MUM",eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo("Bang",ssid=1212,cname="MC",hobby1="Read",hobby2="Play") #
Function Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex5.py

def showinfo(city,*k1,crs="PYTHON", **kvr):


print("-"*50)
print("Variable Length Arguments:")
print("-"*50)
for val in k1:
print("\t{}".format(val))
print("-"*50)
print("Key Word Variable Length Arguments:")
print("-"*50)
print("Living City={}".format(city))
print("Course:{}".format(crs))
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))
print()
print("-"*50)
#main program
showinfo("HYD",10,20,sno=100,sname="TR",) # Function Call-2
showinfo("MUM",1.2,1.3,1.4, eno=10,ename="RS",sal=3.4) # Function Call-
1
showinfo("Bang",12,34,ssid=1212,cname="MC",hobby1="Read",hobby2="Play")
# Function Call-3

================================================
5) Key Word Variables Length Parameters (or) arguments

144
================================================
=>When we have familiy of multiple function calls with Key Word
Variable number of values / arguments then with normal python
programming, we must define mutiple function defintions. This process
leads to more development time. To overcome this process, we must use
the concept of Keyword Variable length Parameters .
=>To Implement, Keyword Variable length Parameters concept, we must
define single Function Definition and takes a formal Parameter preceded
with a symbol called double astrisk ( ** param) and the
formal parameter with double astrisk symbol is called Keyword Variable
length Parameters and whose purpose is to hold / store any number of
(Key,Value) coming from similar function calls and whose type is
<class, 'dict'>.

Syntax for function definition with Keyword Variables Length


Parameters:

def functionname(list of formal params, **param) :

=>Here **param is called Keyword Variable Length parameter and it can


hold any number of Key word argument values (or) Keyword variable
number of argument values and **param type is <class,'dict'>

=>Rule:- The **param must always written at last part of Function


Heading and it must be only one (but not multiple)

Final Syntax:

def funcname(PosFormal parms, *Varlenparams, default params,


**kwdvarlenparams):

--
==============================X=======================================

#Program for demostrating KeyWord Arguments (or) Parameters


#kwdargsex1.py
def showempinfo(eno,ename,sal,dsg): print("\t{}\t{}\t{}\
t{}".format(eno,ename,sal,dsg))

#main program
print("-"*50)
print("\tEno\tName\tSal\tDsg")
print("-"*50)

145
showempinfo(10,"RS",5.6,"SE") # Function Call--Possitional Args
showempinfo(dsg="TL",eno=30,ename="JG",sal=4.5)# Function Call--Keyword
Args
showempinfo(20,"DR",dsg="HR",sal=3.4) # Function Call--Possitional Args
& Keyword Args
#showempinfo(sal=7.8,dsg="PM",40,"TR") SyntaxError: positional argument
follows keyword

showempinfo(40,sal=4.5,dsg="TL",ename="DR")
print("-"*50)

#Program for demostrating KeyWord Arguments (or) Parameters


#kwdargsex2.py
def showempinfo(eno,ename,sal,dsg,crs="PYTHON",cnt="INDIA"): print("\
t{}\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,crs,cn
t))

#main program
print("-"*50)
print("\tEno\tName\tSal\tDsg\tCourse\tCountry")
print("-"*50)
showempinfo(10,"RS",5.6,"SE") # Function Call--Possitional Args
showempinfo(dsg="TL",eno=30,ename="JG",sal=4.5)# Function Call--Keyword
Args
showempinfo(20,"DR",dsg="HR",sal=3.4) # Function Call--Possitional Args
& Keyword Args
#showempinfo(sal=7.8,dsg="PM",40,"TR") SyntaxError: positional argument
follows keyword

showempinfo(40,sal=4.5,dsg="TL",ename="DR")
showempinfo(50,"MC",4.6,"TL","JAVA") # Function Call--Possitional Args
showempinfo(crs="Django",sal=3.4,eno=60,dsg="Sr.SE",ename="ST")##
Function Call--Keyword Args
#showempinto(sal=4.9,eno=70,"KN",dsg="Traine") SyntaxError: positional
argument follows keyword argument
showempinfo(crs="DS",cnt="USA",sal=6.7,ename="KR",dsg="RA",eno=80)##
Function Call--Keyword Args
print("-"*50)
#Program for demonstrating Keyword Variable Length Arguments (or)
Parameters
#purekwdvarlegargsex1.py--

def showinfo( **kvr): # here ** kvr is called is calle Keyword Var


length param--type is dict
print(kvr,type(kvr))

#main program
showinfo(sno=100,sname="TR") # Function Call-2
showinfo(eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo(ssid=1212,cname="MC",hobby1="Read",hobby2="Play") # Function
Call-3

146
#Program for demonstrating Keyword Variable Length Arguments (or)
Parameters
#purekwdvarlegargsex2.py

def showinfo( **kvr): # here ** kvr is called is calle Keyword Var


length param--type is dict
print("-"*50)
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))

#main program
showinfo(sno=100,sname="TR") # Function Call-2
showinfo(eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo(ssid=1212,cname="MC",hobby1="Read",hobby2="Play") # Function
Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex3.py

def showinfo(city,**kvr): # here ** kvr is called is calle Keyword


Var length param--type is dict
print("-"*50)
print("Living City={}".format(city))
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))

#main program
showinfo("HYD",sno=100,sname="TR") # Function Call-2
showinfo("MUM",eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo("Bang",ssid=1212,cname="MC",hobby1="Read",hobby2="Play") #
Function Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters
#purekwdvarlegargsex4.py

def showinfo(city,crs="PYTHON",**kvr):
print("-"*50)
print("Living City={}".format(city))
print("Course:{}".format(crs))
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))

#main program
showinfo("HYD",sno=100,sname="TR") # Function Call-2
showinfo("MUM",eno=10,ename="RS",sal=3.4) # Function Call-1
showinfo("Bang",ssid=1212,cname="MC",hobby1="Read",hobby2="Play") #
Function Call-3

#Program for demonstrating Keyword Variable Length Arguments (or)


Parameters

147
#purekwdvarlegargsex5.py

def showinfo(city,*k1,crs="PYTHON", **kvr):


print("-"*50)
print("Variable Length Arguments:")
print("-"*50)
for val in k1:
print("\t{}".format(val))
print("-"*50)
print("Key Word Variable Length Arguments:")
print("-"*50)
print("Living City={}".format(city))
print("Course:{}".format(crs))
for k,v in kvr.items():
print("\t{}--->{}".format(k,v))
print()
print("-"*50)
#main program
showinfo("HYD",10,20,sno=100,sname="TR",) # Function Call-2
showinfo("MUM",1.2,1.3,1.4, eno=10,ename="RS",sal=3.4) # Function Call-
1
showinfo("Bang",12,34,ssid=1212,cname="MC",hobby1="Read",hobby2="Play")
# Function Call-3

==================================================
Local Variables and Global Variables
===================================================
=>Local Variables are those which are used inside of FunctionBody and
they can used for storing Temprorary Results.
=>The Local Variables can be accessed within Corresponding Function
Defintion and not possible to access other part of program and in other
Functions.
=>Global Variables are those which used any where else in the program
and they are used for storing Common Values for all Different Function
calls but global variables should not be defined inside of Function
Definition.
=>Global Variables must be defined before all the function Calls to
access its common value in all its Function Definitions. ( But not
necessary to define before the function Definitions)
==============================X=====================================

#GlobalLocalVarEx1.py
lang="PYTHON" # Global Variable--Stores Common values for Different
Function Calls.

def learnDS():
crs1="DS"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs1,lang))

def learnML():
crs2="ML"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs2,lang))

def learnIOT():
crs3="IOT"

148
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs3,lang))

#main program
learnDS()
learnML()
learnIOT()

#GlobalLocalVarEx2.py
def learnDS():
crs1="DS"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs1,lang))

def learnML():
crs2="ML"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs2,lang))

def learnIOT():
crs3="IOT"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs3,lang))

#main program
lang="PYTHON" # Global Variable--Stores Common values for Different
Function Calls.
learnDS() # Function Call
learnML() # Function Call
learnIOT() # Function Call

#GlobalLocalVarEx3.py
def learnDS():
crs1="DS"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs1,lang))

def learnML():
crs2="ML"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs2,lang))

def learnIOT():
crs3="IOT"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs3,lang))

#main program
#learnDS() # Function Call--In this Function Definition, we can't
access 'lang' value
lang="PYTHON" # Global Variable--Stores Common values for Different
Function Calls.
learnML() # Function Call
learnIOT() # Function Call

149
#GlobalLocalVarEx4.py
def learnDS():
crs1="DS"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs1,lang))

def learnML():
crs2="ML"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs2,lang))

def learnIOT():
crs3="IOT"
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs3,lang))

#main program
#learnDS() # Function Call--In this Function Definition, we can't
access 'lang' value
#learnML() # Function Call---In this Function Definition, we can't
access 'lang' value
#learnIOT() # Function Call--In this Function Definition, we can't
access 'lang' value
lang="PYTHON" # Global Variable--Stores Common values for Different
Function Calls.

#GlobalLocalVarEx5.py

def learnDS():
crs1="DS" # Local Varaible
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs1,lang))
#print(crs2,crs3) can't access bcoz crs2 and crs3 are local
varibles
def learnML():
crs2="ML" # Local Varaible
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs2,lang))
#print(crs1,crs3) can't access bcoz crs1 and crs3 are local
varibles

def learnIOT():
crs3="IOT" # Local Varaible
print("\nTo Learn and code in '{}' , we need '{}'
Language".format(crs3,lang))
#print(crs1,crs2) can't access bcoz crs1 and crs3 are local
varibles
#main program
lang="PYTHON" # Global Variable--Stores Common values for Different
Function Calls.
learnDS() # Function Call--In this Function Definition, we can access
'lang' value

150
learnML() # Function Call---In this Function Definition, we can access
'lang' value
learnIOT() # Function Call--In this Function Definition, we can access
'lang' value

======================================
global key word
======================================
=>When we want MODIFY the GLOBAL VARIABLE values in side of function
defintion then global variable names must be preceded with 'global'
keyword otherwise we get "UnboundLocalError: local variable names
referenced before assignment"

Syntax:

var1=val1
var2=val2
var-n=val-n # var1,var2...var-n are called global variable
names.
def fun1():

global var1,var2...var-n
# Modify var1,var2....var-n

def fun2():

global var1,var2...var-n
# Modify var1,var2....var-n

Examples:

#globalvarex1.py
a=10
def access1():
print("Val of a=",a) # Here we are accessing the global variable
'a' and No Need to use global kwd.

#main program
access1()

#globalvarex2.py
a=10
def access1():
global a # refering global Varaible before its updation /
Modification
a=a+1 # Here we are modifying the global variable value then we
need to use global keyword.
print("Val of a inside of access1()=",a) # 11
#main program
print("Val of a in main before access1():",a) # 10

151
access1()
print("Val of a in main after access1():",a) # 11

Examples:

#globalvarex3.py
def update1():
global a,b # refering global Variables.
a=a+1 #updating global Variable a
b=b+1 #updating global Variable b
def update2():
global a,b # refering global Variables.
a=a*10 #updating global Variable a
b=b*10 #updating global Variable b

#main program
a,b=1,2 # here a and b are called Global Variables
print("Val of a={} and Value of b={} in main program before update
functions :".format(a,b))
# Val of a=1 and Value of b=2 in main program before update functions
:
update1()
print("Val of a={} and Value of b={} in main program after
update1():".format(a,b))
#Val of a=2 and Value of b=3 in main program after update1():
update2()
print("Val of a={} and Value of b={} in main program after
update2():".format(a,b))
#Val of a=20 and Value of b=30 in main program after update1():
================================X=====================================

#globalkwdex1.py
a=10 # global varaible
def fun1():
print("\nVal of Global Variable-a in fun1()={}".format(a)) #
Here we are accessing Global Variable Value

def fun2():
print("\nVal of Global Variable-a in fun2()={}".format(a)) #
Here we are accessing Global Variable Value

#main program
print("Val of Global Variable-a in main program={}".format(a))
fun1()
fun2()

#globalkwdex2.py
a=10 # global variable value
def fun1():
global a # here PVM refers Global Variable value 'a' bcoz we
use global kwd
a=a+1 # updating or modifying the global Variable Value

def fun2():
global a # here PVM refers Global Variable value 'a' bcoz we
use global kwd

152
a=a*2

#main program
print("Val of Global Variable-a in main program before
fun1()={}".format(a)) # 10
fun1()
print("Val of Global Variable-a in main program after
fun1()={}".format(a)) # 11
fun2()
print("Val of Global Variable-a in main program after
fun2()={}".format(a)) # 22

#globalkwdex3.py
a=10
b=20 # here 'a' and 'b' are called global variables
c=30 # Here 'c' is also global Variable
def updatevalues():
global a,b # here PVM refers Global Variable value 'a and b'
bcoz we use global kwd
a=a+1
b=b+1
c=100 #herere 'c' is local Variable
c=c+1 # updating local Variable
print("Val of c inside updatevalues()={}".format(c)) # 101

#main program
print("Val of Global Variable-a in main program before updatevalues()
={}".format(a))#10
print("Val of Global Variable-b in main program before
updatevalues()={}".format(b))#20
updatevalues()
print("\nVal of Global Variable-a in main program after
updatevalues()={}".format(a)) # 11
print("Val of Global Variable-b in main program after
updatevalues()={}".format(b)) # 21
print("Val of c--global Variables ={}".format(c)) #30

17/05/2022
============================================
global and local variables and globals()
============================================
=>When we come acrosss same global Variable names and Local Vraiable
Names in same function definition then PVM gives preference for local
variables but not for global variables.
=>In this context, to extract / retrieve the values of global variables
names along with local variables, we must use globals() and it returns
an object of <class,'dict'> and this dict object stores all global
variable Names as Keys and global variable values as values of value.

=>Syntax:-
var1=val1
var2=val2

153
var-n=val-n # var1, var2...var-n are called global
Variables
def functionname():

var1=val11
var2=val22

var-n=val-nn # var1, var2...var-n are called


local Variables
# Extarct the global variables values
dictobj=globals()

globalval1=dictobj['var1'] # or
dictobj.get("var1") or globals()['var1']
globalval2=dictobj['var2'] # or
dictobj.get("var2") or globals()['var2']

---

---
==================================================================
Examples:
============
#globalsfunex3.py
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])

154
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================
#main program
operations()
==================================================

Examples:

#Program for demonstrating globals()


#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()['c']+glo
bals()['d']
print(res)

#main program
operation()

====================================X==================================
==

#Program for demonstrating globals()


#globalsfunex1.py
a=10
b=20
c=30
d=40 # Here 'a b , c d ' are called global Variables
def operations():
global c,d # refering global Variable Values
c=c+1
d=d+1 # Modifying the global Variables Values c=31 and d=41
a=1
b=2 # Here 'a' and 'b' are local Variables
res=a+b+c+d+ globals()['a']+globals()['b'] # way-1
print("Result=",res)
print(" ")
res=a+b+c+d+ globals().get('a')+globals().get('b')
print("Result=",res)
print("======================================")
print("Val of a--local={}".format(a))
print("Val of b--local={}".format(b))
print("Val of a--global={}".format(globals().get('a')))
print("Val of b--global={}".format(globals().get('b')))
print("Val of c--global={}".format(c))
print("Val of d--global={}".format(d))
#main program
operations()
print("\ntype of operations=",type(operations))

155
====================================================================

#globalsfunex2.py---globals()
a=100
b=200
c=300 # Here 'a b ,c ' are called global Variables
def func1():
d=globals() # obtains all the values Global Variables and store
them dict object
print("type of d=",type(d)) # type of d= <class 'dict'>
for k,v in d.items():
print("{}-->{}".format(k,v)) print("\
n=================================")
print("Programmer-defined Global Variables-Way-1")
print("Val of a=", d.get('a'))
print("Val of b=", d.get('b'))
print("Val of c=", d.get('c'))
print("=================================")
print("Programmer-defined Global Variables-Way-2")
print("Val of a=", d['a'] )
print("Val of b=", d['b'] )
print("Val of c=", d['c'] )
print("=================================")
print("Programmer-defined Global Variables-Way-3")
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("=================================")
print("Programmer-defined Global Variables-Way-4")
print("Val of a=", globals()['a'] )
print("Val of b=", globals()['b'] )
print("Val of c=", globals()['c'] )
print("=================================")

#main program
func1()

"""
OUTPUT
E:\KVR-PYTHON-7AM\FUNCTIONS>py globalsfunex2.py
name --> main
doc -->None
package -->None
loader --><_frozen_importlib_external.SourceFileLoader object at
0x0000022968434A90>
spec -->None
annotations -->{}
builtins --><module 'builtins' (built-in)>
file -->E:\KVR-PYTHON-7AM\FUNCTIONS\globalsfunex2.py
cached -->None
a-->100
b-->200
c-->300

156
func1--><function func1 at 0x0000022968023E20>
func2--><function func2 at 0x000002296885D3F0> """

=====================================================================

=================================
generator in python
=================================
=>generator is one of the function
=>The generator function always contains yield keyword
=>If the function contains return statement then it is called Normal
Function
=>If the function contains yield keyword then it is called generator
=>Syntax:
def function_name(start,stop,step):

yield value

=>The 'yield' key word is used for giving the value back to function
call from function defintion and continue the function execution until
condition becomes false.
=>The advantage of generators over functions concept is that it save
lot of memory space in the case large sampling of data. In otherwords
Functions gives all the result at once and it take more memory space
where as generators gives one value at a time when programmer requested
and takes minimized memory space.
=>The advantage of generators concept is that To minimize the memory
space for Application data and provides the value(s) on the basis of
request or demand.
===============================X=======================================
=====

#genex1.py
def kvrrange(k,v):
while(k<=v):
yield k
k=k+1

#main program
r=range(10,20)
print("type of r=",type(r))
print(r)
for v in r:
print(v)
print(" ")
kvrobj=kvrrange(100,105)
print("type of kvrobj=",type(kvrobj))
while(True):
try:
print(next(kvrobj))
except StopIteration:
break

#genex3.py
def func1():
yield "Python"
yield "Django"

157
yield "Data Science"
yield 1.2

#main program
res=func1()
print("type of res=",type(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))

===================================================
Anonymous Functions or Lambda Functions
===================================================
=>Anonymous Functions are those which does not contain any name
explicitly.
=>The purpose of Anonymous Function is that "To Perform Instant
Operations."
=>Instant Operations those Operation which are performing at that point
of time only and no
longer interested to carry or re-use in further applications.
=>Anonymous Functions are containing single line statement for
performing Instant
Operations.
=>To define Anonymous Functions, we use lambda keyword and Hence
Anonymous
Functions are also called Lambda Functions.
=>Anonymous Functions are automatically returns the result of Instant
Operations. In
otherwords there is no need to use return statement in Anonymous
Function.

Syntax:- varname=lambda params-list : Statement

Explanation:

=>Here "varname" is an object of <class, 'function'> and hence


indirectly varname is acting
as Function Name
=>"lambda" is a keyword used to define Anonymous Functions.
=>"params-list" reprsents list of formal params used for storing
Inputs / data from from
Function Calls.
=>"Statement" represents an executable statemnent and it is meant for
providing solution
for Instant Operation and return the result automatically (or)
implicitly.
==============================x========================================
=

Example: addition of two numbers

By Using Normal Function:


---------------------------------------- Function C
def addop(a,b):
res1=addop(10,20)

158
c=a+b
res2=addop(100,200)
retutn c

By Anonymous Function

addop=lambda a,b:a+b

Function calls

res1=addop(2,3)
res2=addop(-4,-5)

#AnonymousFunex1.py
def addop(a,b): # Normal Func Def
c=a+b
return c

sumop=lambda a,b:a+b # anonymous function definition


#main program
print("type of addop=",type(addop))
res1=addop(2,3)
print("Sum by using Normal Function=",res1)
print("Sum by using Normal Function=",addop(100,200))
print("="*50)
print("type of sumop=",type(sumop))
res2=sumop(10,20)
print("Sum by using Anonymous Function=",res2)
res3=sumop(-30,-60)
print("Sum by using Anonymous Function=",res3)
print("Sum by using Anonymous Function=",sumop(1,2))

#AnonymousFunex2.py

sumop=lambda a,b : a+b # anonymous function definition

#main program
res3=sumop(float(input("Enter First Value:")), float(input("Enter
Second Value:")))
print("Sum=",res3)

""""
E:\KVR-PYTHON-7AM\FUNCTIONS>py AnonymousFunex2.py
Enter First Value:10
Enter Second Value:20
Sum= 30.0
"""

159
#AnonymousFunex3.py
def findbig(a,b):
if a>b:
return a
else:
return b

big=lambda a,b: a if a>b else b

#main program
res=findbig(100,20)
print("Result=",res)
print(" ")
res=big(1000,2000)
print("Result=",res)

#AnonymousFunex4.py

big=lambda a,b: a if a>b else b

#main program
x=float(input("Enter Value of a:"))
y=float(input("Enter Value of b:"))
res=big(x,y) print("big({},
{})={}".format(x,y,res))

#AnonymousFunex5.py

big=lambda a,b: "ALL VALUES ARE EQUAL" if a==b else a if a>b else b

#main program
x=float(input("Enter Value of a:"))
y=float(input("Enter Value of b:"))
res=big(x,y) print("big({},
{})={}".format(x,y,res))

#AnonymousFunex6.py

big=lambda k,v,r:"ALL VALUES ARE EQUAL" if (k==v==r) else k if(v<=k>r)


else v if (k<v>r) else r

small=lambda a,b,c: a if (b>a<c) else b if(a>b<c) else c if(a>c<b) else


"ALL VALUES ARE EQUAL"

#main program
x=float(input("Enter Value of x:"))
y=float(input("Enter Value of y:"))
z=float(input("Enter Value of z:"))
res1=big(x,y,z) # 10 5 8
res2=small(x,y,z) # 10 5 8
print(" ")
print("big({},{},{})={}".format(x,y,z,res1))

160
print("small({},{},{})={}".format(x,y,z,res2))
print(" ")

#AnonymousFunex7.py

#Anonymnous Function
big=lambda obj1:max(obj1)
small=lambda obj2: min(obj2)
#main program
print("Enter list of values separated bt space:")
lst=[ int(val) for val in input().split()]
print("big({})={}".format(lst, big(lst) ))
print("small({})={}".format(lst, small(lst) ))

========================================= Special Fu
=========================================
=>In Python Programming, we have 3 special Functions. They are
1. filter()
2. map()
3. reduce()

1) filter():

=>filter() is used for "Filtering out some elements from list of


elements by applying to function".
=>Syntax:- varname=filter(FunctionName, Iterable_object)

Explanation:

161
=>here 'varname' is an object of type <class,'filter'> and we can
convert into any iteratable object by using type casting functions.
=>"FunctionName" represents either Normal function or anonymous
functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of filter() is that " Each Value of Iterable
object sends to Function Name. If the function return True then the
element will be filtered. if the Function returns False the that
element will be neglected/not filtered ". This process will be
continued until all elements of Iterable object completed.

#program for filtering the values by using filter()


def posneg1(x):
if x>0:
return True
else:
return False

def posneg2(n):
if n<0:
return True
else:
return False

#main program

lst=[10,-20,30,-40,-50,60,25]
kvr=filter(posneg1,lst)
print("Type of kvr obj=",type(kvr)) # Type of kvr obj= <class 'filter'>
print("content of kvr=",kvr) # content of kvr= <filter object at
0x0000021FFF150460>
#convert filter object into Iterable object like list, tuple or
set..ect
pslist=set(kvr)
print("Possitive Elements=",pslist)
print("================================")
nslist=list(filter(posneg2,lst))
print("Negative Elements=",nslist)
#FilterEx2.py

even=lambda n : n>0 # Anonymous Function


odd=lambda x : x<0 # Anonymous Function

#main program
print("Enter List of values separated by space:")
lst=[int(val) for val in input().split()]

pslist=list(filter(even,lst))

nslist=tuple(filter(odd,lst))
print("Given List={}".format(lst))
print("Positive Elements={}".format(pslist))
print("Negative Elements={}".format(nslist))
=====================================================================

162
#FilterEx3.py

print("Enter List of values separated by space:")


lst=[int(val) for val in input().split()]
pslist=list(filter(lambda n: n>0 , lst))
nslist=tuple(filter(lambda x: x<0 , lst))
print("Given List={}".format(lst))
print("Positive Elements={}".format(pslist))
print("Negative Elements={}".format(nslist))

=============================================================

#FilterEx4.py

def uppercase(s):
return s.isupper()

def lowercase(s):
return s.islower()

def notlowerupper(k): # k=PYThon


return (not (k.isupper() or k.islower() ))

#main program
print("Enter List of Names separated by space:")
lst=[str(val) for val in input().split() ]
uppernames=list(filter(uppercase,lst))
lowernames=list(filter(lowercase,lst))
notloweruppernames=list(filter(notlowerupper,lst))
print("Given List=",lst)
print("Upper Case Names=",uppernames)
print("Lower Case Names=",lowernames)
print("Mixed Case Names=",notloweruppernames)

=====================================================================

#FilterEx5.py

uppercase= lambda s: s.isupper()

lowercase=lambda s: s.islower()

notlowerupper=lambda k: not (k.isupper() or k.islower() )

#main program
print("Enter List of Names separated by space:")
lst=[str(val) for val in input().split() ]
uppernames=list(filter(uppercase,lst))
lowernames=list(filter(lowercase,lst))
notloweruppernames=list(filter(notlowerupper,lst))
print("Given List=",lst)
print("Upper Case Names=",uppernames)
print("Lower Case Names=",lowernames)

163
print("Mixed Case Names=",notloweruppernames)

====================================
2) map()
====================================
=>map() is used for obtaining new Iterable object from existing
iterable object by applying old iterable element to the function.
=>In otherwords, map() is used for obtaining new list of elements from
existing existing list of elements by applying old list elements to
the function.

=>Syntax:- varname=map(FunctionName,Iterable_object)

=>here 'varname' is an object of type <class,map'> and we can convert


into any iteratable object by using type casting functions.
=>"FunctionName" represents either Normal function or anonymous
functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of map() is that " map() sends every element of
iterable object to the specified function, process it and returns the
modified value (result) and new list of elements will be obtained".
This process will be continued until all elements of Iterable_object
completed.

#Program demonstrating map() concept


#mapex1.py
def square(n):
return (n**2)

#main program
lst=[2,3,5,-4,-6,4,8]
obj=map(square,lst)
print("type of obj=",type(obj)) # type of obj= <class 'map'>
print("content of obj=",obj) # content of obj= <map object at
0x0000029B632902B0>
sqlist=list(obj)
print("Original List=",lst)
print("Square list=",sqlist)
=======================================================================

#Program demonstrating map() concept


#mapex2.py
square=lambda n: n**2

#main program
lst=[2,3,5,-4,-6,4,8]
sqlist=tuple(map(square,lst))
print("Original List=",lst)
print("Square list=",sqlist)

164
=======================================================================

#Program demonstrating map() concept


#mapex3.py
lst=[12,13,15,-14,-6,4,8]
sqlist=tuple(map(lambda x: x*x ,lst))
print("Original List=",lst)
print("Square list=",sqlist)

=======================================================================

#programming accepting list of values and update them with 2%---map()


#mapex4.py
def updatevalues(n):
return (n+n*(2/100) )

#main program
print("Enter list of values separated by space:")
lst=[int(val) for val in input().split()]
updatelist=list(map(updatevalues,lst))
print("Original List={}".format(lst))
print("Updated List={}".format(updatelist))

#programming accepting list of values and update them with 2%---map()


#mapex5.py
print("Enter list of values separated by space:")
lst=[int(val) for val in input().split()]
updatelist=list(map(lambda val:val+val*(2/100) , lst))
print("Original List={}".format(lst))
print("Updated List={}".format(updatelist))

=======================================================================

#programming for finding sum of two lists.


#mapex6.py
print("Enter list of values separated by space for first list:")
lst1=[int(val) for val in input().split()]
print("Enter list of values separated by space for second list:")
lst2=[int(val) for val in input().split()]
#find sum of tw lists
sumlist=list(map(lambda x,y:x+y , lst1,lst2))
print("List1 content=",lst1)
print("List2 content=",lst2)
print("Sum list=",sumlist)

=======================================================================

#programming for finding mul of two lists.


#mapex7.py
def sumop(x,y):
return (x*y)
print("Enter list of values separated by space for first list:")
lst1=[int(val) for val in input().split()]
print("Enter list of values separated by space for second list:")

165
lst2=[int(val) for val in input().split()]
#find sum of tw lists
mullist=list(map(sumop , lst1,lst2))
print("List1 content=",lst1)
print("List2 content=",lst2)
print("Mul list=",mullist)

=======================================================================

#example with filter() and map()


#mapfilterex.py
print("Enter list of values separated by space for first list:")
lst1=[int(val) for val in input().split()]
print("Given List=",lst1)
pssqlist=list(map(lambda n:n**2,list(filter(lambda n : n>0,lst1))))
print(pssqlist)
nssqlist=tuple(map(lambda n:n*n,list(filter(lambda n:n<0,lst1))))
print(nssqlist)

=======================================================================

#programming accepting list of values and update them with 2%---map()


#non_mapex.py
def updatevalues(obj):
uplist=[]
for val in obj:
res=val+val*(2/100)
uplist.append(res)
return uplist

#main program
print("Enter list of values separated by space:")
lst=[int(val) for val in input().split()]
updatedlist=updatevalues(lst)
print("Original List={}".format(lst))
print("Updated List={}".format(updatedlist))

=======================================================================

================================
reduce()
================================
=>reduce() is used for obtaining a single element / result from given
iterable object by applying to a function.
=>Syntax:-
varname=reduce(function-name,iterable-object)
=>here varname is an object of int, float,bool,complex,str only
=>The reduce() belongs to a pre-defined module called" functools".

Internal Flow of reduce()

step-1:- Initially ,reduce() selects First Two values of Iterable object


and place them in First var and Second var .
step-2:- The function-name(lambda or normal function) utilizes the values
of First var and Second var applied to the specified
logic and obtains the result.

166
Step-3:- reduce () places the result of function-name in First variable and
reduce()
selects the succeeding element of Iterable object and places
in second variable.
Step-4: repeat Step-2 and Step-3 until all elements completed in
Iterable object and returns the result of First Variable

#program for finding sum of list elements


#reduceex1.py
import functools
lst=[10,15,25,5,35,40]
res=functools.reduce(lambda a,b:a+b,lst)
print("Sum({})={}".format(lst,res))

==========================================================
#program for finding max and min from list of elements
#reduceex2.py
import functools
print("Enter List of Elements separated by space:")
lst=[int(val) for val in input().split()] # 10 20 5 35 -4 23 45 0
234
#define reduce() for max
big=functools.reduce(lambda a,b: a if a>b else b, lst)
small=functools.reduce(lambda a,b: a if a<b else b, lst)
print("big({})={}".format(lst,big))
print("small({})={}".format(lst,small))

====================================================================
#Program concatenating multiple words
#reduceex3.py
import functools
def concatop(x,y):

167
return(x+" "+y)

lst=["Python", "is","an","oop","lang","Developed","by","Rossum"]
line=functools.reduce(concatop,lst)
print("Line=",line)

====================================================================
#Program concatenating multiple words
#reduceex4.py
import functools
print("Enter list of words separated by space")
lst=[str(val) for val in input().split()]
line=functools.reduce(lambda x,y: x+" "+y,lst)
print("Given List=",lst)
print("Line=",line)
=====================================================================

#Program concatenating multiple words


#reduceex4.py
import functools
print("Enter List of Elements separated by space:")
lst=[int(val) for val in input().split()]
pnsum=functools.reduce(lambda x,y:x+y,list(map(lambda a: a**2,
list(filter(lambda x: x>0,lst)))))
nnsum=functools.reduce(lambda x,y:x+y,list(map(lambda a: a**2,
list(filter(lambda x: x<0,lst)))))
print("Possitive Num Squares Sum=",pnsum)
print("Negative Num Squares Sum=",nnsum)

=====================================================================
23-may-2022

=============================================
Modules in Python
=============================================
=>We know that Functions concept makes us 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 Modules:

=>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

168
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.

Examples: math cmath functools sys calendar os


re threading pickle random.......etc

=>Out of many pre-defined modules, in python programming one implicit


pre-defined module imported to every python program called "builtins" .

2) Programmer or user or custom-defined modules:

=>These modules are developed by Python Programmers and they are


avialable in Python Project and they are used by other python
programmers who are in project development to deal with common
requirements.
=>Examples:- aop mathsinfo etc

=================================================
Development of Programmer-Defined Module
=================================================
=>To develop Programmer-Defined Modules, we must use the following
steps

Step-1 : Define Variables (Global variables)


Step-2: Define Functions
Step-3: Define Classes

=>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 "filename.cpython-
310.pyc ".

Examples:

pycache <-----Folder
Name

aop.cpathon-310.pyc <-----------------
--Module Name
mathsinfo.cpython-310.pyc<--------------
Module Name

169
icici.cpython-310.pyc<
--Module Name

=================================================
Development of Programmer-Defined Module
=================================================
=>To develop Programmer-Defined Modules, we must use the following
steps

Step-1 : Define Variables (Global variables)


Step-2: Define Functions
Step-3: Define Classes

=>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 "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

=============================================
Modules
=============================================
Index

=>Purpose of Modules
=>Definition of Module
=>Types of Modules
a) Pre-defined Modules
b) Programmer-defined modules
=>Development Programmer-Defined Modules
=>Techniques for Re-Using the Modules
1) by using import statement (4 syntaxes
2) By using from ... import statement (3 syntaxes )
=>Programming Examples
=>Re-loding the Modules
=>Programming Examples

170
=======================================================================
24-may-2022

===============================================
Techniques for Re-Using the Modules
(OR)
Number of approaches to Re-use Modules
===============================================
=>We know that a module is a collection of Variables ,Functions and
Class Names.
=>The purpose of Module is that to re-use the Variables ,Functions and
Class Names of one
module in other part of the program.
=>To re-use Variables ,Functions and Class Names of module in other
part of the program, we have two approaches. They are
1) By using import statement.
2) By using from.....import statement.

1) By using import statement:

=>here import is a keyword


=>import statement is used for referfing or importing the variable
names, function names and
class names in current program.
=>import statement can be used in 4 ways. They are

Syntax1: import module name


=>This Syntax imports one module at a time in the current program
=>Example: import aop
import calendar
import icici

Syntax2: import module name1,module name2.....module name-n


=>This Syntax imports multiple modules at a time in the current
program
=>Example: import aop, calendar, icici

Syntax3: import module name as alias name


=>This Syntax imports one module at a time with alias name in the
current program
=>Example: import aop as a
import calendar as c
import icici as k

Syntax4: import module name1 as alias name,module name2 as


alias name.....module name-n
as alias name
=>This Syntax imports multiple modules with alias name at a time in
the current program
=>Example: import aop as a , calendar as c, icici as i

171
=>NOTE: After importing the modules in current program, we must access
the variable names, Function names and Class Names in current program
w.r.t Module Name or Alias Name

ModuleName.Variable Name
ModuleName.Function Name
ModuleName.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name
=======================================================================
2) By using from.....import statement.

---
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 names ."
=> 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.

Example: from calendar import month


from aop import sumop
from icici import pi,e,simpleint

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 icici import pi as p, e, 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.

Example: from calendar import *


from aop import *
from mathsinfo import *

172
=>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 alias names for
Variables Names, Function Names and Class Names but not for Module
Name".
===================================X===================================
=====

#Approach1.py--File Name
#This program want to re-use addop() of some other program
import aop
import calendar
aop.sumop(10,2) # Function Call
print(calendar.month(2022,5))

=======================================================================

#Approach2.py--File Name
#This program want to re-use addop() of some other program
import aop , calendar
aop.sumop(10,2) # Function Call
print(" ")
print(calendar.month(2022,5))

=======================================================================

#Approach3.py--File Name
#This program want to re-use addop() of some other program
import aop as a
import calendar as c
a.sumop(10,2) # Function Call
print(" ")
print(c.month(2022,5))
print(c.month(2022,11))

=======================================================================
#Approach4.py--File Name
#This program want to re-use addop() of some other program
import aop as a , calendar as c
a.sumop(10,2) # Function Call
print(" ")
print(c.month(2022,5))
print(" ")
print(c.month(2022,11))
print(" ")

=======================================================================

173
#Approach5.py--File Name
from aop import sumop
from calendar import month
sumop(10,2) # Function Call
print(month(2022,5))

=======================================================================

#Approach6.py--File Name
from aop import sumop as s
from calendar import month as m
from m1 import subject as s1
from m2 import subject as s2
from m1 import hello as h1
from m2 import hello as h2
s(10,2) # Function Call
print(m(2022,5))
print(s1)
print(s2)
h1("Rossum")
h2("McLinney")

=======================================================================

#Approach7.py--File Name
from aop import sumop as s
from calendar import month as m
from m1 import subject as s1,hello as h1
from m2 import subject as s2, hello as h2

s(10,2) # Function Call


print(m(2022,5))
print(s1)
h1("Rossum")
print(s2)
h2("McLinney")

=======================================================================

#Approach8.py--File Name
from icici import *
from m1 import *
print("val of pi=",pi)
print("val of e=",e)
simpleint()
print(" ")
print(subject)
hello("Rossum")

==================================================================

#aop.py---file name and treated as Module Name


#This program defines a function and reusing in same program
def sumop(a,b):
c=a+b

174
print("sum({},{})={}".format(a,b,c))
=======================================================================

#icici.py---file name and acts as module name


pi=3.14
e=2.71 # Here pi and e are called global variables

def simpleint():
p=float(input("Enter Principle Amnount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
#cal si
si=(p*t*r)/100
totamt=p+si
print("="*50)
print("Principle Amount:{}".format(p))
print("Time :{}".format(t))
print("Rate of Interest:{}".format(r))
print("-"*50)
print("Simple Interrest:{}".format(si))
print("Total Amount to pay:{}".format(totamt))
print("="*50)

=======================================================================

#m1.py--file name and module name


subject="PYTHON"
def hello(s):
print("Hi {} , Good Morning".format(s))

=======================================================================

#m2.py--file name and module name


subject="Data Science"
def hello(s):
print("Hi {} , Good Evening".format(s))

=======================================================================

#m1m2.py----main program
import m2 ,m1
print("Subject=",m1.subject)
print("Subject=",m2.subject)
print(" ")
m1.hello("Rossum")
m2.hello("Travis")

=======================================================================

#operations.py---File Name and acts as module name


def square(n):
print("Square({})={}".format(n,n**2))
def sqrt(n):

175
print("Sqrt({})={}".format(n,n**0.5))

=======================================================================

#operationsdemo.py--main program
from operations import square as s, sqrt as t
s(float(input("Enter a number for Square Cal:")))
t(float(input("\nEnter a number for Square Root Cal:")))

=======================================================================

==========================================
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().

176
===================================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)

====================================================================

#shares.py-----file name and acts as module name


def sharesinfo():
d={"IT":1500,"Phama":1400,"Auto":100,"Fin":105}
return d
===========================
#SharesDemo.py
import shares
import time
import importlib
def dispshares(d):
print("-"*50) print("\
tShareName\tShareValue")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("-"*50)

177
#main program
d=shares.sharesinfo()
dispshares(d)
print("i am going to sleep for 10 secs")
time.sleep(15)
print("i am coming out of sleep")
importlib.reload(shares) # Re-loading previously imported module
d=shares.sharesinfo()
dispshares(d)
print("i am going to sleep for 15 secs second time")
time.sleep(15)
print("i am coming out of sleep second time")
importlib.reload(shares) # Re-loading previously imported module
d=shares.sharesinfo()
dispshares(d)

=======================================================================

#aopmenu.py---file name and acts as module name


def aopmenu():
print("="*50) print("\
tArithmetic Operation")
print("="*50) print("\
t1.Addition") print("\
t2.Substraction") print("\
t3.Multiplication") print("\
t4.Division") print("\t5.Modulo
Div") print("\
t6.Exponentiation") print("\
t7.Exit") print("="*50)
=======================================================================

#aopoperation.py--file name and acts as module name


def readvalues(kvr):
a=float(input("Enter First Value for {}".format(kvr)))
b=float(input("Enter Second Value for {}".format(kvr)))
return a,b
def addop():
a,b=readvalues("Addition") print("sum({},
{})={}".format(a,b,a+b))
def subop():
a,b=readvalues("Subtract")
print("sub({},{})={}".format(a,b,a-b))

def mulop():
a,b=readvalues("Multiplication") print("mul({},
{})={}".format(a,b,a*b))
def divop():
a,b=readvalues("Division") print("Div({},
{})={}".format(a,b,a/b))
print("Floor Div({},{})={}".format(a,b,a//b))
def modop():
k,v=readvalues("Modulo Division") print("Mod({},
{})={}".format(k,v,k%v))

178
def expoop():
a=float(input("Enter Base:"))
b=float(input("Enter Power:")) print("pow({},
{})={}".format(a,b,a**b))

======================================================

#aopdemo.py
from aopmenu import aopmenu
import sys
from aopoperation import addop,subop,mulop,divop,modop,expoop
while(True):
aopmenu()
ch=int(input("Enter ur choice:"))
match(ch):
case 1:
addop()
case 2:
subop()
case 3:
mulop()
case 4:
divop()
case 5:
modop()
case 6:
expoop()
case 7:
print("Thx for using this program")
sys.exit()
case _: # default case block
print("Ur Selection of Operation is wrong-try
again")

=============================================
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.

=>The Modules concept is a collection of Variables, Functions and


classes and we can re-use the code across the Programs provided Module
name and main program present in same folder but unable to provide code
re-usability across the folders / drives / enviroments.

=>The Package Concept is a collection of Modules.


=>The purpose of Packages is that to provide code re-usability across
the folders / drives / enviroments.

179
=>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
aopmenu.py-----Module Name
aoperations.py---Module Name
runappl.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")

=>sys is pre-defined module


=>path is a pre-defined object / variable present in sys module
=>append() is pre-defined function present in path and is used for
locating the package name of python( specify the absolute path)

Example:

sys.path.append("E:\\KVR-PYTHON-7AM\\ACKAGES\\BANK")
(or) sys.path.append("E:\
KVR-PYTHON-7AM\ACKAGES\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-7AM/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

180
Var Value : E:\KVR-PYTHON-7AM\PACKAGES\BANK

The overall path


PYTHONPATH= E:\KVR-PYTHON-
11AM\PACKAGES\BANK

#icici.py---file name and acts as module name


pi=3.14
e=2.71 # Here pi and e are called global variables
def simpleint():
p=float(input("Enter Principle Amnount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
#cal si
si=(p*t*r)/100
totamt=p+si
print("="*50)
print("Principle Amount:{}".format(p))
print("Time :{}".format(t))
print("Rate of Interest:{}".format(r))
print("-"*50)
print("Simple Interrest:{}".format(si))
print("Total Amount to pay:{}".format(totamt))
print("="*50)

init .py
#multable.py--file name and acts as module name
def table():
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("="*50)
print("Mul Table for {}".format(n))
print("="*50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
else:
print("="*50)

========================================
random module
========================================
=>random one of pre-defined module present in python
=>The purpose of random is that "To generate random values in various
contexts".
=>random module contains the follwoing essential functions.
a) randrange()
b) randint()

181
c) random()
d) uniform()

e) choice()
f) shuffle()
g) sample()

===============================================================
a) randrange()

=>This function is used for generating random integer values between


specified limits.
Syntax1:- random.randrang(Value)
This syntax generates any random value between 0 to
Value-1

Syntax-2: random.rangerange(start,stop)
This syntax generates any random value between start to
stop-1

Examples:

>>> import random


>>> print(random.randrange(100,150))----133
>>> print(random.randrange(100,150))----121
>>> print(random.randrange(100,150))----139
>>> print(random.randrange(100,150))----143
>>> print(random.randrange(100,150))---106
>>> print(random.randrange(100,150))---133
>>> print(random.randrange(10))----5
>>> print(random.randrange(10))----9

#randrangeex.py
import random
for i in range(1,6):
print(random.randrange(10))
print(" ")
for i in range(1,6):
print(random.randrange(1000,1100))
print(" ")
================================X============================
b) randint():

=>Syntax:- random.radint(start,stop)
=>This syntax generates any random value between start to stop. Here
start and stop are inclusive.
Examples:

>>> print(random.randint(10,15))------10
>>> print(random.randint(10,15))-----13
>>> print(random.randint(10,15))----14
>>> print(random.randint(10,15))----11
>>> print(random.randint(10,15))----15

#randintex.py
import random
for i in range(1,6):
print(random.randint(10,20))

182
print(" ")
==============================X================================
c) random()

=>Syntax:- random.random()
=>This syntax generates floating point random values between 0.0 and
1.0 (Exlusive))
Examples:

>>> import random


>>> print(random.random())----------0.1623906138450063
>>> print(random.random())--------0.15382209709271966
>>> print(random.random())-------0.09542283007844476
>>> print(random.random())-----0.6134301633766425

#randomex.py
import random
lst=[]
for i in range(1,6):
lst.append("%0.2f" %random.random())
print(" ")
print("Content of lst={}".format(lst))
============================X=============================
d) uniform()

Syntax:- random.uniform(start,stop)
=>This generates random floting point values from start to stop-1
values
=>The values of start and stop can both Integer or floating point
values.
Examples:

>>> import random


>>> print(random.uniform(10,15))----------14.416746067678286
>>> print(random.uniform(10,15))----13.2420406264978
>>> print(random.uniform(10,15))-----11.716110933506432
>>> print(random.uniform(10,15))--------10.703499588966528
>>> print(random.uniform(10,15))-----11.306226559323017
>>> print(random.uniform(10.75,15.75))--------13.939787347170148
>>> print(random.uniform(10.75,15.75))----10.760428232717597

#uniformex.py
import random
lst=[]
for i in range(1,6):
lst.append(float("%0.2f" %random.uniform(10,15.5)))
print(" ")
print("Content of lst={}".format(lst))
===========================X================================
e) choice():

Syntax:- random.choice(Iterable_object)
=>This function obtains random values from Iterable_object.

EXAMPLES:

183
>>>
print(random.choice([10,20,30,40,50]),random.choice("PYTHON"),random.ch
oice(range(10,15)))---40 T 11
>>>
print(random.choice([10,20,30,40,50]),random.choice("PYTHON"),random.ch
oice(range(10,15)))----------30 P 12
>>>
print(random.choice([10,20,30,40,50]),random.choice("PYTHON"),random.ch
oice(range(10,15)))-----------40 N 12

#choiceex.py
import random
s="AaBRe#^%@8YuQLPau*&"
for i in range(1,6):

print(random.choice(s),random.choice(s),random.choice(s),random.choice(
s))
===========================X================================
f) shuffle():

=>This Function is used for re-organizing the elements of any mutable


object but not on immutable object.

Syntax:- random.shuffle(list)
=>We can shuffle the data of list but not other objects of Data Types
Examples:

>>> d={10:"cadburry",20:"kitkat",30:"malkybar", 40:"dairymilk"}


>>> print(d)---{10: 'cadburry', 20: 'kitkat', 30: 'malkybar', 40:
'dairymilk'}
>>> for k,v in d.items():
... print(k,"--",v)
...
10 -- cadburry
20 -- kitkat
30 -- malkybar
40 -- dairymilk
>>> import random
>>> print(random.shuffle(d))----Traceback (most recent call last):
File "<stdin>",
line 1, in <module>
File
"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\lib\random.p
y", line 394, in shuffle
x[i], x[j] =
x[j], x[i]
KeyError: 3
>>> s={10,20,30,40,50}
>>> print(random.shuffle(s))
Traceback (most recent call
last):
File "<stdin>", line 1, in
<module>
File
"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\lib\random.p
y", line 394, in shuffle
x[i], x[j] = x[j], x[i]

184
TypeError: 'set' object is
not subscriptable

>>> t=(10,20,30,40,50)
>>> print(random.shuffle(t))
Traceback (most recent call
last):
File "<stdin>", line 1, in
<module>
File
"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\lib\random.p
y", line 394, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object
does not support item assignment
>>> l=[10,20,30,40,50]
>>> print(random.shuffle(l))-----None
>>> print(l)-------------[30, 40, 50, 10, 20]
>>> random.shuffle(l)
>>> print(l)------------[40, 30, 10, 20, 50]
>>> random.shuffle(l)
>>> print(l)---------[40, 10, 50, 20, 30]
>>> random.shuffle(l)
>>> print(l)------------[30, 50, 20, 40, 10]

#shuffleex.py
import random as r
l=[10,"Python","Rossum",34.56,True]
for i in range(1,6):
r.shuffle(l)
print("content of l=",l)
===================================X============================
g) sample()

=>This Function is used for selecting random samples from any Iterable
object based on number of samples(+ve)
Syntax:- random.sample(iterable_object, k)
=>Here 'k' can be number of samples.

Examples:

>>> import random


>>> s="ABCabcERTYUertyu$%^&*#@!%^&ghjkiyl"
>>> print(random.sample(s,5))----------['A', '*', '^', 'j', 't']
>>> print(random.sample(s,5))---------['%', 'l', 'b', 'C', 'y']
>>> print(random.sample(s,5))----------['%', 'e', 'Y', 'j', 'u']
>>> print(random.sample(s,5))------['y', 'E', '&', '$', '#']
>>> print(random.sample(s,5))----------['j', '*', 't', '$', 'u']

#sampleex.py
import random
lst=[10,"Rossum","Python",34.56,True]
for i in range(1,6):
print(random.sample(lst,2))
================================X===========================

#randintex1.py
#generage 5, 4 digit random numbers

185
import random as r
for i in range(1,5):
print(r.randint(1000,9999))

=======================================================================

#randrangeex1.py
#generage 10, 3 digit random numbers
import random as r
for i in range(1,11):
print("SBI"+str(r.randrange(100,1000)))
=======================================================================
#randrangeex2.py
#generage 10, 3 digit random numbers
import random as r
for i in range(1,11):
print("SBI"+str(r.randrange(10)))
=======================================================================

#randrangeex3.py
#generage 10, 3 digit random numbers
import random as r
for i in range(1,11):
print("SBI"+str(r.randrange(10,50,5)))
=======================================================================

#randdomex.py
#generage 5, floating point random values between 0.0 to 1.0
(exclusive)
import random as r
for i in range(1,5):
print(round(r.random(),3))
=======================================================================

#uniformex.py
#generage 5, floating point random values based programmer choice
import random as r
for i in range(1,5):
print(r.uniform(1.5,2))
=======================================================================

#sir in passport office, I find some numbers come with 'c' series, some
with 'd' series randomly depend on category. how can they do it sir.
#passport.py
import random as r
for i in range(1,20):
ch1=r.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
ch2=r.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print("\tTS{}{}{}".format(ch1,ch2,r.randint(1000,2000)))
=======================================================================

#shuffleex.py
#generage 5 samples of list with shuflling
import random as r
l1=[10,20,30,"Python","Data Sci",34.56,True]
for i in range(1,6):
r.shuffle(l1)

186
print(l1)
=======================================================================

#sampleex.py
#generage 5, capcha codes
import random as r
s="ABCDEFGHI2345679@#$%^&*abcdefght&*%$#"
for i in range(1,6):
for val in r.sample(s,4):
print(val,end=" ")
print()
=======================================================================

#sampleex1.py
#generage 5, capcha codes
import random as r
s="ABCDEFGHI2345679@#$%^&*abcdefght&*%$#"
for i in range(1,6):
print(r.sample(s,5))

============================================
Exception Handling
============================================
=>Purpose of Exception Handling
=>What is meant by Exception?
=>What is meant by Exception Handling?
=>Types of Errors
a) Compile Time Errors
b) Logical Errors
c) Runtime Errors
=> Building Points to remember in Exception Handling
=>Types of Exceptions
a) Pre-defined or Built-in Exceptions
b) Programmer/ Use/ Custom-Defined Exceptions
=>Keywords for Handling Exceptions
a) try
b) except
c) else
d) finally
e) raise
=>Syntax for Handling the Exceptions
=>Explanation for the keywords for Handling the Exceptions
=>Programing Examples

=>Steps for Development of Programmer-Defined Exceptions.


=>Programming Examples
=>ATM Case Study
=================================X===================================

187
===================================================
Exception Handling
===================================================
=>The purpose of Exception Handling is that "To Build Robust
(Strong) Applications".

=>In Real Time, to develop any project, we must choose a


language. By using a particular language, we develop, compile
and execute various programs. During this process of
development, compilation and execution, we get 3 types of
errors. They are
1. Compile Time Errors
2. Logical Errors
3. Runtime Errors

1. Compile Time Errors

=>Compile Time Errors are those, which are occuring during


Compilation Process(.py-->.pyc)
=>Compile Time Errors occurs due to Syntax are not followed.
=>Compile Time Errors must be solved by Programmer during
development time.

2. Logical Errors

=>Logical Errors are those, which are occuring during


Runtime or execution time.
=>Logical Errors occurs due to wrong representation of logics.
=>Logical Errors always gives Wrong Results.
=>Logical Errors must be solved by Programmer during development time.

3. Runtime Errors------Forecasting Knowledge

=>Runtime Errors are those, which are occuring during


Runtime or execution time.
=>Runtime Errors occurs due to Invalid or wrong Input entered by En-
User /
Application
user.
=>To handlle Runtime Errors, Programmer must Forecasting for addressing
Implemetation
Errors.
=====================================X===============================

188
=================================================
Bulding Points to remember in Exception Handling
=================================================
1. When the application user or end user enters Invalid or
wrong input then we get Runtime
Error.
2. By default Runtime Errors generates Technical Error
Messages and these messages

189
understandable by Programmers but not by end-users.
Industry recommended to generate user-frinedly error meassages
by using exception handling.
3. Def. of Exception:- Every Runtime Error is called Exception.
(Invalid Input---->Runtime Error-----
>Exception)
4. Every Valid Input gives Result and Every Invalid
Input gives Exception.
5. All exceptions by default gives Technical Error Messages
6. Def. of Exception Handling: The Process of converting
Technical Error Messages into
User-Friendly Error
Messages.

7. When an exception occurs in Python Program, Internally 3


steps takes place.
a) PVM Stops the program execution abnormally
b) PVM Comes out of Program flow completely
c) PVM generates Technical Error Messages by
default
.
8. To do Step-(a), Step-(b) and Step-(c), Internally PVM
creates an object of an appropriate
exception class. In general for every exception(Invalid
Input) there an exception class for creating an
object(InvalidInput----
>Runtime Error--->Exception-->object-->exception class)
9. Hence When an exception occurs in Python Program,
Internally PVM creates an object of
appropriate exception class.

10. Hence every exception is considered as an object.

===============================================
Types of Exceptions in python
===============================================
=>In Python Programming, we have two types of exceptions. They are
1) Pre-defined or Built-in Exceptions
2) Programmer / User / Custom-Defined Exceptions.

1) Pre-defined or Built-in Exceptions:


190
=>These exceptions developed by Python Language developers and
they are available in Python Software and used by Python
Language Programmers for deal with Universal Problems.
=>Some of the universal Problems are
1. Division by Zero Problems ( ZeroDivisionError )
2. conversion of Invalid Numbers formats ( ValueError)
3. Type number of parameters to the function (TypeError)
4. Wrong Index Value ( IndexError)
5. Module not foud (MouduleNotFoundError)
.......etc

2) Programmer / User / Custom-Defined Exceptions.

191
=>These exceptions developed by Python Programmers developers
and they are available in Python Project and used by Other
Python Programmers for deal with Common Problems.

=>Some of the common problems are


a) Attempting to enter wrong ATM PIN
b) Attempting to wrong User name and password
c) Try to withdraw more amount than existing account bal
d) attempting to enter wrong pattern.etc
================================X=====================================

===============================================
Handling the Exception=>Handling the Exceptions are nothing but
converting Technical Error Messages into User-Friendly Error Messages.
=>In Python Programming, for handling the exceptions, we have 5
keywords. 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 statements
generating User-Friendly Error
Messages. except <exception-class-
name-2>:
Block of statements
generating User-Friendly Error Messages.

except <exception-class-name-n>:
Block of statements
generating User-Friendly Error
Messages. else:
Block of statements
recommended to
generates results
finally:
block of statements
executed compulsorily.

#Program for accepting two integer values from KBD and


find their division
#Div1.py
192
s1=input("Enter Value First Value:")
s2=input("Enter Value Second
Value:") #convert s1 and s2 into
int

a=int(s1) #
b=int(s2)
c=a/b
print("Val of a=",a)
print("Val of
b=",b)
print("Div=",c)

#Program for accepting two integer values from KBD and


find their division
#Div2.p
y try:
s1=input("Enter Value First
Value:") s2=input("Enter Value
Second Value:") #convert s1 and
s2 into int type a=int(s1)
b=int(s
2)
c=a/b
except ZeroDivisionError:
print("\nDON'T ENTER ZERO FOR DEN...")
except ValueError:
print("\nDon't enter strs, symbols and alpha-numerics")
else
: print("="*50)
print("Val of
a=",a) print("Val
of b=",b)
print("Div=",c)
print("="*50)
finally:
print("i am from finally block")
===============================================================
Explanation related to the keywords in Handling the Exceptions
===============================================================
1. try block

=>It is the block, in which we write block of statements


generating exceptions. In Otherwords
what are all the statements are generating the exceptions
those statements must be written within try block and try
block is called exception monitering block.
=>When an exception in try block then PVM comes out of try
block and PVM executes
appropriate except block.

=>After executing appropriate except block, PVM never goes to


try block to execute rest of
193
the statements in try block.
=>Every try block must be immediately followed by except
block(Otherwise we get error)
=>Every try block must contain atleast one except block and
recommended to write multiple
except blocks for generating multiple user-friendly error
messages.

194
2. except block
=>It is the block, in which we write block of statements
generating User-Friendly Error
Messages. In Other words, except block will supress the
technical error messages and generates user-friendly error
messages and hence except is called exception processing block
.
NOTE: Handling Exception=try block + except block.
=>except block will execute when there is exception in try
block.
=>Even we write multiple except blocks, at any point of time
PVM will execute an appropriate
except block only.
=>The place of writing except block is after try block and
before else block (if we write )

3. else block

=>It is the block in which we Block of statements


recommended to generates results.
=>else block will execute when there is no exception in try block
=>writing else block is optional
=>The place of writing else block is after writing except
block and before finally block (if we
write)
4. finally block

=>It is the block, in which we write block of statements ,


which will relinquish (release/ close /
give-up / cleaning up ) the resources ( Files,
DataBasees) which are obtained in try block.
=>finally block will execute compulsorily( if we write).
=>Writing finally block is optional
=>The place of writing finally is after else block (if
else block present).
=================================x=====================================

=====================================================
Various forms of except blocks
=====================================================
=>We know that except block will supress the technical error
messages and generates user-friendly error messages and hence
except is called exception processing block .
=>We can use except block in various ways and shown bellow.,

=>Syntax-1: This Syntax handle one specific exception at a time

try:
Block of
statements
195
g nerating
e exceptions
except <exception-class-name-1>:
Block of statements
generating User-Friendly Error Messages.

196
=>Syntax-2: This Syntax handles multiple specific exceptions
at a time
This facility is called multi exception handling
block

try:
Block of
statements
generating
exceptions
except (exception-class-name-1,exception-
class-name- 2,...exception-class-name-n):
Block of statements
generating User-Friendly Error Messages for all specific
exceptions.

=>Syntax-3: This Syntax handle one specific exception at a


time with alias name
This syntax displays on error messages occurs
due to exception occurence.

try:
Block of
statements
generating
exceptions
except <exception-class-name-1> as alias
name: print(alias name)

=>Syntax-4: This Syntax handles all kinds of exceptions

try:
Block of
statements
generating
exceptions
except : # default except block and written at
last block of stmts

#Program for accepting two integer values from KBD and


197
find their division
#Div2.p
y try:
s1=input("Enter Value First
Value:") s2=input("Enter Value
Second Value:") #convert s1 and
s2 into int type a=int(s1)
b=int(s
2)
c=a/b
except ZeroDivisionError:
print("\nDON'T ENTER ZERO FOR DEN...")
except ValueError:

198
print("\nDon't enter strs, symbols and alpha-numerics")
else
: print("="*50)
print("Val of
a=",a) print("Val
of b=",b)
print("Div=",c)
print("="*50)
finally:
print("i am from finally block")

=======================================================================

#Program for accepting two integer values from KBD and


find their division
#Div3.p
y try:
s1=input("Enter Value First
Value:") s2=input("Enter Value
Second Value:") #convert s1 and
s2 into int type a=int(s1)
b=int(s
2)
c=a/b
except (ZeroDivisionError,ValueError):
print("\nDON'T ENTER ZERO FOR
DEN...")
print("\nDon't enter strs, symbols and alpha-numerics")
else
: print("="*50)
print("Val of
a=",a) print("Val
of b=",b)
print("Div=",c)
print("="*50)
finally:
print("i am from finally block")
#Program for accepting two integer values from KBD and
find their division
#Div4.p
y try:
s1=input("Enter Value First
Value:") s2=input("Enter Value
Second Value:") #convert s1 and
s2 into int type a=int(s1)
b=int(s
2)
c=a/b
except ZeroDivisionError as z:
print(z) # division by
zero
except ValueError as hyd:
print(hyd) # invalid literal for int() with base 10:
else
: print("="*50)
print("Val of
199
a ,a) print("Val of
= b=",b)
" print("Div=",c)
print("="*50)
finally:
print("i am from finally block")

=======================================================================

200
#Program for accepting two integer values from KBD and
find their division
#Div5.p
y try:
s1=input("Enter Value First
Value:") s2=input("Enter Value
Second Value:") #convert s1 and
s2 into int type a=int(s1)
b=int(s
2)
c=a/b
except :
print("Some went wrong")
else
: print("="*50)
print("Val of
a=",a) print("Val
of b=",b)
print("Div=",c)
print("="*50)
finally:
print("i am from finally block")

=======================================================================

#Program for accepting two integer values from KBD and


find their division
#Div6.p
y try:
s1=input("Enter Value First
Value:") s2=input("Enter Value
Second Value:") #convert s1 and
s2 into int type a=int(s1)
b=int(s2
) c=a/b
s="PYTHO
N"
print(s[10])
except
ZeroDivisionError :
print("\nDON'T ENTER ZERO FOR DEN...")
except ValueError :
print("\nDon't enter strs, symbols and alpha-
numerics") except IndexError: # default except block---write
always at last
print("Plx chech the index ")
except : # default except block---write always at
last print("Some went wrong")
else
: print("="*50)
print("Val of
a=",a) print("Val
of b=",b)
print("Div=",c)
print("="*50)
finally:
201
print("i am from finally block")

=======================================================================

==============================================================
Development of Programmer / User / Custom-Defined Exceptions.

202
==============================================================
=>These exceptions developed by Python Programmers and they
are available in Python Project and used by Other Python
Programmers for deal w
=>Some of the common problems are
a) Attempting to enter wrong ATM PIN
b) Attempting to enter wrong User name and password
c) Try to withdraw more amount than existing account bal
d) attempting to enter wrong pattern.etc
=>If an exception occurs then PVM creates an object of an
appropriate exception class. If the exception class presents
in Python API then it is called Pre-defined exception class.
If the exception class not present in Python API then Python
Programmer must develop our own exception class and it is
called Programmer-defined Exception class.

Steps for Developing Programmer-defined Exception class:

1) Choose the Programmer-Defined Class Name.


2) The Programmer-Defined Class Name must inherit from
Exception or BaseException.
(Here Exception or BaseException are pre-defined super
classes for all types of exceptions and they provides
exception handling properties to its sub classes). Hence the
programmer-defined class is called Programmer-Defined
exception sub Class .
3) we must save the above development on some file name name
with an extension .py

Examples: atm.py------(3)----File Name and Acts as Module Name


(1) (2)
class PinError(Exception):pass

Example: login.py------(3)----File Name and Acts as


Module Name
(1) (2)
class LogincError(Exception):pass
==================================X===================================
Number of Phases required for Developing Programmer-defined
exception based Application.
=======================================================================
=====
Phases:
1) Development of programmer-defined exception class
2) Hitting or raising the programmer-defined exception
clas
s 3) Handling the programmer-defined exception class

203
1) Development of programmer-defined exception class

#development of Programmer-defined exception class which works


like ZeroDivisionError

204
#vspark.py----File Name and acts as Module Name (3)
# (1) (2)
class vsparkDivisionError(Exception):pass

2) Hitting or raising the programmer-defined exception class

#div.py--file name and acts as


module name
from vspark import
vsaprkDivisionError
def division(a,b):
if(b==0):
raise vsaprkDivisionError # hitting or
generating programmer-defined exceptiuons.
else:
c=a/b
return c

# Here division(a,b) is common function can be used any


programmer for cal division of two numbers--Phase-2

3) Handling the programmer-defined exception class

#This program will handle the programmer-defined


exceptions #divisiondemo.py

from div import division


from vspark import
vsparkDivisionError
a=int(input("Enter First
Value:"))
b=int(input("Enter Second
Value:"))
try:
result=division(a,b) # Function
Call except vsparkDivisionError:
print("\nDon't enter Zero for Den...")
else:
print("Div=",result)
finally:
print("i am from finally block")

205
#development of Programmer-defined exception class which works like
ZeroDivisionError
#kvr.py----File Name and acts as Module Name (3)
# (1) (2)
class KvrDivisionError(Exception):pass

#div.py--file name and acts as


module name from kvr import
KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError # hitting or
generating programmer-defined exceptiuons.
else:
c=a/b
return c

# Here division(a,b) is common function can be used any


programmer for cal division of two numbers--Phase-I

#This program will handle the programmer-defined


exceptions #divisiondemo.py
from div import division
from kvr import
KvrDivisionError try:
a=int(input("Enter First Value:"))# ValueError
b=int(input("Enter Second Value:")) # ValueError
result=division(a,b) # Function Call--raising
206
KvrDivisionError
except KvrDivisionError:

207
print("\nDon't enter Zero for
Den...") except ValueError:
print("\nDon't enter strs,symbols and alpha-
numeric") except :
print("Some Thing went wrong")
else:
print("Div=",result)
finally:
print("i am from finally block")

#Phase-1---development programmer-defined
exceptions #MulExcept.py----File Name and
acts as module name class
NegativeNumberError(Exception):pass
class ZeroNumberError(BaseException):pass

#Phase-2 This program generates mul table and hit the


exceptions if required.
#multable.py----file name and acts as module name
from MulExcept import
ZeroNumberError,NegativeNumberError def
table(n):
if(n==0):
raise
ZeroNumberError
elif(n<0):
raise
NegativeNumberError
elif(n>0):
print("="*50)
print("Mul Table for :
{}".format(n)) print("="*50)
for i in range(1,11):
print("\t{} x
{}={}".format(n,i,n*i)) print("="*50)

#Phase-3--main program for accepting the input from KBD and


handling the exception if required.
#MulDemo.py
from multable import table
from MulExcept import
ZeroNumberError,NegativeNumberError try:
n=int(input("Enter a
number:")) table(n) #
Function Call
except ZeroNumberError:
print("\nDon't enter zero for Mul
table:") except NegativeNumberError:
print("\n-Ve Numbers does not contain Mul
Table:") except ValueError:
208
print("\nDon't enter strs, symbols and alpha-
numerics:") finally:
print("\ni am from finally block:")

209
#atmmenu.py--file name and acts as
module name def menu():
print("-"*50)
print("\tATM
Operations")
print("-"*50)
print("\t1. Deposit")
print("\t2.
WithDraw") print("\
t3. Bal Enq")
print("\t4. Exit")
print("-"*50)

#bankexcept.py--file name and acts as


module name class
DepositError(Exception):pass
class WithdrawError(Exception):pass
class InSuffFundError(BaseException):pass

#atmoperations.py---file name and acts as module name


from bankexcept import DepositError,WithdrawError,
InSuffFundError bal=500.00
def deposit():
damt=float(input("Enter How much u want to Deposit:")) #
ValueError
if(damt<=0):
raise DepositError
else
: global bal
bal=bal+da
mt
print("Ur Account XXXXX123 Credited with
INR:{}".format(damt))
print("Now Ur Current Bal INR:{}".format(bal))

def withdraw():
global bal
wamt=float(input("Enter How much u want to Withdraw:")) #
ValueError
if(wamt<=0):
raise
WithdrawError
elif((wamt+500)>bal):
raise InSuffFundError
else
: bal=bal-wamt
print("Ur Account XXXXX123 Debited with
INR:{}".format(wamt))
print("Now ur Current Bal INR:{}".format(bal))

def balenq():
print("Current Bal in Ur Account INR:
{}".format(bal)) #atmdemo.py--MAIN PROGRAM
import sys
from atmmenu import menu
from atmoperations import deposit,withdraw,balenq
210
from bankexcept import DepositError,WithdrawError,
InSuffFundError while(True):
try:
menu()
ch=int(input("Enter Ur Choice:"))

211
match(ch):
case
1: try
: deposit()
except ValueError:
print("\nDon't try to deposit
strs,symbols and alpha-
numerics")
except DepositError:
print("\tDon't try to deposit Zero
or -ve
Numbers") case
2: try
: withdraw()
except ValueError:
print("\nDon't try to withdraw
strs,symbols and alpha-
numerics")
except WithdrawError:
print("\tDon't try to withdraw Zero
or -ve
Numbers") except
InSuffFundError:
print("\nUr Account does not
have
suff . Funds--read Python Notes")
case 3:
balenq()
case
print("Thx for using this
program") sys.exit()
4:
try print("Ur Selection of operation is wrong-
again")
case

_:
except ValueError:
print("Ur Choice should not be strs, symbols and alpha-
numerics")

212
=================================================
raise key word
=================================================
=>raise keyword is used for hitting / raising /
generating the exception provided some condition must be
satisfied.

213
=>raise keyword always used inside of Function Definition only.
=>PVM uses raise keyword implicitly for pre-defined Exception
where as Programmer makes the PVM use raise keyword explicitly
for Hitting or Generating Programmer-defined Exceptions.

=>Syntax:- if (Test Cond):


raise <exception-class-name>

Examples:
from kvr import
KvrDivisionError def
division(a,b):
if(b==0):
raise KvrDivisionError
else:
return (a/b)

214
=================================================
Files in Python
OR
Stream Handling in Python

215
=================================================
Index

=>Purpose of Files
=>Types of Applications in the context of Files
a) Non-Persistant Applications
b) Persistant Applications
=>Def. of File
=>Def. of Stream
=>Operations on Files
a) Write Operation
b) Read Operation
=>Steps for Write Operation
=>Steps for Read Operation
=>Types of Files
a) Text Files
b) Binary Files
=>File Opening Modes
1) r
2) w
3) a
4) r+
5) w+
6) a+
7) x
=>Syntax for Opening Files
a) open()
b) with open()
=>Programming Examples

=>Pickling and Un-Pickling (Object Serialization and Object De-


Serialization)
=>pickle module explanation
=>Implementation of Pickling and Un-Pickling
=>Programming Examples

=>os module
=>Working with CSV files
=>Programming Examples
====================================X==================================

=================================================
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

216
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.

=>We know that Data stored in Main Memory is temporary.


=>In Persistant Applications development, we read the data from
Keyboard , stored in main memory(RAM) in the form objects, processed
and whose results stored Permanently.
=>In Industry, we have two ways two store the data Permanently. They
are
1) By using Files
2) By Using DataBase Softwares ( Oracle, MySQL,
MongoDB, DB2, PostgreySQL, SQL
=================================x====================================

=================================================
Files in Python
OR
Stream Handling in Python
=================================================
=>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.

=>Def.of File:

=>A File is a Collection of Records


=>A File Name is always considered as named location in Secondary
Memory(HDD).
=>All files always resides in Secondary Memory.

Def. of Stream:

=>The flow of data between main memory and file of secondary memory is
called stream .

217
==================================================
Operations on Files
==================================================
=>On Files, we can perform two types of Operations. They are
1. Write Operation
2. Read Operation

1. Write Operation:

=>The purpose of Write Operation is that " To transfer temporary data


(object data) of main memory into the file of Secondary Memory".
=>To perform Write Operation, we use the following Steps.

1. Choose the File Name


2. Open the file in write mode
3. Perform Cycle of write Operations

218
=>While we are performing write Operations, we get the following
Exceptions.
a) FileExistError
b) OSError

2. Read Operation:

=>The purpose of Read Operation is that "To read the data / record from
the file of secondary Memory into the object of main memory."
=>To perform Read Operation, we use the following Steps.
1. Choose the file name
2. Open the file in read mode
3. Perform Cycle of Read Operations
=>While we are performing read Operation, we get the following
Exceptions.
a) FileNotFoundError
b) EOFError
===============================X=======================================

================================================
File Opening Modes
================================================
=>To do any of operations on the files, we must open the files in
appropriate mode. They are
1. r
2. w
3. a
4. r+
5. w+
6. a+
7. x

1. r

=>This mode is used for opening the file Read Mode and we read the data
only from file.
=>It is one of the deafult mode.
=>When we open the file in 'r' mode and if that file does not exist in
secondary memory then
we get FileNotFoundError.

2. w

=>This is always creates the file and opens in write mode


=>If the file already exist and if we open the file in 'w' mode then
the existing data of the file
OVERLAPPED( REPLACED ) with New Data.

219
3. a:

=>This is always creates the file and opens in write mode


=>If the file already exist and if we open the file in 'a' mode then
the then the existing data of the file APPENDED (writing at end)
with New Data.

4. r+

=>This mode is used for opening the file in Read Mode and First
Performs read operation and later we can perform Write Operation also.
=>When we open the file in 'r+' mode and if that file does not exist
in secondary memory then
we get FileNotFoundError and if we attempt read the data beyand the
file data then we get EOFError.

5. w+

=>This is always creates the file and opens in write mode


=>If the file already exist and if we open the file in 'w' mode then
the existing data of the file
OVERLAPPED( REPLACED ) with New Data and later we can also perform
Read Operation.
=>If we open the file in w+ mode then there is possibility of occuring
OSError

6. a+

=>This is always creates the file and opens in write mode and we can
First Write Operation ands later we can also perform Read Operastion.
=>If the file already exist and if we open the file in 'a+' mode then
the then the existing data of the file APPENDED (writing at end)
with New Data and we can we can also perform Read Operastion.

7. x

=>This mode is used for opening the file in eXclusively in write mode
and we can perform write operations only.
=>If we open the existing file in 'x' mode then we get FileExistError

220
================================================
Number of approaches to open the files
================================================
=>To perform any operations on files, along with File Mode and File
Name, we must we to approaches to open the files. They are
1) By using open()
2) By Using " with open() "

1) By using open()

Syntax: varname=open("FileName","File Mode")

Explanation:

=>Varname(object) is treated as file pointer and whose type is


<class,TextIOWrapper>
=>open() is a pre-defined function present in builtins module and it is
used for opening the in
specifed file mode.
=>"FileName" is of the file and it exist in secondary memory.
=>"File Mode" can be either r,w,a,r+,w+,a+,or x (any one)
=>When we open the file with open() then It is mandatory to close the
file by using close() and this is called Manual Closing File. open()
does not provide auto-closable property.

2) By Using " with open() "

Syntax:-
with open("FileName","File Mode") as VarName:

Block of Statements--Performs File


Operations

Other Statements in Program

Explanation:

=>"with" and "as" are the Keywords


=>Varname(object) is treated as file pointer and whose type is
<class,TextIOWrapper>
=>open() is a pre-defined function present in builtins module and it is
used for opening the in
specifed file mode.
=>"FileName" is of the file and it exist in secondary memory.

221
=>"File Mode" can be either r,w,a,r+,w+,a+,or x (any one)
=>The advantage of "with open() " is that "It Provides auto-closability
of file"
=>In Otherwords, as long as PVM executes the statements which are
written inside of "with open()" indentation then file is in active
state. Once PVM comes out of "with open()" indentation then PVM closes
the file autromatically.

#Program for opening the file name "hyd.data" in read mode--"r"


#FileOpenEx1.py
try:
fp=open("hyd.data","r")
except FileNotFoundError:
print("\nFile does not exist")
else:
print("Type of fp obj=",type(fp))
# Type of fp obj= <class
'_io.TextIOWrapper'>
print("File Opened in Read Mode Successfully")
print("Name of of the file=",fp.name)
print("File Mode=",fp.mode)
print("can we read? : ",fp.readable() )
print("can we write? : ",fp.writable() )
print("if file closed in line-14 : ",fp.closed )
finally:
print("\nI am from finally block")
fp.close() # manual closing of files
print("if file closed in line-18 : ",fp.closed )

#Program for opening the file name "hyd.data" in write mode--"w"


#FileOpenEx2.py
kvr=open("hyd.data","w") print("\
nType of kvr obj=",type(kvr))
print("File Created and opened in write mode successfully")

#Program for opening the file name "hyd.data" in read mode--"r"


#FileOpenEx3.py
try:
with open("hyd.data","r") as fp:
print("\nType of fp obj=",type(fp)) # Type of fp obj=
<class '_io.TextIOWrapper'>
print("File Opened in Read Mode Successfully")
print("Name of of the file=",fp.name)
print("File Mode=",fp.mode)
print("can we read? : ",fp.readable() )
print("can we write? : ",fp.writable() )
print("if file closed in line-11 within 'with open()' :
",fp.closed ) # False
print("\ni am out-of 'with open()' indentation")
print("if file closed in line-13 within 'with open()' :
",fp.closed ) # True

222
except FileNotFoundError: print("\
nFile does not exist")

#Program for opening the file name "hyd.data" in varaious modes mode--
#FileOpenEx4.py
with open("hyd.data","a+") as fp:
print("\nType of fp obj=",type(fp)) # Type of fp obj= <class
'_io.TextIOWrapper'>
print("File Opened in write Mode Successfully")
print("Name of of the file=",fp.name)
print("File Mode=",fp.mode)
print("can we read? : ",fp.readable() )
print("can we write? : ",fp.writable() )

#Program for opening the file name "hyd.data" in varaious modes mode--
#FileOpenEx5.py
try:
with open("kvr.data","x") as fp:
print("\nType of fp obj=",type(fp)) # Type of fp obj=
<class '_io.TextIOWrapper'>
print("File Opened in x Mode Successfully")
print("Name of of the file=",fp.name)
print("File Mode=",fp.mode)
print("can we read? : ",fp.readable() )
print("can we write? : ",fp.writable() )
except FileExistsError:
print("File alerady exist:")

==============================================
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: filepointer.write(str data)


=>This function is used for writing any type of data to file in the for
str.
=>If we have non-str data then convert into str type and then write it
to the file.

2) writelines():

=>Syntax: filepointer.writelines(str data)

223
=>This function is used for writing any type of Iterable object data to
file in the for str.
=>If we have non-str data then convert into str type and then write it
to the file.
================================x======================================
===

=======================================
Reading the data from the file
=======================================
=>To read the data from the file, we have 4 pre-defined functions
present in File Pointer object. They are
1. read()
2. read(no.of chars)
3. readline()
4. readlines()

1. read():

=>This function is used for reading entire content of the file in the
form of str.
=>Syntax:- varname=filepointer.read()
=>here varname is an object of type <class, str>
Example: FileReadEx1.py

2) read(no.of chars)

=>This function is used for reading specified number of chars from th


given file.
=>In the file, The data always organized in the form Indices
Examples:- FileReadEx2.py

3) readline()

=>This function is used for reading One Line at a time from the file in
the form of str.
=>Syntax: varname=filepointer.readline()
=>here varname is an object of type <class, str>
Examples:- FileReadEx3.py

4) readlines()

=>This function is used for reading all Lines at a time from the file
in the form of list .
=>Syntax: listobj=filepointer.readlines()
=>here listobj is an object of type <class, list>
Examples:- FileReadEx4.py
====================================X==================================
====

224
#Programming for demonstrating writing and appending the data to the
file---write()
#FileWriteEx1.py
with open("addr1.data","a") as fp:
fp.write("Dennis Ricthe\n")
fp.write("13-41 Sea Side\n")
fp.write("Bell Labs\n")
fp.write("USAQ\n")
print("Data written to the file--verify")

=======================================================================
=
#Programming for demonstrating writing and appending the data to the
file--writelines()
#FileWriteEx2.py
d={10:"Apple",20:"Mango",30:"Kiwi"}
with open("addr2.data","a") as fp:
fp.writelines(str(d )+"\n")
print("Data written to the file--verify")

#Programming for demonstrating reading the data from the file--read()


#FileReadEx1.py
try:
with open("D:\\ampt//addr2.data","r") as fp:
filedata=fp.read()
print(filedata)
except FileNotFoundError:
print("File does not exist")

#Programming for demonstrating reading the data from the file--


read(no.of chars)
#FileReadEx2.py
try:
with open("addr1.data","r") as fp:
print("Initital Index of fp=",fp.tell()) # 0
filedata=fp.read(5)
print("File data=", filedata)
print("Now Index of fp=",fp.tell()) # 5
filedata=fp.read(9)
print("File data=", filedata)
print("Now Index of fp=",fp.tell()) # 15
filedata=fp.read()
print("File data=", filedata)
print("Now Index of fp=",fp.tell()) # 186
fp.seek(0)
print("Now Index of fp after seek()=",fp.tell()) # 0
filedata=fp.read(14)
print("File data=", filedata)
print("Now Index of fp=",fp.tell()) #
except FileNotFoundError:
print("File does not exist")

225
#Programming for demonstrating reading the data from the file--
readline()
#FileReadEx3.py
try:
with open("addr1.data","r") as fp:
filedata=fp.readline()
print("File Data=",filedata)
filedata=fp.readline()
print("File Data=",filedata)
filedata=fp.readline()
print("File Data=",filedata)
filedata=fp.readline()
print("File Data=",filedata)
filedata=fp.read()
print("File Data=",filedata)
except FileNotFoundError:
print("File does not exist")

#Programming for demonstrating reading the data from the file--


readlines()
#FileReadEx4.py
try:
with open("hyd.data","r") as fp:
filedata=fp.readlines()
for line in filedata:
print(line,end="")
except FileNotFoundError:
print("File does not exist")

#Program for reading data from KBD and write it to the file
#DynamicWriteEx.py
import sys
with open("hyd.data","a") as fp:
print("\nEnter the data dynamically from KBD to stop press @:")
while(True):
kbdata=input()
if(kbdata=="@"):
sys.exit()
else:
fp.write(kbdata+"\n")

226
#Program for finding number of lines, words and chars from any file
#LineWordsChars.py
fname=input("Enter any file name:")
try:
nl=0
nw=0
nc=0
with open(fname) as fp:
lines=fp.readlines()
for line in lines:
print(line,end="")
nl=nl+1
nw=nw+len(line.split())
nc=nc+len(line)
else:
print()
print("="*50)
print("Number of Lines=",nl)
print("Number of Words=",nw)
print("Number of Chars=",nc)
print("="*50)

except FileNotFoundError:
print("File does not exist")

=======================================================================

#Program for copying the content of one file(Source File) into another
file (Destination File)
#FileCopy.py
sfile=input("Enter Source
File Name:") try:
with open(sfile) as fp1: # Opening the Source File in r mode
dfile=input("Enter Destination File:")
with open(dfile,"a") as fp2: # Opening the Destination
File in 'a' mode
filedata=fp1.read() # Reading from Source File
fp2.write(filedata) # Writing the data to
destrination File
print("Source File Data Copied into Dest. File")
except FileNotFoundError:
print("Source File Does not exist")

=======================================================================

#Program for copying the one image(Source File) into another file
(Destination File) contains an image
#ImageCopy.py
sfile=input("Enter Source File Name:")
try:
with open(sfile,"rb") as fp1: # Opening the Source File in r
mode with binary(b)
dfile=input("Enter Destination File:")
with open(dfile,"ab") as fp2: # Opening the Destination
File in 'a' mode with binary(b)
filedata=fp1.read() # Reading from Source File

227
fp2.write(filedata) # Writing the data to
destrination File
print("Source File Data Copied into Dest. File")
except FileNotFoundError:
print("Source File Does not exist")

========================================
Types of Files in Python
========================================
=>In Python Programming, we have two types of Files. They are

1. Text File
2. Binary Files

1) Text File:

=>A text file is one which contains Alphabets, Digits and Special
Symbols.
=>In Python Programming, a text file is denoted by a letter 't' .
=>Examples: .py . java .c .cpp
.txt .doc .xlsx...etc

2) Binary File:

=>A Binary File always contains data in the form Binary Data Format.
=>In Python Programming, a Binary file is denoted by a letter 'b' .
=>Examples:- images (.jpg,jpeg, .png, .gif)
audio and video files
PDF formats with Images

=================================================
Pickling and Un-Pickling
(OR)
Object Serialization or Object De-Serialization
=================================================

Pickling

=>Let us assume there there exist an object which contains multiple


values. To
save or write object data of main memory into the file of secondary
memory by using write() and writelines() , they transfers the values in
the form of value by value and it is one of the time consuming process(
multiple write operations).
=>To Overcome this time consuming process, we must use the concept of
Pickling.
=>The advantage of pickling concept is that with single write operation
, we can

228
save or write entire object data of main memory into the file of
secondary memory.
=>Definition of Pickling:

=>The Process saving or transfering entire object content of main


memory into the file of secondary memory by performing single write
operation is called Pickling.
=>Pickling concept participates in Write Operations.

Steps for implementing Pickling Concept:

=>import pickle module, here pickle is one of the pre-defined module


=>Choose the file name and open it into write mode.
=>Create an object with collection of values (Iterable object)
=>use the dump() of pickle module. dump() save the content of any
object into the
file with single write operation.
Syntax: pickle.dump(object , filepointer)
=>NOTE That pickling concept always takes the file in Binary Format.

Un-Pickling

=>Let us assume there exists a record with multiple values in a file of


secondary memory. To read or trasfer the entire record content from
file of secondary memory, if we use read(), read(no.of chars),
readline() and readlines() then they read record values in the form of
value by value and it is one of the time consuming process( multiple
read operations).
=>To overcome this time consuming process, we must use the concept of
Un-pickling.
=>The advantange of Un-pickling is that with single read operation, we
can read entire record content from the file of secondary memory into
the object of main memory.
=>Definition of Un-Pickling:

=>The process of reading or trasefering the enrite record content from


file of secondary memory into the object of main memory by performing
single read operation is called Un-pickling.

=>Un-Pickling concept participates in Read Operations.

Steps for implementing Un-Pickling Concept:

=>import pickle module


=>Choose the file name and open it into read mode.
=>Use the load() of pickle module. load() is used for transfering or
loading the
entire record content from file of secondary memory into object of
main memory.
Syntax: objname=pickle.load(filepointer)
=>NOTE That Un-pickling concept always takes the file in Binary Format.

229
#Program for accepting student details such as sno,sname and marks and
save them in file as a record.
#studpick.py
import pickle,sys
def savestudentdata():
with open("stud.data","ab") as fp:
while(True):
#accept student values
print("-"*50)
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
#create an empty list and append student values
l=list()
l.append(sno)
l.append(sname)
l.append(marks)
#save iterable object 'l' data into the file--use
dump() of pickle
pickle.dump(l,fp)
print("\nStudent Record Saved in File--
successfully")
print("-"*50)
ch=input("Do u want to insert another
record(yes/no):")
if(ch.lower()=="no"):
print("Thx for using program")
sys.exit()
#main program
savestudentdata()

=======================================================================

#Program for reading student records from file


#studunpick.py
import pickle
try:
with open("stud.data","rb") as fp:
print("-"*50) print("Stno\
tName\tmarks")
print("-"*50)
while(True):
try:
obj=pickle.load(fp)
for val in obj:
print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break

except FileNotFoundError:
print("File does not exist")
=====================================================

230
=======================================
=======================================
=>"os" is one of pre-defined module
=>The purpose of 'os' module is that " To perform ceratin Os Level
Operations"
=>The essential Os Level Operations are
1) getting current working folder
( getcwd() )
2) create a folder ( m
3) create a folders hierarchy
( makedirs() )
4) remove a folder ( r
5) remove a folders Hierarchy (
removedirs() )
6) rename a folder (
7) list files in folder

1) getting current working folder:

=>To get current working folder, we use a pre-defined function


getcwd() of os module
=>Syntax: varname=os.getcwd()

Example:

#This program gives current working folder----getcwd()


#getcwdex.py
import os
cwfolder=os.getcwd()
print("Current Working Folder=",cwfolder)

2) create a folder :

=>To create a folder, we use mkdir() of os module.


=>Syntax:- os.mkdir("folder name")
=>mkdir() can create one folder at a time and it is unable create
Folders Hierarchy.
=>mkdir() generate FileExistsError provided if the folder alerady
exists.
=>mkdir() generates FileNotFoundError / OSError provided when we
attempt create Folders Hierarchy.

Examples:

#mkdirex.py
import os
try:
os.mkdir("D:\\kiwi\mango\guava")
print("Folder created successfully--verify")
except FileExistsError:
print("Folder already exists")
except FileNotFoundError:
print("Creation of Folders Hierarchy is not possible:")
#(OR)
except OSError:
print("mkdir() can't create Folder Hierarchy")

231
3) create a folders hierarchy:

=>To create a folders hierarchy, we use makedirs() of os module


=>Syntax:- os.makedirs("folders hierarchy")
=>If the folders Hierarchy already exists then we get FileExistsError.

Examples:

#Program for creating a folders Hierarchy


#mkdirsex.py
import os
try:
os.makedirs("D:\\India\Hyd\Ameerpet\Python\Data Science")
print("Folders created successfully--verify")
except FileExistsError:
print("Folder already exists")

4) remove a folder :

=>To remove a folder, we use rmdir() of os module


=>Syntax: os.rmdir("folder name")
=>If folder name does not exists then we get FileNotFoundError.
=>If the folder contains any files or sub folder then it is not
possible to remove folder and we get OSError.
=>rmdir() can remove one folder at a time but not possible to remove
Folders Hierarchy.

Examples:

#rmdirex.py
import os
try:
os.rmdir("D:\\hyd")
print("Folder removed successfully--verify")
except FileNotFoundError:
print("Specified Folders does not exists")
except OSError:
print("Specified Folder is not empty--not possible to remove")

5) remove a folders Hierarchy:

=>To remove a folders Hierarchy, we use removedirs() of os module


=>Syntax:- os.removedirs("folders Hierarchy")
=>If folders Hierarchy does not exists then we get FileNotFoundError.
=>If the folder hierarchy contains any files or sub folder then it is
not possible to remove folders hierachy and we get OSError.

Examples:

#removemdirex.py
import os
try:
os.removedirs("D:\\India/Hyd\Ameerpet/Python/django")

232
print("Folders Hierarhcy removed successfully--verify")
except FileNotFoundError:
print("Specified Folders does not exists")
except OSError:
print("Specified Folders is not empty--not possible to remove")

6) rename a folder :

=>To rename a folder , we use rename() of os module


=>Syntax: os.rename("existing folder name", "New Folder name")
=>If existing folder name does not exists then we get
FileNotFoundError.

Examples:

#renamedirex.py
import os
try:
os.rename("c:\\mango","c:\\india")
print("Folder renamed successfully--verify")
except FileNotFoundError:
print("Folders does not exists")

7) list files in folder :

=>To list the files in folder , we use listdir() of os module


=>Syntax:- listobj=os.listdir("folder name")
=>if the "folder name" does not exists then we get FileNotFoundError

Examples:

#Program for listing files


#listfiles.py
import os
try:
foldername=input("Enter Folder Name:")
listfiles=os.listdir(foldername)
print("-"*50)
print("Number of file in '{}' folder={}".format(foldername,
len(listfiles)))
print("-"*50)
for filename in listfiles: print("\
t{}".format(filename))
print("-"*50)
except FileNotFoundError:
print("Folders does not exists:")
===================================X===================================
=====

#This program gives current working folder----getcwd()


#getcwdex.py
import os
cwfolder=os.getcwd()

233
print("Current Working Folder=",cwfolder)

==========================
#This program creates a folder---mkdir()
#mkdirex.py
import os
try:
os.mkdir("d:\HYD")
print("Folder created successfully--verify")
except FileExistsError:
print("Folder already exist")
except OSError:
print("mkdir() can't create Folder Hierarchy")

#This program creates a folders hierarchy---makedirs()


#makedirsex.py
import os
try:
os.makedirs("c:\Apple\python")
print("Folders hierarchy created successfully--verify")
except FileExistsError:
print("Folder hierachy already exist")

#This program remove a folder ---rmdir()


#rmdirex.py
import os
try:
os.rmdir("notes")
print("Folder removed successfully --verify")
except FileNotFoundError:
print("Folder Does not Exist")
except OSError:
print("Folder is not empty-can't remove the folder")

#This program removes folders Hierarchy ---removedirs()


#removedirex.py
import os
try:
os.removedirs("C:\India\hyd")
print("Folders hierarchy removed successfully --verify")
except FileNotFoundError:
print("Folder Does not Exist")
except OSError:
print("Folder is not empty-can't remove the folder")

234
#This program renames a folder--rename()
#renamefolderex.py
import os
try:
os.rename("D:\BANG","D:\PYTHON",)
print("Folder Renamed successfully --verify")
except FileNotFoundError:
print("Folder Does not Exist")

#This program list the files in a folder--listdir()


#listdirsex.py
import os
try:
foldername=input("Enter Folder Name:")
fileslist=os.listdir(foldername)
print("Number of File =",len(fileslist))
for filename in fileslist:
print("\t{}".format(filename))
except FileNotFoundError:
print("Folder does not exists")

================================================
Working with CSV Files in Python
================================================
=>CSV stannds for Comma Separated Values.
=>A CSV File is one of the is a simple file format used to store
tabular data, such as a
spreadsheet or database.
=>A CSV file stores tabular data (numbers and text) in plain text.
=>Each line of the CSV file is a data record. Each record consists of
one or more fields,
separated by commas.
=>Python provides an in-built module called csv to work with CSV files.
=>There are 2 classes provided by this module for writing the data to
CSV File. They are
1) By using Using csv.writer class object
2) By Using csv.DictWriter class object

1) By using Using csv.writer class object

=>The csv.writer class object is used to insert data to the CSV file.
=>To create an object of csv.writer class object, we use writer() and
present in csv module.
=>csv.writer class object provides two Functions for writing to CSV
file.
=>They are
1) writerow()
2) writerows()

1) writerow(): This method writes a single row at a time.


Field row can be written using this method.
Syntax:- csvwriterobj.writerow(fields Row / Data Row)
2) writerows(): This method is used to write multiple rows at a time.
This can be used to write rows list.
Syntax: Writing CSV files in Python

235
csvwriterobj.writerows(data rows)
here data rows can be list tuple set,frozenset only

2) By Using csv.DictWriter class object

=>The csv.DictWriter class object is used to insert dict data to the


CSV file.
=>To create an object of csv.DictWriter class object, we use
DictWriter() and present in csv module.
=>csv.DictWriter class object provides two Functions for writing to
CSV.
1) writeheader()
2) writerows()

1) writeheader():

writeheader() method simply writes the first row of your csv file
using the pre-specified fieldnames.
Syntax: DictWriterObj.writeheader()

2) writerows():

=>writerows() method simply writes all the values of (Key,Value) from


dict object in the form of separate rows[ Note: it writes only the
values(not keys) ]
Syntax:- DictWriterObj.writerows(dictobject)

Reading the data from CSV File

=>There are various ways to read a CSV file that uses either the CSV
module or the pandas
library.
=>The csv Module provides classes for reading information from CSV
file .
1) csv.reader
2) csv.DictReader

1) csv.reader():

=>This Function is used for creating an object of csv.reader class and


It helps us to read the data records from csv file.
=>Syntax:- csvreaderobj=csv.reader(filepointer)

2) csv.DictReader():

=>This Function is used for creating an object of csv.DictReader class


and It helps us to read the data from csv file where it contains dict
data(Key,Value).
=>Syntax:- csvdictreaderobj=csv.DictReader(filepointer)

236
#Reading the data from CSV file-----stud.csv--by using Files
#non-csv.py
with open("stud.csv","r") as fp:
records=fp.readlines()
for record in records:
print("{}".format(record),end=" ")
print()

#Reading the data from CSV file-----stud.csv--by using csv module---


reader()
#CsvEx1.py
import csv
with open("stud.csv","r") as fp:
csvr=csv.reader(fp)
for record in csvr:
for val in record:
print("\t{}".format(val),end="")
print()

# Python program to demonstrate writing to CSV File


#csvwriteex1.py
import csv
# field names
recfields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'CSE', '2', '9.0'],
['Sanchit', 'CSE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1'] ]
# name of csv file
csvfilename = "univ1.csv"
# writing data to csv file
with open(csvfilename, 'w') as fp:
# creating a csv writer object
csvwriter = csv.writer(fp)
# writing the fields
csvwriter.writerow(recfields)
# writing the data rows
csvwriter.writerows(rows)
print("\nCSV file Created and Verify")

# Python program to demonstrate to write single record


# writing single record to CSV file
#csvwriteex2.py
import csv

237
# data record of csv file
row = ['KVR', 'CSE', '2', '9.0']

# name of csv file


filename = "univ1.csv"
# writing to csv file
with open(filename, 'a') as fp:
# creating a csv writer object
cw = csv.writer(fp)
# writing the data row to the csv file
cw.writerow(row)
print("\nSingle Record Written to the CSV File:")

# importing the csv module


#csvdictwriteex2.py
import csv

# my data rows as dictionary objects


mydict =[ {'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year':
'2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit',
'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year':
'2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year':
'1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek',
'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year':
'2'} ]

# field names
csvfields = ['name', 'branch', 'year', 'cgpa']

# name of csv file


filename = "univ2.csv"

# writing to csv file


with open(filename, 'w') as fp:
# creating a csv dict writer object
dictwriter = csv.DictWriter(fp, fieldnames = csvfields)
# writing headers (field names)
dictwriter.writeheader()
# writing data rows
dictwriter.writerows(mydict)
print("\nDict Data Written to the csv file--verify")

#readcsvex4.py
import csv
# opening the CSV file
with open("univ2.csv" , "r" ) as fp:

238
dr=csv.DictReader(fp)# <class 'csv.DictReader'>
#print("type of dr=",type(dr)) # type of dr= <class
'csv.DictReader'>
for d in dr:
for k,v in d.items():
print("{}--->{}".format(k,v))
print()

=============================================
Python DataBase Communication ( PDBC )
=============================================
=>Even we acheived the Data Persistency by using Files, Files has the
following Limitations.

1. Files of any language does not contain security bcoz


Files are unable to provide
security in the form of User Name and Password.
2. Files are unable to store large amount of data
3. File are differing from One OS to another OS (Files
are OS depenedent)
4. Querying and Processing the data from Files is Very
Complex bcoz file data is
organized w.r.t Indices and idenfying the indices is
very complex.
5. Files does not contain Column Names (Except CSV
Files)
=>To Overcome the limitation of files and to acheive the Data
Persistency, we must use the concept of any RDBMS DataBase Softwares (
Oracle, MYSQL, Mongo DB, DB2, SQL Server, Postgey SQL,
SQLITE3 etc).

1. All RDBMS DataBase Softwares Provides Security bcoz


RDBMS DataBase
Softwares considers User names and Password.
2. All RDBMS DataBase Softwares stores large amount of
data
3. All RDBMS DataBase Softwares Arch Remains Same on
types of OSes ( OS
Independent)
4. Querying and Processing the data from All RDBMS
DataBase Softwares is Very
Simple bcoz data of All RDBMS DataBase Softwares
oranganized in the of Tables with Column Names.
5. The Data Present in any RDBMS DataBase Softwares
oranganized in the of Tables
with Column Names.

=>If Python Program want to communicate with any RDBMS DataBase


Softwares then we must use a PRE-DEFINED MODULE and such PRE-DEFINED
MODULE does not exist in Python Software.
=>Some Third Party Software Vendors( "Anthony Tuininga") developed a
Module for Python Programmers to copmmunicate with DBMS DataBase

239
Softwares and placed in github and Third Party Software Modules must
be installed.
=>To install any Third Party Software Modules in python , we use a
tool called pip and it is present in C:\Users\KVR\AppData\Local\
Programs\Python\Python310\Scripts folder.

=>Syntax : pip install Module Name (at any command prompt

=>If Python Program want to communicate with Oracle Database, then we


must install
cx_Oracle Module.
=>Examples : pip install cx_Oracle

=>If Python Program want to communicate with MySQL Database, then we


must install
mysql-connector or mysql-connector-python Module.

=>Examples : pip install mysql-connector


=>Examples : pip install mysql-connector-python
====================================x==================================
======

================================================================
Communication between Python Program and Oracle Database
================================================================
=
=>In order to write python program to communicate with Oracle Database,
we must follow 6 steps. They are

1. import cx_Oracle module


2. Python Program must get the connection from Oracle DB
3. Create an object Cursor
4. Python program must Prepare the Query and Execute the
Query in Oracle DB
5. Python Program Process the Result of the Query.
6. Python Program closes the connection.

Explanation:

1. import cx_Oracle module:

=>If a python Program want to perform any database operations(insert ,


delete , update record , read records..etc) then we must import a pre-
defined thgrd party module "cx_Oracle".
=>We know that a module is a collection of Variables, Function Name and
Class Names.

Examples: import cx_Oracle

2. Python Program must get the connection from Oracle DB

=>Tomorrow class i will discuss

240
=================================================================
Communication between Python Program and Oracle Database
=================================================================
=>In order to write python program to communicate with Oracle Database,
we must follow 6 steps. They are

1. import cx_Oracle module


2. Python Program must get the connection from Oracle DB
3. Create an object Cursor
4. Python program must Prepare the Query and Execute the
Query in Oracle DB
5. Python Program Process the Result of the Query.
6. Python Program closes the connection.

Explanation:

1. import cx_Oracle module:

=>If a python Program want to perform any database operations(insert ,


delete , update record , read records..etc) then we must import a pre-
defined thgrd party module "cx_Oracle".
=>We know that a module is a collection of Variables, Function Name and
Class Names.

Examples: import cx_Oracle

2. Python Program must get the connection from Oracle DB

=>To do any Data Base Operations, First python program must get the
connection from Oracle.
=>To get the connection any Database, we use connect() which is present
in cx_Oracle module.
=>Syntax:- varame=cx_Oracle.connect("Connection URL")

=>Here connection URL Represents " UserName/Password@DNS/Serviceid "


(OR)
"
UserName/Password@IPAddress/Serviceid "

=>Here Varname is an object of <class, cx_Oracle.Connection>


=>Here "UserName" represents User Name of Oracle Data Base (Ex: scott )
=>here "password" represents Password of Oracle Data Base (Ex: tiger )
=>here DNS(Domain Naming Service) represents name of the machine where
Database
Software Installed. The default Name of Every Machine is
"localhost".
=>Here IPAddress (Internet Protocal Address) represents An address of
Physical Machine where Database software Installed. The default IP
Address of Every Machine is 127.0.0.1 (Loop back address)
=>Here "serviceid" represents on which name Oracle data base Installed
in current working machine. To find Service Id in Oracle Data base, we
use the following at SQL Environment

SQL> select * from global_name;


GLOBAL_NAME

241
ORCL <---------------Service id
=>When we use / write Invalid Connection URL then we get
cx_Oracle.DatabaseError as an exception and must handle.

3. Create an object of Cursor

=>The purpose of creating an object of Cursor is that "To carry the


Query from Python Program, hand over to Database, and obtains Result
from Database and Gives to Python Program".
=>To create an object of Cursor, we use cursor() which is present in
Connection Object.
=>Syntax: varname=conobject.cursor()
=>Here Varname reprsents an object of <class, cx_Oracle.Cursor>

4. Python program must Prepare the Query and Execute the Query in
Oracle DB

=>A Query is a statement or Request or Question to database software


for obtaining data base results.
=>To execute the query in any Database software, we use execute() which
is present in cursor object.
=>Syntax: cursorobj.execute(Query)
=>Here Query is of type str and In any database software we have
different Queries (DDL,DML,DRL )

Oracle view.png
Missing

Type of levels.png
Missing
=============================================
Types of Queries in Database Softwares
=============================================
=>In any database, we have 3 types of Queries. They are

1. DDL( Data Definition Language) Queries


2. DML (Data Manipulation Language) Queries
3. DRL (Data Retrieval Language ) Queries

242
#Program for obtaining Connection from Oracle
#TestOracle.py
import cx_Oracle # step-1
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # Step-2
print("\nPython Progrm got connection from Oracle DB")
print("Type of con=",type(con)) # Type of con= <class
'cx_Oracle.Connection'>
except cx_Oracle.DatabaseError as db:
print("Prob in Database: ", db)

#Program for creating cursor object


#cursorex1.py
import cx_Oracle # Step-1
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # Step-2
print("\nPython Progrm got connection from Oracle DB")
cur=con.cursor() # Step-3
print("\nPython program created cursor object:")
print("Type of cur=",type(cur)) # Type of cur= <class
'cx_Oracle.Cursor'>

#Program creating Student Table wityh sno,sname and marks as column


names
#TableCreate.py
import cx_Oracle # Step-1
def tablecreate():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") #
Step-2
cur=con.cursor() # Step-3
#prepare and execute the query--- # Step-4
tq="create table student(sno number(2) primary key,sname
varchar2(10) not null, marks number(5,2) not null )"
cur.execute(tq)
print("Table Created successfully in Oracle --verify")#
Step-5
except cx_Oracle.DatabaseError as db:
print("Prob in Database: ", db)

#main program
tablecreate()

#Program for altering new column to student table in oracle--add with


alter
#tablealteradd.py
import cx_Oracle
def alteroperation():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()

243
#prepare the query and execute
#aq="alter table student add(crs varchar2(10))"
cur.execute("alter table student add(crs varchar2(10))")
print("Table altered--verify")
except cx_Oracle.DatabaseError as db:
print("Prob in the Database:",db)
#main program
alteroperation()

#Program for altering column sizes of student table in oracle--modify


with alter
#tablealtermodify.py
import cx_Oracle
def alteroperation():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#prepare the query and execute
aq="alter table student modify(sno number(3), marks
number(6,2) )"
cur.execute(aq)
print("Table altered--verify")
except cx_Oracle.DatabaseError as db:
print("Prob in the Database:",db)

#main program
alteroperation()

#This program drops the table


import cx_Oracle
def droptableop():
try:
con=cx_Oracle.connect("scott/tiger@127.0.0.1/orcl")
cur=con.cursor()
cur.execute("drop table employee")
print("Table Dropped Sucessfully")
except cx_Oracle.DatabaseError as db:
print("Problem in Data Base:",db)
#main program
droptableop()

==============================================
1. DDL( Data Definition Language) Queries
==============================================
=>The purpose of DDL Queries is that to deal with Physical Level of
Database software such as creation of Tables, altering column sizes,
adding new Columns etc.
=>in any Database software , we have 3 types of DDL Queries. They are

244
1. create
2. alter
3. drop

1) create:

=>This Query is used for creating a table in Oracle Database


=>Syntax:-
SQL> create table <table-name> ( col name1 database data
type, col name2 database data type, ......col name-n database data
type )

SQL> create table employee(eno number(2) primary key ,ename


varchar2(10) not null , sal number (6,2) not null);

2. alter :

=>This Query is used for alter the table structure such as modifying
(modify) the column sizes and adding (add) new columns.

Syntax1:- SQL> alter table <table-name> modify ( existing col name1


database data type....
existing col name-n database data type )

Syntax2:- SQL> alter table <table-name> add ( new col name1 database
data type....
new col name-n database data type )

Examples: SQL> alter table employee add(cname varchar2(10));


SQL> alter table employee modify(ename varchar2(20),
sal number(8,2));

3) drop :

=>This query is used for removing the table from Database Software
=>Syntax:- SQL> drop table <table-name>
=>Example:- SQL> drop table employee

================================================
2. DML (Data Manipulation Language) Queries
================================================
=>The purpose of DML operations is that To manipulate the table such
Inserting the records, deleting the records and updating the records.
=>In RDBMS database softwares, we have 3 types of DML Operations. They
are

245
1. insert
2. delete
3. update
=>When we execute any DML Operation through python program, we must use
commit() for permanent change / update / modification and to roll back
we use roolback().
=>commit() and rollback() are present in connection object.

1. insert:

=>This query is used for inserting a record in table of database.


=>Syntax:- SQL> insert into <table-name> values( val1 for column1,
val2 for column2.....
val
Example: SQL> insert into student values (20,'DR',33.45,'C');
SQL>insert into student values
(10,'RS',23.45,'Python');
SQL> commit ;

#This program insert student data in student table


import cx_Oracle
def insertrecird():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#prepare the query and execute
iq="insert into student values(50,'KR',12.22,'Java')"
cur.execute(iq)
con.commit()
print("{} Record Inserted in
student".format(cur.rowcount))
except cx_Oracle.DatabaseError as db:
print("Prob in the Database:",db)
#main program
insertrecird()

#StudentRecordInsertEx2.py
import cx_Oracle
def insertrecird():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
stno=int(input("Enter Student Number:"))
name=input("Enter Student Name:")
marks=float(input("Enter Student Marks"))

246
course=input("Enter Student Course:")
#prepare the query and execute
iq="insert into student values(%d,'%s',%f,'%s')"
cur.execute(iq %(stno,name,marks,course))
con.commit()
print("{} Record Inserted in
student".format(cur.rowcount))
except cx_Oracle.DatabaseError as db:
print("Prob in the Database:",db)
#main program
insertrecird()

#StudentRecordInsertEx3.py
import cx_Oracle
def insertrecird():
try:
while(True):

con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
stno=int(input("Enter Student Number:"))
name=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
course=input("Enter Student Course:")
#prepare the query and execute
iq="insert into student values(%d,'%s',%f,'%s')"
cur.execute(iq %(stno,name,marks,course))
con.commit()
print("{} Record Inserted in
student".format(cur.rowcount))
print("-"*50)
ch=input("Do u want to insert another
record(yes/no):")
if(ch.lower()=="no"):
break
except cx_Oracle.DatabaseError as db:
print("Prob in the Database:",db)
#main program
insertrecird()

#StudentRecordDeleteEx.py
import cx_Oracle
def deleterecord():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#accpept student from KBD
stno=int(input("Enter Student Number:"))
cur.execute("delete from student where sno=%d" %stno)

247
con.commit()
if(cur.rowcount>0):
print("{} Record Deleted :".format(cur.rowcount))
else:
print("Record does not exists")

except cx_Oracle.DatabaseError as db:


print("Problem in Database:",db)

#main program
deleterecord()

#StudentRecordUpdateEx.py
import cx_Oracle
def updaterecord():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#accpept student from KBD
stno=int(input("Enter Student Number:"))
marks=float(input("Enter Student Marks for updation:"))
crs=input("Enter Student Course for Updation:")
cur.execute("update student set marks=%f , crs='%s' where
sno=%d" %(marks,crs,stno))
con.commit()
if(cur.rowcount>0):
print("{} Student Record Updated--
Verify".format(cur.rowcount))
else:
print("Student Record does not exist")
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)

#main program
updaterecord()

import cx_Oracle
def readrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
cur.execute("select * from student")
print("="*50)
while(True):
record=cur.fetchone()

248
if(record!=None):
for val in record:
print("{}".format(val),end=" ")
print()
else:
print("=" * 50)
break
except cx_Oracle.DatabaseError as db:
print("Prob in Data base:",db)
#main program
readrecords()

import cx_Oracle
def readrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
cur.execute("select * from student")
print("="*50)
records=cur.fetchmany(3)
for record in records:
for val in record:
print("{}".format(val),end=" ")
print()
else:
print("=" * 50)
except cx_Oracle.DatabaseError as db:
print("Prob in Data base:",db)
#main program
readrecords()

import cx_Oracle
def readrecords():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
cur.execute("select * from student")
print("="*50)
records=cur.fetchall()
for record in records:
for val in record:
print("{}".format(val),end=" ")
print()
else:
print("=" * 50)
except cx_Oracle.DatabaseError as db:
print("Prob in Data base:",db)
#main program
readrecords()

249
===========================================
3. DRL (Data Retrieval Language ) Queries
===========================================
=>The purpose of DRL statements is that To read or select the records
from table.
=>To the read the records from table, we use select statement and it
comes under DRL
statement.

Syntax1:- SQL> select col1,col2...col-n from <table-name> ;


(OR)
SQL> select * from <table-name> ;

Syntax2:- SQL> select col1,col2...col-n from <table-name> where cond


list
(OR)
SQL> select * from <table-name> where cond list;

#This program obtains connection from MySQL


#mysqlcontest.py
import mysql.connector # step-1
con=mysql.connector.connect(host="localhost",

print("Python program got connection MySQL")

#This program creates an object of cursor


#mysqlcurtest.py
import mysql.connector # step-1
con=mysql.connector.connect(host="localhost",

print("\nPython program got connection MySQL")


cur=con.cursor() # step-3
print("\nPython created an object of Cursor:")

#This program creates a databse in MYSQL


#dbcreate.py
import mysql.connector # step-1
try:
con=mysql.connector.connect(host="localhost",

cur=con.cursor() # step-3
#create a database in mysql on the name of batch7am
dc="create database batch7am"
cur.execute(dc)
print("Database Created Successfully in MySQL")
except mysql.connector.DatabaseError as db:

250
print("Prob in database:",db)

#This program creates a table student in batch7am database in MYSQL


#tablecreate.py
import mysql.connector # step-1
try:
con=mysql.connector.connect(host="localhost",

cur=con.cursor() # step-3
#create a table student in batch7am
tc="create table emp(eno int primary key, ename varchar(10) not
null, sal float not null )"
cur.execute(tc)
print("Table created successfully in MySQL")
except mysql.connector.DatabaseError as db:
print("Prob in database:",db)

#StudentRecordInsertEx.py
import mysql.connector
def insertrecord():
try:
while(True):
con=mysql.connector.connect(host="localhost",

cur=con.cursor()
stno=int(input("Enter Student Number:"))
name=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
#prepare the query and execute
iq="insert into student values(%d,'%s',%f)"
cur.execute(iq %(stno,name,marks) )
con.commit()
print("{} Record Inserted in
student".format(cur.rowcount))
print("-"*50)
ch=input("Do u want to insert another
record(yes/no):")
if(ch.lower()=="no"):
break
except mysql.connector.DatabaseError as db:
print("Prob in the Database:",db)
#main program
insertrecord()

#StudentRecordDeleteEx.py

251
import mysql.connector
def deleterecord():
while(True):
try:
con=mysql.connector.connect(host="localhost",

cur=con.cursor()
#accpept student from KBD
stno=int(input("Enter Student Number:"))
cur.execute("delete from student where sno=%d"
%stno)
con.commit()
if(cur.rowcount>0):
print("{} Record Deleted
:".format(cur.rowcount))
else:
print("Record does not exists")

ch=input("Do u want to delete another


record(yes/no):")
if(ch.lower()=="no"):
break
except mysql.connector..DatabaseError as db:
print("Problem in Database:",db)

#main program
deleterecord()

#StudentRecordUpdateEx.py
import mysql.connector
def updaterecord():
try:
con=mysql.connector.connect(host="localhost",

cur=con.cursor()
#accpept student from KBD
stno=int(input("Enter Student Number:"))
stname=input("Enter Student Name for updation:")
stmarks=float(input("Enter Student Marks for
Updation:"))
cur.execute("update student set sname='%s' , marks=%f
where sno=%d " %(stname,stmarks,stno))
con.commit()
if(cur.rowcount>0):
print("{} Student Record Updated--
Verify".format(cur.rowcount))
else:
print("Student Record does not exist")
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)

252
#main program
updaterecord()

#StudentRecordSelectex1.py
import mysql.connector
def readrecords():
try:
con=mysql.connector.connect(host="localhost",

cur=con.cursor()
cur.execute("select * from student")
print("="*50)
records=cur.fetchall()
for record in records:
for val in record:
print("{}".format(val),end=" ")
print()
else:
print("=" * 50)
except mysql.connector.DatabaseError as db:
print("Prob in Data base:",db)
#main program
readrecords()
#Colnames.py
import mysql.connector
def readrecords():
try:

con=mysql.connector.connect(host="localhost",user="root",passwd=
"root",database="batch7am")
cur=con.cursor()
cur.execute("select * from student")
colsinfo=cur.description
collist=[str(colinfo[0]) for colinfo in colsinfo ]
print("="*50)
for colname in collist:
print("{}".format(colname),end="\t")
print()
print("="*50)

except mysql.connector.DatabaseError as db:


print("prob in database:",db)

#main program
readrecords()

#StudentRecordSelectex2.py
import mysql.connector
def readrecords():

253
try:

con=mysql.connector.connect(host="localhost",user="root",passwd=
"root",database="batch7am")
cur=con.cursor()
cur.execute("select * from student")
#Obtains and display Col Names
colsinfo=cur.description
collist=[str(colinfo[0]) for colinfo in colsinfo ]
print("="*50)
for colname in collist:
print("{}".format(colname),end="\t")
print()
print("="*50)
#display Records
records=cur.fetchall()
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("="*50)
except mysql.connector.DatabaseError as db:
print("prob in database:",db)

#main program
readrecords()
>17-jun-22<

==========================================================
Object Oriented Principles (or) Features (or) Concepts (12 days)
==========================================================
Index

=>Models or Paradigams of Programming Languages


=>What are advtanges of Object Oriented Principles
=>What are Object Oriented Principles
1) Classes
2) Object
3) Data Encapsulation
4) Data Abstraction
5) Inheritance
6) Polymorphism
7) Message Passing
=>Programming Examples

==========================================================
Object Oriented Principles (or) Features (or) Concepts
==========================================================
=>In Real time, to develop any project, we need to use a programming
language.
=>The Programming Laguages satisfies two types of Principles. They are
1. Procedure Oriented Principles( Functional )
2. Object Oriented Principles.

254
=>If Programming Laguage satisfies Procedure Oriented Principles then
that language is
called Procedure Oriented Programming Laguage.
Examples: 8086, C, Pascal, COBOL...etc Oracle 7.x
=>If Programming Laguage satisfies Object Oriented Principles then that
language is called
Object Oriented Programming Laguage.

=>PYTHON is one of the Functional and object oriented programing Lang.


=>Even though PYTHON belongs to Functional and object oriented
programing Lang, Internally every thing treated as objects.

"Every Thing is an object "---Python


(OR)
Advantages of OO Principles

=>In Object, we can store large Volume of Data and achieves Platform
Independency
(Python)
=>The confidential Data can be transfered between multiple remote
machine in the
form cipher text (Encrypted format). So that security can be
enhanced ( Improved).
=>The Large of Volume of Data Transfered between Multiple Machines all
at once in
the form of object and leads to effective communication.
=>All Values are available around the objects and provides effective
memory
Management.
===============================X=======================================

===============================================
List of Object Oriented Principles
===============================================
=>To Say Python is one of the Object Oriented Programming Language, It
has to Satisfy the following OOPs Principles.
1) Classes
2) Objects
3) Data Encapsulation
4) Data Abstraction
5) Inheritance
6) Polymorphism
7) Message Passing (already discussed )
================================x==================================

===============================
1) Classes
===============================
=>The purpose of Classes concept is that "To develop Programmer Defined
Classes and To
develop any real time application in OOPs"

255
=>The purpose of Developing Programmer Defined Classes is that "To
customize the
operations on objects"
=>To develop Programmer Defined Classes with classes concept, we use a
keyword called
"class"
=>Every Programmer-defined class is considered as Programmer-Defined
data type.
=>Every Python Program must write with classes concept. Without classes
concept there is Python Program.

=>Definition of Class:

=>A class is a collection Data Members and Methods.

=>Data Members are also called Variables / attributes / Fields.


=>Functions are called Methods in OOPs
=>When we define a class, memory space is not created for Data Members
and Methods but whose space is created when we create an object.
=>Hence Class does not contain memory space and object contains memory
space.

====================================================
Syntax for defining a class in Python
====================================================

class <clsname>:
Class Level Data Members
def instancemethodname(self,list of formal params if
any):
--------Instance Data Members-----
Specific Operations

@classmethod
def classlevelmethod(cls,,list of formal params if any):

--------Class Level Data Members-----


Common Operations

@staticmethod
def staticmethodname(list of formal params if any):

------Utility Operations------------

=======================================================================

============================================

256
Types of Data Members in Class of Python
============================================
=>In class of python, we can defined two types of Data Members. They
are
1) Instance Data Members .
2) Class Level Data Members.

1) Instance Data Members .

=>Instance data members are used for storing specific values and they
are always available as a part of object and hence they are also called
object level data members.
=>Instnace Data members memory space created every time when we create
an object.
=>Instance Data Members can be specified in three places. They are
1) through object.
2) through Instance Method.
3) throughConstructor.
=>We can access the Instance Data Members by using two syntaxes. They
are
a) by using object name-----> objectname.instance
data member
b) by using implicit object---->
self..instance data member

2) Class Level Data Members .

=>Class Level Data Members are used for storing Common values and they
are always
available to all objects of same class
=>Class Level Data Members memory space created Only time
irrespective number of objects are created.
=>Class Level Data Members can be specified in 2 places. They are
1) Inside of Class definition.
2) Inside of Class Level Method Definition.
=>We can access the Class Level Data Members by using two syntaxes.
They are
a) by using Class Name name-----> classname.class
level data member
b) by using object name----------->
objectname.class level data member

#Program for storing student details such as stno,name and marks


#StudEx2.py-----Instance Data Members
class Student:pass

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
s1.stno=10
s1.sname="RS"

257
s1.marks=11.22
#add the Instance Data Members to s2
s2.stno=20
s2.sname="JG"
s2.marks=33.33
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks)
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print(" ")

#Program for storing student details such as stno,name and marks


#StudEx3.py-----Instance Data Members
class Student:pass

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
print("First Student Details")
print(" ")
s1.stno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print(" ")
#add the Instance Data Members to s2
print("Second Student Details")
print(" ")
s2.stno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks)
print(" ")
print("Content of s2")
print(" ")

258
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print(" ")
=======================================================================

#Program for storing student details such as stno,name and marks


#StudEx4.py-----Class Level Data Members and Instance Data Members
class Student:
crs="PYTHON" # Here 'crs' is called Class Level Data Member

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
print("First Student Details")
print(" ")
s1.stno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print(" ")
#add the Instance Data Members to s2
print("Second Student Details")
print(" ")
s2.stno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks) # Accessing Instance Data
Members(stno,sname and marks) w.r.t object name
print("Studennt Course=",Student.crs)#Accessing class Level Data
member(crs) by using class name
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print("Studennt Course=",Student.crs)# Accessing class Level Data
member by using class name
print(" ")

#Program for storing student details such as stno,name and marks


#StudEx5.py-----Class Level Data Members and Instance Data Members
class Student:
crs="PYTHON" # Here 'crs' is called Class Level Data Member

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
print("First Student Details")
print(" ")

259
s1.stno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print(" ")
#add the Instance Data Members to s2
print("Second Student Details")
print(" ")
s2.stno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks) # Accessing Instance Data
Members(stno,sname and marks) w.r.t object name
print("Studennt Course=",s1.crs)#Accessing class Level Data member(crs)
by using object name
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print("Studennt Course=",s2.crs)# Accessing class Level Data member by
using object name
print(" ")
#EmpEx1.py------>Demonstrates Class Level and Instance Data Members
class Employee:
cname="IBM" # class level data member

#main program
e1=Employee() # Object creation
e2=Employee() # Object creation
# Read Employee object1 data
print("First Employee Details")
print(" ")
e1.eno=int(input("Enter Employee Number:"))
e1.ename=input("Enter Employee Name:")
e1.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Second Employee Details")
print(" ")
e2.eno=int(input("Enter Employee Number:"))
e2.ename=input("Enter Employee Name:")
e2.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Content of e1")
print(" ")
print("Employee Number:{}".format(e1.eno))
print("Employee Name:{}".format(e1.ename))
print("Employee Salary:{}".format(e1.sal))
print("Employee Working Company:{}".format(Employee.cname))
print(" ")
print("Content of e2")
print(" ")
print("Employee Number:{}".format(e2.eno))

260
print("Employee Name:{}".format(e2.ename))
print("Employee Salary:{}".format(e2.sal))
print("Employee Working Company:{}".format(Employee.cname))
print(" ")

#EmpEx2.py------>Demonstrates Class Level and Instance Data Members


class Employee:
cname="IBM" # class level data member

#main program
e1=Employee() # Object creation
e2=Employee() # Object creation
# Read Employee object1 data
print("First Employee Details")
print(" ")
e1.eno=int(input("Enter Employee Number:"))
e1.ename=input("Enter Employee Name:")
e1.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Second Employee Details")
print(" ")
e2.eno=int(input("Enter Employee Number:"))
e2.ename=input("Enter Employee Name:")
e2.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Content of e1")
print(" ")
print("Employee Number:{}".format(e1.eno))
print("Employee Name:{}".format(e1.ename))
print("Employee Salary:{}".format(e1.sal))
print("Employee Working Company:{}".format(e1.cname))
print(" ")
print("Content of e2")
print(" ")
print("Employee Number:{}".format(e2.eno))
print("Employee Name:{}".format(e2.ename))
print("Employee Salary:{}".format(e2.sal))
print("Employee Working Company:{}".format(e2.cname))
print(" ")

#CircleArea.py
class Circle:
PI=3.14

#main program
c1=Circle()
c1.r=float(input("Enter Radious:"))
c1.arc=Circle.PI*c1.r**2
print(" ")
print("Given radious:{}".format(c1.r))
print("Area of Circle:{}".format(c1.arc))

261
print(" ")

21-jun-2020

=================================================
Types of Methods in class of Python
=================================================
=>In a class of Python, we can defined 3 types of Methods. They are
1) Instance Methods
2) Class Level Method
3) Static Method

1) Instance Methods

=>Instance Methods are used for Performing Specific Operations on


objects and these
methods are also called Object Level Methods.
=>Syntax:- def instancemethodname(self,list of formal params if
any):

----Specify Instance Data Members and


Operations----

=>Instance Methods always takes "self" as a First Formal Parameter for


holding or storing
Current Object Memory Address or Reference or Id.
=>Instnace Method Must be accessed w.r.t object name or self.

objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()

What is "self" ( implicit object)

=>"self" is one of the implicit object created by Python Execution


Environment for storing
current object address or id or Reference.
=>"self" is always taken as a First Formal Parameter in Instance Method
Definition.
=>Programtically "self" must be used as a part of corresponding
Instance Method Defintion
only but not Other Part of the program.
=======================================================================
=
2) Class Level Method:

=>Class Level Methods are used for Performing Common Operations for all
the objects same
class. In Other words Class Level Methods are used for specifying
Class Level Data Members.
=>Syntax:
@classmethod

262
def classlevelmethodname(cls,list of formal
params if any):

----Specify Class Level Data Members and


Operations----

=>Class Level Method always takes "cls" as a First Formal Parameter and
it is an alternative
name for Corresponding Class Name.
=>Class Level Method Must be accessed w.r.t class name or cls

classname.ClassLevelMethodName()
(OR)
cls.ClassLevelMethodName()
(OR)
self.ClassLevelMethodName()

What is "cls"

=>"cls" is one of the implicit name created by Python Execution


Environment for representing the class name .
=>"cls" is always taken as a First Formal Parameter in Class Level
Method Definition.
=>Programtically "cls" must be used as a part of corresponding Class
Level Method Defintion
only but not Other Part of the program.

3) Static Method-----Tomorrow class

#Program for storing student details such as stno,name and marks


#InstanceMethodEx1.py
class Student:
def readstuddata(self): # Instance Method
print("Id of current object=",id(self))
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstuddata(self): # Instance Method
print(" ")
print("Id of current object=",id(self))
print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print(" ")

#main program
s1=Student() # Object creation
s2=Student() # Object creation
print("First Student Details")
print(" ")

263
print("Id of s1 in main program:",id(s1))
s1.readstuddata() # Method Call
print(" ")
print("Second Student Details")
print(" ")
print("Id of s2 in main program:",id(s2))
s2.readstuddata() # Method Call
print(" ")
print("Content of s1")
print("Id of s1 in main program:",id(s1))
s1.dispstuddata() # Method Call
print("Content of s2")
print("Id of s2 in main program:",id(s2))
s2.dispstuddata() # Method Call

#Program for storing student details such as stno,name and marks


#InstanceMethodEx2.py
class Student:
def readstuddata(self): # Instance Method
print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")
self.dispstuddata() # calling Instance Method

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print(" ")

#main program
s1=Student() # Object creation
s2=Student() # Object creation
print("First Student Details")
s1.readstuddata() # Method Call
print("Second Student Details")
s2.readstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx1.py
class Student:
@classmethod
def getcourse(cls):
cls.crs="PYTHON"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")

264
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx2.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx3.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
@classmethod
def getcompaddress(cls):

265
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
Student.getcompaddress() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx4.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
Student.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method

266
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx5.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
cls.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx6.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
cls.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")

267
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


Student.getcourse() # calling Class Level Method
print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx7.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
cls.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


self.getcourse() # calling Class Level Method
print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program

268
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

=================================================
Types of Methods in class of Python
=================================================

=>In a class of Python, we can defined 3 types of Methods. They are


1) Instance Methods
2) Class Level Method
3) Static Method

1) Instance Methods

=>Instance Methods are used for Performing Specific Operations on


objects and these
methods are also called Object Level Methods.
=>Syntax:- def instancemethodname(self,list of formal params if
any):

----Specify Instance Data Members and


Operations----

=>Instance Methods always takes "self" as a First Formal Parameter for


holding or storing
Current Object Memory Address or Reference or Id.
=>Instnace Method Must be accessed w.r.t object name or self.

269
objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()

What is "self" ( implicit object)

=>"self" is one of the implicit object created by Python Execution


Environment for storing
current object address or id or Reference.
=>"self" is always taken as a First Formal Parameter in Instance Method
Definition.
=>Programtically "self" must be used as a part of corresponding
Instance Method Defintion
only but not Other Part of the program.
=======================================================================
=
2) Class Level Method:

=>Class Level Methods are used for Performing Common Operations for all
the objects same
class. In Other words Class Level Methods are used for specifying
Class Level Data Members.
=>Syntax:
@classmethod
def classlevelmethodname(cls,list of formal
params if any):

----Specify Class Level Data Members and


Operations----

=>Class Level Method always takes "cls" as a First Formal Parameter and
it is an alternative
name for Corresponding Class Name.
=>Class Level Method Must be accessed w.r.t class name or cls

classname.ClassLevelMethodName()
(OR)
cls.ClassLevelMethodName()
(OR)
self.ClassLevelMethodName()

What is "cls"

=>"cls" is one of the implicit name created by Python Execution


Environment for representing the class name .
=>"cls" is always taken as a First Formal Parameter in Class Level
Method Definition.
=>Programtically "cls" must be used as a part of corresponding Class
Level Method Defintion
only but not Other Part of the program.

3) Static Method:

270
=>Static Methods are those which are used for Performing utility
Operation or Universal Operation
=>Static Methods Definition neither takes "self" nor takes "cls" but
it takes an object as parameter (if req) which belongs other classes
=>Syntax:
@staticmethod
def staticmethodname(list of formal params if
any):

----Utility or Universal Operations----

=>=>Static Methods Must be accessed w.r.t class name or object name

classname.Static Method name()


(OR)
objectname.Static Method Name()
================================X=====================================

#Program demonstrating the importnace of static method


#StaticMethodEx1.py
class Emp:
def readempvalues(self):
print("-"*50)
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)

class Student:
def readstudentvalues(self):
print("-"*50)
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College Name:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("Enter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
print("-"*50)

class Hyd:
@staticmethod
def dispobjvalues( obj ):

271
print("-"*50)
for k,v in obj. dict .items():
print("\t{}--->{}".format(k,v))
print("-"*50)

#main program
e=Emp()
s=Student()
t=Teacher()
#read the values for the objects of Emp ,Student and Teacher
print("Employee Information:")
e.readempvalues()
print("Student Information:")
s.readstudentvalues()
print("Teacher Information:")
t.readteachervalues()
#display any type of object values
print("Content of Employee:")
Hyd.dispobjvalues(e)
print("Content of Student:")
Hyd.dispobjvalues(s)
print("Content of Teacher:")
Hyd.dispobjvalues(t)

#Program demonstrating the importnace of static method


#StaticMethodEx2.py
class Emp:
def readempvalues(self):
print("-"*50)
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)

class Student:
def readstudentvalues(self):
print("-"*50)
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College Name:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("Enter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
print("-"*50)

class Hyd:
@staticmethod
def dispobjvalues( obj ):

272
print("-"*50)
for k,v in obj. dict .items():
print("\t{}--->{}".format(k,v))
print("-"*50)

#main program
e=Emp()
s=Student()
t=Teacher()
#read the values for the objects of Emp ,Student and Teacher
print("Employee Information:")
e.readempvalues()
print("Student Information:")
s.readstudentvalues()
print("Teacher Information:")
t.readteachervalues()
#display any type of object values
h=Hyd()
print("Content of Employee:")
h.dispobjvalues(e)
print("Content of Student:")
h.dispobjvalues(s)
print("Content of Teacher:")
h.dispobjvalues(t)

l=list()

===================================================
objects in Python
===================================================
=>When we define a class, memory space is not created for Data Members
and Methods but whose memory is created when we create an object w.r.t
class name.
=>To do any Data Processing, It is mandatory to create an object.
=>To create an object, there must exists a class Definition otherwise
we get NameError

Definition of object:

=>Instance of a class is called object ( Instance is nothing but


allocating sufficient memory space for the Data Members and Methods of
a class)

Syntax for creating an object

varname=classname()

Examples: create an object of Student

so=Student()
Example:- create an object Employee

eo=Employee()

273
Differences Betwwen Classes and Objects

Class:

1) A class is a collection of Data Members and Methods


2) When we define a class, memory space is not created for Data Members
and Methods and it can be treated as specification / model for real
time application.
3) Definition of a perticular exists only once
4) When we develop any Program with OOPs principles, Class Loaded First
only once in main memory.

Objects:

1) Instance of a class is called Object


2) When we create an object, we get the memory space for Data members
and Methods of Class.
3)w.r.t One class Definition, we can create multiple objects.
4)we can crate an object after loading the class definition otherwise
we get NameError
===============================X=================================

#objdemo.py
class Test:
def disp(self):
print("Test--disp()")
s=Sample()
s.disp()

class Sample:
def disp(self):
print("Sample--disp()")

#main program
t1=Test()
t1.disp()
=========================x============================

#Test.py
class Student1:
def disp1(self):
print("disp1()--student1 class")
s2=Student2 ()
s2.disp()

class Student2:
def disp(self):
print("disp2()--Student2 class")

#main program

274
s1=Student1()
s1.disp1()

======================================x=========================

#Program for reading employee Values and insert employee values in emp
table----Oracle
#EmpDataSave.py
import cx_Oracle
class Employee:
def readempvalues(self):
print("-"*50)
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
self.dsg=input("Enter Employee Designation:")
print("-"*50)
def saveempdata(self):
self.readempvalues()
try:
#we must write PDBC Code

con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
cur.execute("insert into employee values(%d,'%s',
%f,'%s') " %(self.eno,self.ename,self.sal,self.dsg))
con.commit()
print("\nEmployee Record Inserted Successfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)

#main program
e=Employee()
e.saveempdata()

========================x=========================x===========

#Program for accepting a number and generates mul table with Classes
and Objects
#MulTable.py---file name and acts as Module name
class MulTable:
def readvalue(self):
self.n=int(input("Enter a number:"))

def table(self):
try:
self.readvalue()
if(self.n<=0):
print("{} is invalid
input".format(self.n))
else:
print("-"*50)
print("Mul Table for :{}".format(self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} =
{}".format(self.n,i,self.n*i))
print("-"*50)

275
except ValueError:
print("Don't enter strs, symbols and alpha-
numerics")

#MulTableDemo.py
from MulTable import MulTable
mt=MulTable()
mt.table()

===================================================
Constructors in Python
===================================================
Index

=>Purpose of Constructors
=>Definition of Constructors
=>Rules / Properties of Constructors
=>Syntax for Constructors
=>Types of Constructors
a) Default or Parameterless Constructor
b) Parameterized Constructors
=>Programming Examples

===================================================
Constructors in Python
===================================================
=>The Purpose of Constructors in Python is that "To Initlize the
object".
=>Initlizing the object is nothing but Placing our own values without
leaving an object empty.

Definition of Constructors :

=>A contructor is one of the special method which is automatically or


implicitly called by PVM during Object Creation and whose role is to
Initlize the object.

Rules or Properties of Constructor

To Constructors in python program, we must follow the folllowing rules.


1) The Name of the Constructor is always init (self,.....)
2) Constructors will be called by PVM automatically or implicitly
during Object Creation
3) Constructors never returns any value
4) Constructors of Python Participates in Inheritance.
5) Constructors of Python can be overridden

Syntax for Constructors:

def init (self, list of formal Params if any):

276
Block of statemenets--Initlization of object

===================================================
Types of Constructors in Python
===================================================
=>Based on object creation, Constructors in Python are classified into
two types. They are
1. Default or Parameter-less Constructor
2. Parameterized Constructor

1. Default or Parameter-less Constructor

=>The purpose of Default or Parameter-less Constructor is that "To


initlize the multiple
objects of same class with same values "

Definition:

=>A constructor is said to be Default or Parameter-less if and only if


it never takes any
Parameters.

=>Syntax:

def init (self):

Block of statemenets--Initlization of object

====================================================================
2. Parameterized Constructor

=>The purpose of Parameter Constructor is that "To initlize the


multiple
objects of same class with different values "

Definition:

=>A constructor is said to be Parameter if and only if it always takes


Parameter(s).

=>Syntax:

def init (self, list of formal params):

Block of statemenets--Initlization of object

======================================================================
Note: In Class of Python, we can't define both default and
Parameterized constructors bcoz PVM can remember only latest

277
constructor (due to its interpretation Process) . To full fill the need
of both default and parameterized constructors , we define single
constructor with default parameter mechanism.

=====================================================

#ConstEx1.py
class Employee:
def init (self): # Default Constructor Definition
print("I am from constructor-calling automatically when
an obj is created")
self.eno=10
self.ename="RS"
self.sal=3.4

#main program
e1=Employee() # Object Creation
print("content of e1=",e1. dict ) # {--------}
e2=Employee() # Object Creation
print("content of e2=",e2. dict ) # {--------}

=====================================================

#ConstEx2.py
class Employee:
def init (self,k,v,r): # Parameterized Constructor
Definition
print("I am from constructor-calling automatically when
an obj is created")
self.eno=k
self.ename=v
self.sal=r

#main program
e1=Employee(10,"RS",2.3) # Object Creation
print("content of e1=",e1. dict ) # {--------}
e2=Employee(20,"DR",4.5) # Object Creation
print("content of e2=",e2. dict ) # {--------}
e3=Employee(30,"SK",2.5) # Object Creation
print("content of e3=",e3. dict ) # {--------}

=====================================================

#ConstEx3.py
class Employee:
def init (self): # Default Constructor Definition
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))

278
#main program
print("First Employee Information")
e1=Employee() # Object Creation
print("\t{}\t{}\t{}".format(e1.eno,e1.ename,e1.sal))
print("Second Employee Information")
e2=Employee() # Object Creation print("\t{}\t{}\
t{}".format(e2.eno,e2.ename,e2.sal))

=====================================================

#ConstEx4.py
class Employee:
def init (self,eno,ename,sal): # Parameterized Constructor
Definition
self.eno=eno
self.ename=ename
self.sal=sal

#main program
print("First Employee Information")
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
e1=Employee(empno,ename,esal) # Object Creation

print("\t{}\t{}\t{}".format(e1.eno,e1.ename,e1.sal))
print("\nSecond Employee Information")
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
e2=Employee(empno,ename,esal) # Object Creation print("\
t{}\t{}\t{}".format(e2.eno,e2.ename,e2.sal))

=====================================================

#Program for default constructor


#defaultconstex.py
class Test:
def init (self): # default constructor
print("-"*50)
self.a=10
self.b=20
print("Val of a=",self.a)
print("Val of b=",self.b)
print("-"*50)

#main program
print("Content of t1 object")
t1=Test() # Object Creation
print("Content of t2 object")
t2=Test() # Object Creation
print("Content of t1 object")
t3=Test() # Object Creation

279
=====================================================

#Program for default constructor and Parameterized constructor


#defaultparamconstex.py
class Test:
def init (self,k=1,v=2): # Paramerized and defacult
constructor
print("-"*50)
self.a=k
self.b=v
print("Val of a=",self.a)
print("Val of b=",self.b)
print("-"*50)
#main program
print("Content of t1 object--default constructor")
t1=Test() # Object Creation--calls default constructor
print("Content of t2 object--Parameterized constructor")
t2=Test(10,20) # Object Creation--calls Parameterized constructor

=====================================================

#Program for Parameterized constructor


#paramconstex.py
class Test:
def init (self,a,b): # Parameterized constructor
print("-"*50)
self.a=a
self.b=b
print("Val of a=",self.a)
print("Val of b=",self.b)
print("-"*50)

#main program
print("Content of t1 object")
t1=Test(10,20) # Object Creation
print("Content of t2 object")
t2=Test(100,200) # Object Creation
print("Content of t3 object")
t3=Test(1000,2000) # Object Creation

=====================================================

#Sample.py
class Employee:
def getempdata(self):
self.eno=10

280
self.ename="RS"
self.sal=3.4

#main program
e=Employee()
print("content of e=",e. dict ) # { }
e.getempdata() # we are calling this method explicitly
print("content of e=",e. dict ) # {---------}
=====================================================

======================================
Destructors in Python
======================================
=>We know that Garbage Collector is one of the in-built program in
python, which is running behind of every python program and whose is
role is to collect un-used memory space and it improves the performnace
of python based applications.
=>Every Garbage Collector Program is internally calling Destructor
program
=>The destructor name in python is def del (self).
=>The destructor always called by Garbage Collector when the program
executed completed for de-allocating the memory space. Where as
constructor called By PVM implicitly when object is created for
initlizing the object.

=>When the program execution is completed, GC calls its own destructor


to de-allocate the memory space of objects present in program.
(automatically GC running )

=>Hence , We have THREE programming conditions for calling GC and to


make the garbage collector to call destructor Functions.

a) By default (or) automatically GC calls destructor, when the program


execution completed.
b) Make the object refereence as None by Forcefully
Syntax : objname=None
c) delete the object by using del by Forcefully
Syntax:- del objname

281
=>Syntax:

def del (self):

=======================================================================
Garbage Collector

=>Garbage Collector contains a pre-defined module called "gc"


=>Here gc contains the following contains the following Functions.

1) isenabled()
2) enable()
3) disable()
=>GC is not under control Programmer but it always maintained and
mangaged by OS and PVM
==============================x========================================
====

#DestEx1.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("Program execution completed:")

=========================================================

#DestEx2.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program

282
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("\nProgram execution completed:")

=========================================================

#DestEx3.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("\nProgram execution completed:")
=========================================================
#DestEx4.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("No longer interested to maintain memory space of e1")
e1=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("No longer interested to maintain memory space of e2")
e2=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("No longer interested to maintain memory space of e3")
e3=None # GC automatically calls del (self)---forcefully calling GC
print("\nProgram execution completed:")

#DestEx5.py

283
import time
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("No longer interested to maintain memory space of e1")
time.sleep(5)
e1=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("No longer interested to maintain memory space of e2")
time.sleep(5)
e2=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("No longer interested to maintain memory space of e3")
time.sleep(5)
e3=None # GC automatically calls del (self)---forcefully calling GC
print("\nProgram execution completed:")
#DestEx6.py
import time
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("No longer interested to maintain memory space of e1")
time.sleep(5)
del e1 # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("No longer interested to maintain memory space of e2")
time.sleep(5)
del e2 # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("No longer interested to maintain memory space of e3")
time.sleep(5)
del e3 # GC automatically calls del (self)---forcefully calling GC

284
print("\nProgram execution completed:")

next peg

#gcex1.py
import gc
print("Is GC running=",gc.isenabled()) # True
print("\nThis is Python Class")
a=10
b=20
c=a+b
print("sum=",c)

#gcex2.py
import gc
print("Line--3-->Is GC running=",gc.isenabled()) # True
print("\nThis is Python Class")
print("Going on OOPS concept")
gc.disable()
print("Now Destructor concept is going on:")
print("Line--8-->Is GC running=",gc.isenabled()) # False
print("After oops , regular expr topic will start")
gc.enable()
print("Line--11-->Is GC running=",gc.isenabled()) # True
print("Later we start numpy and pandas topic")

==============================================================
#gcex3.py
import gc
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("Line--14-->Is GC running=",gc.isenabled()) # True
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
gc.disable()
print("Line--16-->Is GC running=",gc.isenabled()) # False
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("\nProgram execution completed:")
=========================================================

#studpick.py
from Student import Student

285
import pickle
class SaveData:
def savestuddata(self):
with open("stud.data","ab") as fp:
while(True):
print("-"*50)
stno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
s=Student(stno,sname,marks)
pickle.dump(s,fp)
print("\nStudent Data Saved in a file:")
print("-"*50)
ch=input("Do u want to insert another
Record(yes/no):")
if(ch=="no"):
print("Thx for using this program")
break

#main program
sd=SaveData()
sd.savestuddata()

#studunpick.py
import pickle
class ReadData:
def readrecord(self):
try:
with open("stud.data","rb") as fp:
print("-"*50) print("Stno\
tName\tMarks")
print("-"*50)
while(True):
try:
record=pickle.load(fp)
record.dispstuddet()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File Not found Error:")

#main program
rd=ReadData()
rd. readrecord()

jun-27-2022

286
>17-jun-22<

==========================================================
Object Oriented Principles (or) Features (or) Concepts (12 days)
==========================================================
Index

=>Models or Paradigams of Programming Languages


=>What are advtanges of Object Oriented Principles
=>What are Object Oriented Principles
1) Classes
2) Object
3) Data Encapsulation
4) Data Abstraction
5) Inheritance
6) Polymorphism
7) Message Passing
=>Programming Examples

==========================================================
Object Oriented Principles (or) Features (or) Concepts
==========================================================
=>In Real time, to develop any project, we need to use a programming
language.
=>The Programming Laguages satisfies two types of Principles. They are
1. Procedure Oriented Principles( Functional )
2. Object Oriented Principles.
=>If Programming Laguage satisfies Procedure Oriented Principles then
that language is
called Procedure Oriented Programming Laguage.
Examples: 8086, C, Pascal, COBOL...etc Oracle 7.x
=>If Programming Laguage satisfies Object Oriented Principles then that
language is called
Object Oriented Programming Laguage.

=>PYTHON is one of the Functional and object oriented programing Lang.


=>Even though PYTHON belongs to Functional and object oriented
programing Lang, Internally every thing treated as objects.

"Every Thing is an object "---Python


(OR)
Advantages of OO Principles

=>In Object, we can store large Volume of Data and achieves Platform
Independency
(Python)
=>The confidential Data can be transfered between multiple remote
machine in the
form cipher text (Encrypted format). So that security can be
enhanced ( Improved).
=>The Large of Volume of Data Transfered between Multiple Machines all
at once in

287
the form of object and leads to effective communication.
=>All Values are available around the objects and provides effective
memory
Management.
===============================X=======================================

===============================================
List of Object Oriented Principles
===============================================
=>To Say Python is one of the Object Oriented Programming Language, It
has to Satisfy the following OOPs Principles.
1) Classes
2) Objects
3) Data Encapsulation
4) Data Abstraction
5) Inheritance
6) Polymorphism
7) Message Passing (already discussed )
================================x==================================

===============================
1) Classes
===============================
=>The purpose of Classes concept is that "To develop Programmer Defined
Classes and To
develop any real time application in OOPs"
=>The purpose of Developing Programmer Defined Classes is that "To
customize the
operations on objects"
=>To develop Programmer Defined Classes with classes concept, we use a
keyword called
"class"
=>Every Programmer-defined class is considered as Programmer-Defined
data type.
=>Every Python Program must write with classes concept. Without classes
concept there is Python Program.

=>Definition of Class:

=>A class is a collection Data Members and Methods.

=>Data Members are also called Variables / attributes / Fields.


=>Functions are called Methods in OOPs
=>When we define a class, memory space is not created for Data Members
and Methods but whose space is created when we create an object.
=>Hence Class does not contain memory space and object contains memory
space.

288
====================================================
Syntax for defining a class in Python
====================================================

class <clsname>:
Class Level Data Members
def instancemethodname(self,list of formal params if
any):

--------Instance Data Members-----


Specific Operations

@classmethod
def classlevelmethod(cls,,list of formal params if any):

--------Class Level Data Members-----


Common Operations

@staticmethod
def staticmethodname(list of formal params if any):

------Utility Operations------------

=======================================================================

============================================
Types of Data Members in Class of Python
============================================
=>In class of python, we can defined two types of Data Members. They
are
1) Instance Data Members .
2) Class Level Data Members.

1) Instance Data Members .

=>Instance data members are used for storing specific values and they
are always available as a part of object and hence they are also called
object level data members.
=>Instnace Data members memory space created every time when we create
an object.
=>Instance Data Members can be specified in three places. They are
1) through object.
2) through Instance Method.
3) throughConstructor.
=>We can access the Instance Data Members by using two syntaxes. They
are
a) by using object name-----> objectname.instance
data member
b) by using implicit object---->
self..instance data member

2) Class Level Data Members .

289
=>Class Level Data Members are used for storing Common values and they
are always
available to all objects of same class
=>Class Level Data Members memory space created Only time
irrespective number of objects are created.
=>Class Level Data Members can be specified in 2 places. They are
1) Inside of Class definition.
2) Inside of Class Level Method Definition.
=>We can access the Class Level Data Members by using two syntaxes.
They are
a) by using Class Name name-----> classname.class
level data member
b) by using object name----------->
objectname.class level data member

#Program for storing student details such as stno,name and marks


#StudEx2.py-----Instance Data Members
class Student:pass

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
s1.stno=10
s1.sname="RS"
s1.marks=11.22
#add the Instance Data Members to s2
s2.stno=20
s2.sname="JG"
s2.marks=33.33
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks)
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print(" ")

290
#Program for storing student details such as stno,name and marks
#StudEx3.py-----Instance Data Members
class Student:pass

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
print("First Student Details")
print(" ")
s1.stno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print(" ")
#add the Instance Data Members to s2
print("Second Student Details")
print(" ")
s2.stno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks)
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print(" ")
=======================================================================

#Program for storing student details such as stno,name and marks


#StudEx4.py-----Class Level Data Members and Instance Data Members
class Student:
crs="PYTHON" # Here 'crs' is called Class Level Data Member

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
print("First Student Details")
print(" ")
s1.stno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print(" ")
#add the Instance Data Members to s2
print("Second Student Details")
print(" ")
s2.stno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print(" ")

291
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks) # Accessing Instance Data
Members(stno,sname and marks) w.r.t object name
print("Studennt Course=",Student.crs)#Accessing class Level Data
member(crs) by using class name
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print("Studennt Course=",Student.crs)# Accessing class Level Data
member by using class name
print(" ")

#Program for storing student details such as stno,name and marks


#StudEx5.py-----Class Level Data Members and Instance Data Members
class Student:
crs="PYTHON" # Here 'crs' is called Class Level Data Member

#main program
s1=Student() # Object creation
s2=Student() # Object creation
#add the Instance Data Members to s1
print("First Student Details")
print(" ")
s1.stno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print(" ")
#add the Instance Data Members to s2
print("Second Student Details")
print(" ")
s2.stno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print(" ")
print("Content of s1")
print(" ")
print("Student Number=",s1.stno)
print("Student Name=",s1.sname)
print("Student Marks=",s1.marks) # Accessing Instance Data
Members(stno,sname and marks) w.r.t object name
print("Studennt Course=",s1.crs)#Accessing class Level Data member(crs)
by using object name
print(" ")
print("Content of s2")
print(" ")
print("Student Number=",s2.stno)
print("Student Name=",s2.sname)
print("Student Marks=",s2.marks)
print("Studennt Course=",s2.crs)# Accessing class Level Data member by
using object name
print(" ")

292
#EmpEx1.py------>Demonstrates Class Level and Instance Data Members
class Employee:
cname="IBM" # class level data member

#main program
e1=Employee() # Object creation
e2=Employee() # Object creation
# Read Employee object1 data
print("First Employee Details")
print(" ")
e1.eno=int(input("Enter Employee Number:"))
e1.ename=input("Enter Employee Name:")
e1.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Second Employee Details")
print(" ")
e2.eno=int(input("Enter Employee Number:"))
e2.ename=input("Enter Employee Name:")
e2.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Content of e1")
print(" ")
print("Employee Number:{}".format(e1.eno))
print("Employee Name:{}".format(e1.ename))
print("Employee Salary:{}".format(e1.sal))
print("Employee Working Company:{}".format(Employee.cname))
print(" ")
print("Content of e2")
print(" ")
print("Employee Number:{}".format(e2.eno))
print("Employee Name:{}".format(e2.ename))
print("Employee Salary:{}".format(e2.sal))
print("Employee Working Company:{}".format(Employee.cname))
print(" ")

#EmpEx2.py------>Demonstrates Class Level and Instance Data Members


class Employee:
cname="IBM" # class level data member

#main program
e1=Employee() # Object creation
e2=Employee() # Object creation
# Read Employee object1 data
print("First Employee Details")
print(" ")
e1.eno=int(input("Enter Employee Number:"))
e1.ename=input("Enter Employee Name:")
e1.sal=float(input("Enter Employee Salary:"))
print(" ")
print("Second Employee Details")
print(" ")
e2.eno=int(input("Enter Employee Number:"))
e2.ename=input("Enter Employee Name:")
e2.sal=float(input("Enter Employee Salary:"))

293
print(" ")
print("Content of e1")
print(" ")
print("Employee Number:{}".format(e1.eno))
print("Employee Name:{}".format(e1.ename))
print("Employee Salary:{}".format(e1.sal))
print("Employee Working Company:{}".format(e1.cname))
print(" ")
print("Content of e2")
print(" ")
print("Employee Number:{}".format(e2.eno))
print("Employee Name:{}".format(e2.ename))
print("Employee Salary:{}".format(e2.sal))
print("Employee Working Company:{}".format(e2.cname))
print(" ")

#CircleArea.py
class Circle:
PI=3.14

#main program
c1=Circle()
c1.r=float(input("Enter Radious:"))
c1.arc=Circle.PI*c1.r**2
print(" ")
print("Given radious:{}".format(c1.r))
print("Area of Circle:{}".format(c1.arc))
print(" ")

21-jun-2020

=================================================
Types of Methods in class of Python
=================================================
=>In a class of Python, we can defined 3 types of Methods. They are
1) Instance Methods
2) Class Level Method
3) Static Method

1) Instance Methods

=>Instance Methods are used for Performing Specific Operations on


objects and these
methods are also called Object Level Methods.
=>Syntax:- def instancemethodname(self,list of formal params if
any):

----Specify Instance Data Members and


Operations----

294
=>Instance Methods always takes "self" as a First Formal Parameter for
holding or storing
Current Object Memory Address or Reference or Id.
=>Instnace Method Must be accessed w.r.t object name or self.

objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()

What is "self" ( implicit object)

=>"self" is one of the implicit object created by Python Execution


Environment for storing
current object address or id or Reference.
=>"self" is always taken as a First Formal Parameter in Instance Method
Definition.
=>Programtically "self" must be used as a part of corresponding
Instance Method Defintion
only but not Other Part of the program.
=======================================================================
=
2) Class Level Method:

=>Class Level Methods are used for Performing Common Operations for all
the objects same
class. In Other words Class Level Methods are used for specifying
Class Level Data Members.
=>Syntax:
@classmethod
def classlevelmethodname(cls,list of formal
params if any):

----Specify Class Level Data Members and


Operations----

=>Class Level Method always takes "cls" as a First Formal Parameter and
it is an alternative
name for Corresponding Class Name.
=>Class Level Method Must be accessed w.r.t class name or cls

classname.ClassLevelMethodName()
(OR)
cls.ClassLevelMethodName()
(OR)
self.ClassLevelMethodName()

What is "cls"

=>"cls" is one of the implicit name created by Python Execution


Environment for representing the class name .
=>"cls" is always taken as a First Formal Parameter in Class Level
Method Definition.
=>Programtically "cls" must be used as a part of corresponding Class
Level Method Defintion
only but not Other Part of the program.

295
3) Static Method-----Tomorrow class

#Program for storing student details such as stno,name and marks


#InstanceMethodEx1.py
class Student:
def readstuddata(self): # Instance Method
print("Id of current object=",id(self))
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstuddata(self): # Instance Method
print(" ")
print("Id of current object=",id(self))
print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print(" ")

#main program
s1=Student() # Object creation
s2=Student() # Object creation
print("First Student Details")
print(" ")
print("Id of s1 in main program:",id(s1))
s1.readstuddata() # Method Call
print(" ")
print("Second Student Details")
print(" ")
print("Id of s2 in main program:",id(s2))
s2.readstuddata() # Method Call
print(" ")
print("Content of s1")
print("Id of s1 in main program:",id(s1))
s1.dispstuddata() # Method Call
print("Content of s2")
print("Id of s2 in main program:",id(s2))
s2.dispstuddata() # Method Call

#Program for storing student details such as stno,name and marks


#InstanceMethodEx2.py
class Student:
def readstuddata(self): # Instance Method
print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

296
self.dispstuddata() # calling Instance Method

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print(" ")

#main program
s1=Student() # Object creation
s2=Student() # Object creation
print("First Student Details")
s1.readstuddata() # Method Call
print("Second Student Details")
s2.readstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx1.py
class Student:
@classmethod
def getcourse(cls):
cls.crs="PYTHON"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx2.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"

def readstuddata(self): # Instance Method


print(" ")

297
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx3.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
Student.getcompaddress() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

298
#Program for storing student details such as stno,name and marks
#ClassLevelMethodEx4.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
Student.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx5.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
cls.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))

299
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

#Program for storing student details such as stno,name and marks


#ClassLevelMethodEx6.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
cls.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


Student.getcourse() # calling Class Level Method
print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

300
#Program for storing student details such as stno,name and marks
#ClassLevelMethodEx7.py
class Student:
@classmethod
def getcourse(cls):
Student.crs="PYTHON"
cls.getcompaddress() # Calling Class Level Method

@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"

def readstuddata(self): # Instance Method


print(" ")
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")

def dispstuddata(self): # Instance Method


self.getcourse() # calling Class Level Method
print("Student Number={}".format(self.stno))
print("Student Name={}".format(self.sname))
print("Student Marks={}".format(self.marks))
print("Student Course={}".format(Student.crs))
print("Student Comp Address={}".format(Student.addr))
print(" ")

#main program
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()

301
=================================================
Types of Methods in class of Python
=================================================

=>In a class of Python, we can defined 3 types of Methods. They are


1) Instance Methods
2) Class Level Method
3) Static Method

1) Instance Methods

=>Instance Methods are used for Performing Specific Operations on


objects and these
methods are also called Object Level Methods.
=>Syntax:- def instancemethodname(self,list of formal params if
any):

----Specify Instance Data Members and


Operations----

=>Instance Methods always takes "self" as a First Formal Parameter for


holding or storing
Current Object Memory Address or Reference or Id.
=>Instnace Method Must be accessed w.r.t object name or self.

objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()

What is "self" ( implicit object)

=>"self" is one of the implicit object created by Python Execution


Environment for storing
current object address or id or Reference.
=>"self" is always taken as a First Formal Parameter in Instance Method
Definition.
=>Programtically "self" must be used as a part of corresponding
Instance Method Defintion
only but not Other Part of the program.
=======================================================================
=
2) Class Level Method:

=>Class Level Methods are used for Performing Common Operations for all
the objects same
class. In Other words Class Level Methods are used for specifying
Class Level Data Members.
=>Syntax:
@classmethod
def classlevelmethodname(cls,list of formal
params if any):

302
----Specify Class Level Data Members and
Operations----

=>Class Level Method always takes "cls" as a First Formal Parameter and
it is an alternative
name for Corresponding Class Name.
=>Class Level Method Must be accessed w.r.t class name or cls

classname.ClassLevelMethodName()
(OR)
cls.ClassLevelMethodName()
(OR)
self.ClassLevelMethodName()

What is "cls"

=>"cls" is one of the implicit name created by Python Execution


Environment for representing the class name .
=>"cls" is always taken as a First Formal Parameter in Class Level
Method Definition.
=>Programtically "cls" must be used as a part of corresponding Class
Level Method Defintion
only but not Other Part of the program.

3) Static Method:

=>Static Methods are those which are used for Performing utility
Operation or Universal Operation
=>Static Methods Definition neither takes "self" nor takes "cls" but
it takes an object as parameter (if req) which belongs other classes
=>Syntax:
@staticmethod
def staticmethodname(list of formal params if
any):

----Utility or Universal Operations----

=>=>Static Methods Must be accessed w.r.t class name or object name

classname.Static Method name()


(OR)
objectname.Static Method Name()
================================X=====================================

303
#Program demonstrating the importnace of static method
#StaticMethodEx1.py
class Emp:
def readempvalues(self):
print("-"*50)
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)

class Student:
def readstudentvalues(self):
print("-"*50)
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College Name:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("Enter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
print("-"*50)

class Hyd:
@staticmethod
def dispobjvalues( obj ):
print("-"*50)
for k,v in obj. dict .items():
print("\t{}--->{}".format(k,v))
print("-"*50)

#main program
e=Emp()
s=Student()
t=Teacher()
#read the values for the objects of Emp ,Student and Teacher
print("Employee Information:")
e.readempvalues()
print("Student Information:")
s.readstudentvalues()
print("Teacher Information:")
t.readteachervalues()
#display any type of object values
print("Content of Employee:")
Hyd.dispobjvalues(e)
print("Content of Student:")
Hyd.dispobjvalues(s)
print("Content of Teacher:")
Hyd.dispobjvalues(t)

304
#Program demonstrating the importnace of static method
#StaticMethodEx2.py
class Emp:
def readempvalues(self):
print("-"*50)
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)

class Student:
def readstudentvalues(self):
print("-"*50)
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College Name:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("Enter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
print("-"*50)

class Hyd:
@staticmethod
def dispobjvalues( obj ):
print("-"*50)
for k,v in obj. dict .items():
print("\t{}--->{}".format(k,v))
print("-"*50)

#main program
e=Emp()
s=Student()
t=Teacher()
#read the values for the objects of Emp ,Student and Teacher
print("Employee Information:")
e.readempvalues()
print("Student Information:")
s.readstudentvalues()
print("Teacher Information:")
t.readteachervalues()
#display any type of object values
h=Hyd()
print("Content of Employee:")
h.dispobjvalues(e)
print("Content of Student:")
h.dispobjvalues(s)
print("Content of Teacher:")
h.dispobjvalues(t)

l=list()

305
===================================================
objects in Python
===================================================
=>When we define a class, memory space is not created for Data Members
and Methods but whose memory is created when we create an object w.r.t
class name.
=>To do any Data Processing, It is mandatory to create an object.
=>To create an object, there must exists a class Definition otherwise
we get NameError

Definition of object:

=>Instance of a class is called object ( Instance is nothing but


allocating sufficient memory space for the Data Members and Methods of
a class)

Syntax for creating an object

varname=classname()

Examples: create an object of Student

so=Student()
Example:- create an object Employee

eo=Employee()

Differences Betwwen Classes and Objects

Class:

1) A class is a collection of Data Members and Methods


2) When we define a class, memory space is not created for Data Members
and Methods and it can be treated as specification / model for real
time application.
3) Definition of a perticular exists only once
4) When we develop any Program with OOPs principles, Class Loaded First
only once in main memory.

Objects:

1) Instance of a class is called Object


2) When we create an object, we get the memory space for Data members
and Methods of Class.
3)w.r.t One class Definition, we can create multiple objects.
4)we can crate an object after loading the class definition otherwise
we get NameError
===============================X=================================

306
#objdemo.py
class Test:
def disp(self):
print("Test--disp()")
s=Sample()
s.disp()

class Sample:
def disp(self):
print("Sample--disp()")

#main program
t1=Test()
t1.disp()
=========================x============================

#Test.py
class Student1:
def disp1(self):
print("disp1()--student1 class")
s2=Student2 ()
s2.disp()

class Student2:
def disp(self):
print("disp2()--Student2 class")

#main program
s1=Student1()
s1.disp1()

======================================x=========================

#Program for reading employee Values and insert employee values in emp
table----Oracle
#EmpDataSave.py
import cx_Oracle
class Employee:
def readempvalues(self):
print("-"*50)
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
self.dsg=input("Enter Employee Designation:")
print("-"*50)
def saveempdata(self):
self.readempvalues()
try:
#we must write PDBC Code

con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
cur.execute("insert into employee values(%d,'%s',
%f,'%s') " %(self.eno,self.ename,self.sal,self.dsg))
con.commit()
print("\nEmployee Record Inserted Successfully")
except cx_Oracle.DatabaseError as db:

307
print("Prob in Database:",db)

#main program
e=Employee()
e.saveempdata()

========================x=========================x===========

#Program for accepting a number and generates mul table with Classes
and Objects
#MulTable.py---file name and acts as Module name
class MulTable:
def readvalue(self):
self.n=int(input("Enter a number:"))

def table(self):
try:
self.readvalue()
if(self.n<=0):
print("{} is invalid
input".format(self.n))
else:
print("-"*50)
print("Mul Table for :{}".format(self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} =
{}".format(self.n,i,self.n*i))
print("-"*50)
except ValueError:
print("Don't enter strs, symbols and alpha-
numerics")

#MulTableDemo.py
from MulTable import MulTable
mt=MulTable()
mt.table()

===================================================
Constructors in Python
===================================================
Index

=>Purpose of Constructors
=>Definition of Constructors
=>Rules / Properties of Constructors
=>Syntax for Constructors
=>Types of Constructors
a) Default or Parameterless Constructor
b) Parameterized Constructors
=>Programming Examples

308
===================================================
Constructors in Python
===================================================
=>The Purpose of Constructors in Python is that "To Initlize the
object".
=>Initlizing the object is nothing but Placing our own values without
leaving an object empty.

Definition of Constructors :

=>A contructor is one of the special method which is automatically or


implicitly called by PVM during Object Creation and whose role is to
Initlize the object.

Rules or Properties of Constructor

To Constructors in python program, we must follow the folllowing rules.


1) The Name of the Constructor is always init (self,.....)
2) Constructors will be called by PVM automatically or implicitly
during Object Creation
3) Constructors never returns any value
4) Constructors of Python Participates in Inheritance.
5) Constructors of Python can be overridden

Syntax for Constructors:

def init (self, list of formal Params if any):

Block of statemenets--Initlization of object

===================================================
Types of Constructors in Python
===================================================
=>Based on object creation, Constructors in Python are classified into
two types. They are
1. Default or Parameter-less Constructor
2. Parameterized Constructor

1. Default or Parameter-less Constructor

=>The purpose of Default or Parameter-less Constructor is that "To


initlize the multiple
objects of same class with same values "

Definition:

=>A constructor is said to be Default or Parameter-less if and only if


it never takes any
Parameters.

=>Syntax:

309
def init (self):

Block of statemenets--Initlization of object

====================================================================
2. Parameterized Constructor

=>The purpose of Parameter Constructor is that "To initlize the


multiple
objects of same class with different values "

Definition:

=>A constructor is said to be Parameter if and only if it always takes


Parameter(s).

=>Syntax:

def init (self, list of formal params):

Block of statemenets--Initlization of object

======================================================================
Note: In Class of Python, we can't define both default and
Parameterized constructors bcoz PVM can remember only latest
constructor (due to its interpretation Process) . To full fill the need
of both default and parameterized constructors , we define single
constructor with default parameter mechanism.

=====================================================

#ConstEx1.py
class Employee:
def init (self): # Default Constructor Definition
print("I am from constructor-calling automatically when
an obj is created")
self.eno=10
self.ename="RS"
self.sal=3.4

#main program
e1=Employee() # Object Creation
print("content of e1=",e1. dict ) # {--------}
e2=Employee() # Object Creation
print("content of e2=",e2. dict ) # {--------}

=====================================================

310
#ConstEx2.py
class Employee:
def init (self,k,v,r): # Parameterized Constructor
Definition
print("I am from constructor-calling automatically when
an obj is created")
self.eno=k
self.ename=v
self.sal=r

#main program
e1=Employee(10,"RS",2.3) # Object Creation
print("content of e1=",e1. dict ) # {--------}
e2=Employee(20,"DR",4.5) # Object Creation
print("content of e2=",e2. dict ) # {--------}
e3=Employee(30,"SK",2.5) # Object Creation
print("content of e3=",e3. dict ) # {--------}

=====================================================

#ConstEx3.py
class Employee:
def init (self): # Default Constructor Definition
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))

#main program
print("First Employee Information")
e1=Employee() # Object Creation
print("\t{}\t{}\t{}".format(e1.eno,e1.ename,e1.sal))
print("Second Employee Information")
e2=Employee() # Object Creation print("\t{}\t{}\
t{}".format(e2.eno,e2.ename,e2.sal))

=====================================================

#ConstEx4.py
class Employee:
def init (self,eno,ename,sal): # Parameterized Constructor
Definition
self.eno=eno
self.ename=ename
self.sal=sal

#main program
print("First Employee Information")
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
e1=Employee(empno,ename,esal) # Object Creation

print("\t{}\t{}\t{}".format(e1.eno,e1.ename,e1.sal)) print("\
nSecond Employee Information")

311
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
e2=Employee(empno,ename,esal) # Object Creation print("\
t{}\t{}\t{}".format(e2.eno,e2.ename,e2.sal))

=====================================================

#Program for default constructor


#defaultconstex.py
class Test:
def init (self): # default constructor
print("-"*50)
self.a=10
self.b=20
print("Val of a=",self.a)
print("Val of b=",self.b)
print("-"*50)

#main program
print("Content of t1 object")
t1=Test() # Object Creation
print("Content of t2 object")
t2=Test() # Object Creation
print("Content of t1 object")
t3=Test() # Object Creation

=====================================================

#Program for default constructor and Parameterized constructor


#defaultparamconstex.py
class Test:
def init (self,k=1,v=2): # Paramerized and defacult
constructor
print("-"*50)
self.a=k
self.b=v
print("Val of a=",self.a)
print("Val of b=",self.b)
print("-"*50)
#main program
print("Content of t1 object--default constructor")
t1=Test() # Object Creation--calls default constructor
print("Content of t2 object--Parameterized constructor")
t2=Test(10,20) # Object Creation--calls Parameterized constructor

=====================================================

312
#Program for Parameterized constructor
#paramconstex.py
class Test:
def init (self,a,b): # Parameterized constructor
print("-"*50)
self.a=a
self.b=b
print("Val of a=",self.a)
print("Val of b=",self.b)
print("-"*50)

#main program
print("Content of t1 object")
t1=Test(10,20) # Object Creation
print("Content of t2 object")
t2=Test(100,200) # Object Creation
print("Content of t3 object")
t3=Test(1000,2000) # Object Creation

=====================================================

#Sample.py
class Employee:
def getempdata(self):
self.eno=10
self.ename="RS"
self.sal=3.4

#main program
e=Employee()
print("content of e=",e. dict ) # { }
e.getempdata() # we are calling this method explicitly
print("content of e=",e. dict ) # {---------}
=====================================================

313
======================================
Destructors in Python
======================================
=>We know that Garbage Collector is one of the in-built program in
python, which is running behind of every python program and whose is
role is to collect un-used memory space and it improves the performnace
of python based applications.
=>Every Garbage Collector Program is internally calling Destructor
program
=>The destructor name in python is def del (self).
=>The destructor always called by Garbage Collector when the program
executed completed for de-allocating the memory space. Where as
constructor called By PVM implicitly when object is created for
initlizing the object.

=>When the program execution is completed, GC calls its own destructor


to de-allocate the memory space of objects present in program.
(automatically GC running )

=>Hence , We have THREE programming conditions for calling GC and to


make the garbage collector to call destructor Functions.

a) By default (or) automatically GC calls destructor, when the program


execution completed.
b) Make the object refereence as None by Forcefully
Syntax : objname=None
c) delete the object by using del by Forcefully
Syntax:- del objname

=>Syntax:

def del (self):

=======================================================================
Garbage Collector

=>Garbage Collector contains a pre-defined module called "gc"


=>Here gc contains the following contains the following Functions.

1) isenabled()
2) enable()
3) disable()
=>GC is not under control Programmer but it always maintained and
mangaged by OS and PVM
==============================x========================================
====

314
#DestEx1.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("Program execution completed:")

=========================================================

#DestEx2.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("\nProgram execution completed:")

=========================================================

#DestEx3.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("\nProgram execution completed:")
=========================================================

315
#DestEx4.py
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("No longer interested to maintain memory space of e1")
e1=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("No longer interested to maintain memory space of e2")
e2=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("No longer interested to maintain memory space of e3")
e3=None # GC automatically calls del (self)---forcefully calling GC
print("\nProgram execution completed:")

#DestEx5.py
import time
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("No longer interested to maintain memory space of e1")
time.sleep(5)
e1=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("No longer interested to maintain memory space of e2")
time.sleep(5)
e2=None # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("No longer interested to maintain memory space of e3")
time.sleep(5)
e3=None # GC automatically calls del (self)---forcefully calling GC
print("\nProgram execution completed:")

316
#DestEx6.py
import time
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
print("No longer interested to maintain memory space of e1")
time.sleep(5)
del e1 # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("No longer interested to maintain memory space of e2")
time.sleep(5)
del e2 # GC automatically calls del (self)---forcefully calling GC
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("No longer interested to maintain memory space of e3")
time.sleep(5)
del e3 # GC automatically calls del (self)---forcefully calling GC
print("\nProgram execution completed:")

next peg

#gcex1.py
import gc
print("Is GC running=",gc.isenabled()) # True
print("\nThis is Python Class")
a=10
b=20
c=a+b
print("sum=",c)

#gcex2.py
import gc
print("Line--3-->Is GC running=",gc.isenabled()) # True
print("\nThis is Python Class")
print("Going on OOPS concept")
gc.disable()
print("Now Destructor concept is going on:")
print("Line--8-->Is GC running=",gc.isenabled()) # False
print("After oops , regular expr topic will start")
gc.enable()
print("Line--11-->Is GC running=",gc.isenabled()) # True
print("Later we start numpy and pandas topic")

==============================================================

317
#gcex3.py
import gc
class Emp:
def init (self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print(self.eno,self.ename,self.sal)

def del (self):


print("GC calls del () for de-allocating mem space:")

#main program
print("Program execution started:")
print("Line--14-->Is GC running=",gc.isenabled()) # True
print("\ncontent of e1")
e1=Emp(10,"RS",1.2)
gc.disable()
print("Line--16-->Is GC running=",gc.isenabled()) # False
print("\ncontent of e2")
e2=Emp(20,"DR",2.2)
print("\ncontent of e3")
e3=Emp(30,"TR",3.2)
print("\nProgram execution completed:")
=========================================================

#studpick.py
from Student import Student
import pickle
class SaveData:
def savestuddata(self):
with open("stud.data","ab") as fp:
while(True):
print("-"*50)
stno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
s=Student(stno,sname,marks)
pickle.dump(s,fp)
print("\nStudent Data Saved in a file:")
print("-"*50)
ch=input("Do u want to insert another
Record(yes/no):")
if(ch=="no"):
print("Thx for using this program")
break

#main program
sd=SaveData()
sd.savestuddata()

318
#studunpick.py
import pickle
class ReadData:
def readrecord(self):
try:
with open("stud.data","rb") as fp:
print("-"*50) print("Stno\
tName\tMarks")
print("-"*50)
while(True):
try:
record=pickle.load(fp)
record.dispstuddet()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File Not found Error:")

#main program
rd=ReadData()
rd. readrecord()

jun-27-2022

================================================
Data Encapsulation and Data Abstraction
================================================
Data Encapsulation:

=>The Process of Hiding the confidential Information / Data / Methods


from external Programmers / end users is called Data Encapsulation.
=>The Purpose of Encapsulation concept is that "To Hide Confidental
Information / Features of Class (Data Members and Methods ) ".
=>Data Encapsulation can be applied in two levels. They are
a) At Data Members Level
b) At Methods Level

=>To implement Data Encapsulation in python programming, The Data


Members , Methods must be preceded with double under score ( _ _ )

Syntax1:- class <ClassName>:


def methodname(self):
self. Data
MemberName1=Value1
self. Data
MemberName2=Value2

self. Data MemberName-


n=Value-n

(OR)
Syntax1:- class
<ClassName>:
def init (self):

319
self. Data
MemberName1=Value1
self. Data
MemberName2=Value2

self. Data MemberName-


n=Value-n

Syntax2:- class <ClassName>:


def methodname(self):
self.Data MemberName1=Value1
self.Data MemberName2=Value2

self.Data MemberName-
n=Value-n

Example1:

#account.py----file name and treated as module name


class Account:
def getaccountdet(self):
self. acno=34567
self.cname="Rossum"
self. bal=34.56
self.bname="SBI"
self. pin=1234
self.pincode=4444444
#here acno,bal and pin are encapsulated

Example2:

#account1.py----file name and treated as module name


class Account1:
def getaccountdet(self): # here getaccountdet() is made
is encapsulated
self.acno=34567
self.cname="Rossum"
self.bal=34.56
self.bname="SBI"
self.pin=1234
self.pincode=4444444

==============================================================
Data Abstraction:

=>The Process of retrieving / extracting Essential Details without


considering Hidden Details is called Data Abstraction.

Example1:

#others.py---This Program access only cname,bname and pincode only


from account import Account
ao=Account()
ao.getaccountdet()

320
#print("Account Number={}".format(ao.acno)) Not Possible to access
print("Account Holder Name={}".format(ao.cname))
#print("Account Bal={}".format(ao.bal)) Not Possible to access
print("Account Branch Name={}".format(ao.bname))
#print("Account PIN={}".format(ao.pin)) Not Possible to access
print("Account Branch Pin Code={}".format(ao.pincode))

Example2:

#others1.py--here we can't access method itself. so that we cant access


Instance Data Members.
from account1 import Account1
ao=Account1()
#ao.getaccountdet()---can't access
#print("Account Number={}".format(ao.acno))
#print("Account Holder Name={}".format(ao.cname))
#print("Account Bal={}".format(ao.bal))
#print("Account Branch Name={}".format(ao.bname))
#print("Account PIN={}".format(ao.pin))
#print("Account Branch Pin Code={}".format(ao.pincode))

Note:- We can't apply Data Encapsulation on Constructors in Python but


whose Initlized Data Memebrs can be encapsulated.

==========================================================
#Acc1.py---file name and module name
class Account:
def init (self):
self. acno=10 # encapsulated
self.cname="Rossum"
self. bal=4.5 # encapsulated
self. pin=4567 # encapsulated
self.bname="SBI"
==========================================================

#Acc2.py---file name and module name


class Account:
def getaccdetails(self):
self.acno=10
self.cname="Rossum"
self.bal=4.5
self.pin=4567
self.bname="SBI"
===========================================================

#Acc3.py---file name and module name


class Account:
def init (self):
self.acno=10 # encapsulated
self.cname="Rossum"
self.bal=4.5 # encapsulated
self.pin=4567 # encapsulated
self.bname="SBI"

===========================================================

321
#OtherProgEx1.py
from Acc1 import Account
ac=Account() # Object Creation
#print("Account Number=",ac.acno) can't access
print("Account Holder Name=",ac.cname)
#print("Account Balance=",ac.bal) can't access
#print("Account PIN=",ac.pin)
print("Account Holder Branch Name=",ac.bname)

========================================================

#OtherProgEx2.py
from Acc2 import Account
ac=Account() # Object Creation
#ac.getaccdetails()
#print("Account Number=",ac.acno)
#print("Account Holder Name=",ac.cname)
#print("Account Balance=",ac.bal)
#print("Account PIN=",ac.pin)
#print("Account Holder Branch Name=",ac.bname)

========================================================

#OtherProgEx3.py
from Acc3 import Account
ac=Account() # Object Creation
ac. init ()
print("Account Number=",ac.acno)
print("Account Holder Name=",ac.cname)
print("Account Balance=",ac.bal)
print("Account PIN=",ac.pin)
print("Account Holder Branch Name=",ac.

========================================================

=========================================
Inheritance
=========================================
Index:

=>Purpose of Inheritance
=>Def. of Inheritance
=>Memeory Management in Inheritance
=>Types of Inheritances
=>Syntax for Inheritance in Python
=>Programming Examples

322
=================================================
Inheritance
=================================================
=>Inhenritance is one of distinct features of OOPs
=>The purpose of Inheritance is that " To build Re-usable Applications
in Python Object Oriented Programming".

=>Definition of Inheritance:

=>The Process obtaining Data members , Methods and Constructors


(Features ) of one class
into another class is called Inheritance.
=>The class which is giving Data members , Methods and Constructors
(Features ) is called
Super or Base or Parent Class.
=>The Class which is taking Data members , Methods and Constructors
(Features ) is called
Sub or Derived or Child Class.
=>The Inheritance concept always follows Logical (Virtual)Memory
Management. This Memory Management says that " Neither we write Source
Code nor Takes Physical Memory Space ".

Advatnages of Inheritance:

=>When we develop any inheritance based application, we get the


following advantages.
1. Application Development Time is Less
2. Application Memory Space is Less
3. Application Execution time is Fast / Less
4. Application Performance is enhanced (Improved )
5. Redundency (Duplication ) of the code is minimized.

====================================
Types of Inheritances
====================================
=>Types of Inheritance is a pattern or model which makes us to
understand, how the features are inherited from base class into
derived classes.
=>In Python Programming, we have 5 types of Inheritances. They are
1) Single Inheritance
2) Multi Level Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance
5) Hybrid Inheritance

323
==============================================================

#Program for demonstrating the concept of Inheritance


#InhProg1.py
class C1:
def getC1Values(self):
self.a=10
self.b=20

class C2(C1):
def getC2values(self):
self.c=1
self.d=2
def operation(self):
self.result=self.a+self.b+self.c+self.d

324
#main program
o2=C2()
print(o2. dict ) # {}
o2.getC1Values()
print(o2. dict ) # {a:10,b:20}
o2.getC2values()
print(o2. dict ) # {a:10,b:20, c:1, d:2}
o2.operation()
print(o2. dict ) # {a:10,b:20,c:1, d:2,result:33}

=============================================================

#Program for demonstrating the concept of Inheritance


#InhProg2.py
class C1:
def getC1Values(self):
self.a=10
self.b=20

class C2(C1):
def getC2values(self):
self.c=1
self.d=2
self.getC1Values() # Calling Base Class Method
self.operation() # Calling Current Class method
def operation(self):
self.result=self.a+self.b+self.c+self.d

print("sum({},{},{},{})={}".format(self.a,self.b,self.c,self.d,s
elf.result))

#main program
o2=C2()
print(o2. dict ) # {}
o2.getC2values()

=============================================================

#InhProg3.py
class Univ:
def getunivdet(self):
self.uname=input("Enter Univeristy Name:")
self.uloc=input("Enter Univeristy Location:")
def dispunivdet(self):
print("-"*50)
print("Unversity Details:")
print("-"*50)
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-"*50)

class College(Univ):
def getcolldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
def dispcolldet(self):

325
print("-"*50)
print("College Details:")
print("-"*50)
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-"*50)

class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
def dispstuddet(self):
print("-"*50)
print("Student Details:")
print("-"*50)
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-"*50)

#main program
so=Student()
so.getstuddet()
so.getcolldet()
so.getunivdet()
so.dispunivdet()
so.dispcolldet()
so.dispstuddet()

=============================================================

#University.py---File Name and acts as module name


class Univ:
def getunivdet(self):
self.uname=input("Enter Univeristy Name:")
self.uloc=input("Enter Univeristy Location:")
def dispunivdet(self):
print("-"*50)
print("Unversity Details:")
print("-"*50)
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-"*50)

=============================================================

#College.py----File Name and acts as module name


from University import Univ
class College(Univ):
def getcolldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
self.getunivdet()
def dispcolldet(self):

326
self.dispunivdet()
print("-"*50)
print("College Details:")
print("-"*50)
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-"*50)

=============================================================

#Student.py---File Name and acts as moudle name


from College import College
import cx_Oracle
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
self.getcolldet()
def dispstuddet(self):
self.dispcolldet()
print("-"*50)
print("Student Details:")
print("-"*50)
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Course:{}".format(self.crs))
print("-"*50)
def storestuddet(self):
try:

con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
cur.execute("insert into student
values(%d,'%s','%s','%s','%s','%s','%s')"
%(self.sno,self.sname,self.crs,self.cname,self.cloc,self.uname,self.ulo
c))
con.commit()
print("\nStudent Record Inserted in Student
Table")
except cx_Oracle.DatabaseError as db:
print("Problem in Database",db)

#UnivCollStud.py---main program
from Student import Student
so=Student()
so.getstuddet()
so.dispstuddet()
so.storestuddet()

=============================================================

327
==============================================
Polymorphism in Python
==============================================
=>Polymorphism is one of the distinct features of OOPs
=>The purpose of Polymorphism is that "Efficient Utilization Memory
Spacee (OR) Less Memory space is achieved".

=>Def. of Polymorphism:

=>The Process of Representing "One Form in multiple Forms " is called


Polymorphism.
=>The Polymorphism Principle is implemented(Bring into action) by Using
"Method Overriding" feature of all OO Programming Languages.
=>In The definition of polymorphism, "One Form" represents "Original
Method" and multiple forms represents Overridden Methods.
=>A "Form" is nothing but existence of a Method. if the method is
existing in base class then it is called "Original Method(one form)"
and if the method existing derived class then it is called "Overridden
Method(multiple Forms)".
X

===========================================
Method Overriding in Python
===========================================
=>Method Overriding=Method Heading is same + Method Body is Different
(OR)
=>The process of re-defining the original method of base class into
various derived classes for performing different operations is called
Method Overriding.
=>To use Method Overriding in python program we must apply Inheritance
Principle.
=>Method Overriding used for implementing Polymorphism Principle.
(Polymorphism Principle<----Uses Method Overriding<---Uses Inheritance
Principle)
Examples:

#methodoverex1.py
class Circle:
def draw(self): # original Method
print("Drawing Circle")

class Rect(Circle):
def draw(self): # overridden Method
print("Drawing Rect:")
super().draw()

class Square(Rect):
def draw(self): # overridden Method
print("Drawing Square:")
super().draw()

#main program
so=Square()
so.draw()

328
#teacher.py
class Teacher:
def readsub(self):
print("Teacher advises to read 2 hours")

class LazyStudent(Teacher):
def readsub(self):
print("LazyStudent never read at all")
class PerfectStudent(Teacher):
def readsub(self):
print(" Perfect Student 2hrs reading and practicing")

ls=LazyStudent()
ls.readsub()
ps=PerfectStudent()
ps.readsub()

#InhEx1.py
class Circle:
def draw1(self): # Original Method
print("Drawing Circle")

class Rect(Circle):
def draw2(self): # Overriden Method
print("Drawing Rect")

class Square(Rect):
def draw3(self): # Overriden Method
print("Drawing Square")

#main program
print("w.r.t Sqaure")
s=Square()
s.draw3()
s.draw2()
s.draw1()

#PolyEx1.py
class Circle:
def draw(self): # Original Method
print("Drawing Circle")

class Rect(Circle):
def draw(self): # Overriden Method
print("Drawing Rect")
super().draw() # Will call base class draw() from derived
class draw()

class Square(Rect):
def draw(self): # Overriden Method
print("Drawing Square")

329
super().draw() # Will call base class draw() from
derived class draw()

#main program
print("w.r.t Sqaure")
s=Square()
s.draw()

#PolyEx3.py
class Circle:
def area(self): # Original Method
self.r=float(input("\nEnter Radious:"))
self.ac=3.14*self.r**2
print("Area of Circle={}".format(self.ac))
class Rect(Circle):
def area(self): # Overriden Method
self.l=float(input("Enter Length:"))
self.b=float(input("Enter Breadth:"))
self.ar=self.l*self.b
print("Area of Rect={}".format(self.ar))
print("-"*50)
super().area() # Will call base class area() from
derived class area()
class Square(Rect):
def area(self): # Overriden Method
self.s=float(input("\nEnter Side:"))
self.sa=self.s**2
print("Area of Square={}".format(self.sa))
print("-"*50)
super().area() # Will call base class area() from
derived class area()

#main program print("\


nw.r.t Square")
s=Square()
s.area()

#PolyEx4.py
class Test:
def init (self): # Original Constructor
print("Test--DC")

class Sample(Test):
def init (self): # Overidden Constructor
print("Sample--DC")
super(). init () # calling Base Class Constructor from
Derived class Constructor

class Hyd(Sample):
def init (self): # Overidden Constructor
print("Hyd--DC")
super(). init ()

#main program
h=Hyd()

330
#teacher.py
class Teacher:
def readsub(self):
print("Teacher advises to read 2 hours")

class LazyStudent(Teacher):
def readsub(self):
print("LazyStudent never read at all")
class PerfectStudent(Teacher):
def readsub(self):
print(" Perfect Student 2hrs reading and practicing")
#main program
ls=LazyStudent()
ls.readsub()
ps=PerfectStudent()
ps.readsub()

==================================================================
Number of approaches to call original methods / constructors from
Overridden methods / Constructors
==================================================================
=>We have two approches to call original method / constructors of base
class from overridden method / constructors of derived class. They are

1) By using super()
2) By using Class Name

-
1) By using super():

=>super() is one of the pre-defined function, which is used for calling


super class original method / constructor from overridden method /
constructors of derived class.

Syntax1:- super().methodname(list of values if any)

Syntax2:- super(). init (list of values if any)

=>with super() we are able to call only immediate base class method
but unable to call Specified method of base Class . To do this we must
use class name approach.

2) By using Class Name:

=>By using ClassName approach, we can call any base class method /
constructor name from the context of derived class method / constructor
names.

Syntax1:- ClassName.methodname(self, list of values if any)


Syntax2:- ClassName. init (self, list of values if any)
X

#NullBodyMethodEx.py
class Teacher:

331
def teach(self):pass # Null Body Method

class KVR(Teacher):
def teach(self): # Overriding Null Body Method
print("KVR Teaches Both Python and Java")
class Raj(Teacher):
def teach(self): # Overriding Null Body Method
print("Raj teaches Tesing Tools")

#main program
k=KVR()
k.teach()
r=Raj()
r.teach()

#PolyEx4.py
class Test:
def init (self): # Original Constructor
print("Test--DC")

class Sample(Test):
def init (self): # Overidden Constructor
print("Sample--DC")
super(). init () # calling Base Class Constructor from
Derived class Constructor

class Hyd(Sample):
def init (self): # Overidden Constructor
print("Hyd--DC")
super(). init ()

#main program
h=Hyd()

#PolyEx5.py
class Sample:
def dispvalues(self,a,b): # Original Method
self.a=a
self.b=b
print("Sample---dispvalues()")
print("Value of a--Sample={}".format(self.a))
print("Value of a--Sample={}".format(self.b))

class Test(Sample):
def dispvalues(self,a,b,c,d): # Overridden Method
super().dispvalues(a,b)
self.c=c
self.d=d
print("Test---dispvalues()")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))

#main program
t=Test()
print(t. dict ) # { }
t.dispvalues(10,20,30,40)

332
print(t. dict ) # { }

#PolyEx6.py
class Sample:
def init (self,a,b): # Original
Constructor self.a=a
self.b=b
print("Sample---Parametrized Constructor:")
print("Value of a--Sample={}".format(self.a))
print("Value of a--Sample={}".format(self.b))

class Test(Sample):
def init (self,a,b,c,d): # Overridden Constructor
super(). init (c,d)
self.c=a
self.d=b
print("Test---Parametrized Constructor:")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))

#main program
t=Test(100,200,300,400)

#PolyEx7.py
class Sample:
def init (self,a,b): # Original
Constructor self.a=a
self.b=b
print("Sample---Parametrized Constructor:")
print("Value of a--Sample={}".format(self.a))
print("Value of a--Sample={}".format(self.b))

class Test(Sample):
def init (self,a,b): # Overridden Constructor
super(). init ( float(input("\nEnter First Value for
Object2:")),float(input("Enter Second Value for Object2:")) )
self.c=a
self.d=b
print("Test---Parametrized Constructor:")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))

#main program
t1=Test(float(input("\nEnter First Value for Object1:")) ,
float(input("Enter Second Value for Object1:")) )

#PolyEx8.py
class Sample:
def dispvalues(self,a,b): # Original Method
self.a=a
self.b=b
print("\nSample---dispvalues()")
print("Value of a--Sample={}".format(self.a))
print("Value of a--Sample={}".format(self.b))
class Test:

333
def dispvalues(self,a,b): # Original Method
self.c=a
self.d=b
print("\nTest---dispvalues()")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))
class Hyd(Sample,Test):
def dispvalues(self,a,b): # Overridden Method
self.c=a
self.d=b
print("\nHyd---dispvalues()")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))
super().dispvalues(100,200) # Using super(), we are
calling dispvalues() of Sample class
Test.dispvalues(self,1000,2000);# By using Test Class
Name, we are calling dispvalues() of Test Class from Hyd class

#main program
h=Hyd()
h.dispvalues(10,20)

#PolyEx9.py
class Sample:
def init (self,a=1,b=2): # Original
Constructor self.a=a
self.b=b
print("\nSample---Default / Parametrized Constructor:")
print("Value of a--Sample={}".format(self.a))
print("Value of a--Sample={}".format(self.b))

class Test:
def init (self,a=10,b=20): # Original Constructor
self.c=a
self.d=b
print("\nTest---Default / Parametrized Constructor:")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))
class Hyd(Sample,Test):
def init (self,a="KVR",b="PYTHON"): # Overridden
Constructor
self.c=a
self.d=b
print("\nHyd---Default / Parametrized Constructor:")
print("Value of c--Test={}".format(self.c))
print("Value of d--Test={}".format(self.d))
super(). init ()
Test. init (self, "KVR",b="Django")
Test. init (self)

#main program
t1=Hyd()

==========================================
Regular Expressions in Python

334
==========================================
=>The Purpose of Regular Expressions in Python is that "To Validate the
data and makes the
application Robust:"
=>Regular Expressions is one of the Programming Language Independent
Topic and different programming language Vendors implemented the
rules of Regular Expressions in the form
of Libraries(Modules).
=>In Python Programming, To develop any program by using Regular
Expressions , we must
use a pre-defined module called "re".

=>Definition of Regular Expression:


=>A Regular Expression is one of the Search Pattern, which is the
combination of Alphabets ,
Digits and Special Symbols which is used to search or find or match
in given data and obtains desired Result.

=>Applications of Regular Expression:

1. Regular Expression used in develoment of IDEs for


Search Patterns
2. Regular Expression used in Pattern Matching
3. Regular Expression used in Compilers and Interpreters
development.
4. Regular Expression used in OS development
5. Regular Expression used in Universal Protocol
Development.
6. Regular Expression used in Electronics Circuits
Designing...etc

=================================================
Module name for Regular Expressions (RegEx)
=================================================
=>To deal with Regular Expressions programs, we must use a pre-defined
module called "re".
=>"re" module the following functions.
1) finditer()
2) findall()
3) search()
4) start()
5) end()
6) group()

==========================================
Pre-defined Functions in re module

335
==========================================
=>The 're' module contains the follwing essential Functions.

1) finditer():

Syntax:- varname=re.finditer("search-pattern","Given data")


=>here varname is an object of type <class,'Callable_Itetaror'>

=>This function is used for searching the "search pattern" in given


data iteratively and it returns table of entries which contains start
index , end index and matched value based on the search pattern.

2) group():

=>This function is used obtaining matched value by the findIter()


=>This function present in match class of re module
Syntax:- varname=matchtabobj.group()

3) start():

=>This function is used obtaining starting index of matched value


=>This function present in match class of re module
Syntax: varname=matchobj.start()

4) end():

=>This function is used obtaining end index+1 of matched value


=>This function present in match class of re module
Syntax: varname=matchobj.end()

5) search():

Syntax:- varname=re.search("search-pattern","Given data")


=>here varname is an object of <class,'re.match'> or <class,'NoneType'>

=>This function is used for searching the search pattern in given data
for first occuence / match only but not for other occurences /
matches.
=>if the search pattern found in given data then it returns an object
of match class which contains matched value and start and end index
values and it indicates search is successful.
=>if the search pattern not found in given data then it returns None
which is type <class, "NoneType"> and it indicates search is un-
successful

6) findall():

336
Syntax:- varname=re.findall("search-pattern","Given data")
=>here varname is an object of <class,'list'>

=>This function is used for searching the search pattern in entire


given data and find all occurences / matches and it returns all the
matched values in the form an object <class,'list'> but not returning
Start and End Index Values.

#RegExpr1.py
import re
gd="Python is an oop lang.Python is also Fun Prog lang."
sp="an"
matches=re.findall(sp,gd)
print(matches)
print(" '{}' Found : {} Time(s) :".format(sp,len(match

#RegExpr2.py
import re
gd="Python is an oop lang.Python is also Fun Prog lang."
sp="an"
mat=re.finditer(sp,gd)
print(type(mat)) # <class 'callable_iterator'>
print(mat) # <callable_iterator object at 0x00000230EA1411B0>
print("="*50)
for m in mat:
print(m,type(m))
print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr2.py
<class 'callable_iterator'>
<callable_iterator object at 0x0000026B4C7710C0>
==================================================
<re.Match object; span=(10, 12), match='an'> <class 're.Match'>
<re.Match object; span=(18, 20), match='an'> <class 're.Match'>
<re.Match object; span=(47, 49), match='an'> <class 're.Match'>
==================================================
"""

#RegExpr3.py
import re
gd="Python is an oop lang.Python is also Fun Prog lang."
sp="Python"
mat=re.finditer(sp,gd)
noc=0
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group()))
noc=noc+1
print("="*50)

337
print("Number of Occurences of '{}'={}".format(sp,noc))

#RegExpr4.py
import re
gd="Python is an oop lang.Python is also Fun Prog lang."
sp="Java"
result=re.search(sp,gd)
if(result!=None):
print("Search is sucessful:")
else:
print("Search is not sucessful:")

#Program for searching either 'a' or 'b' or 'c' only


#RegExpr5.py
import re
mat=re.finditer("[abc]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr5.py
==================================================
Start Index:1 End Index:2 Value:a
Start Index:5 End Index:6 Value:c
Start Index:12 End Index:13 Value:c
Start Index:20 End Index:21 Value:b
==================================================
"""

#Program for searching all except either 'a' or 'b' or 'c'


#RegExpr6.py
import re
mat=re.finditer("[^abc]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)
"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr6.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:2 End Index:3 Value:K
Start Index:3 End Index:4 Value:6
Start Index:4 End Index:5 Value:#
Start Index:6 End Index:7 Value:&
Start Index:7 End Index:8 Value:q
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:T
Start Index:10 End Index:11 Value:L
Start Index:11 End Index:12 Value:%

338
Start Index:13 End Index:14 Value:@
Start Index:14 End Index:15 Value:D
Start Index:15 End Index:16 Value:u
Start Index:16 End Index:17 Value:9
Start Index:17 End Index:18 Value:^
Start Index:18 End Index:19 Value:!
Start Index:19 End Index:20 Value:B
Start Index:21 End Index:22 Value:J
================================================== """

#Program for searching all lower case alphabets only


#RegExpr7.py
import re
mat=re.finditer("[a-z]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""\
E:\KVR-PYTHON-7AM\REGEX>py RegExpr7.py
==================================================
Start Index:1 End Index:2 Value:a
Start Index:5 End Index:6 Value:c
Start Index:7 End Index:8 Value:q
Start Index:8 End Index:9 Value:p
Start Index:12 End Index:13 Value:c
Start Index:15 End Index:16 Value:u
Start Index:20 End Index:21 Value:b
==================================================
"""
#Program for searching all except lower case alphabets
#RegExpr8.py
import re
mat=re.finditer("[^a-z]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr8.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:2 End Index:3 Value:K
Start Index:3 End Index:4 Value:6
Start Index:4 End Index:5 Value:#
Start Index:6 End Index:7 Value:&
Start Index:9 End Index:10 Value:T
Start Index:10 End Index:11 Value:L
Start Index:11 End Index:12 Value:%
Start Index:13 End Index:14 Value:@
Start Index:14 End Index:15 Value:D
Start Index:16 End Index:17 Value:9
Start Index:17 End Index:18 Value:^

339
Start Index:18 End Index:19 Value:!
Start Index:19 End Index:20 Value:B
Start Index:21 End Index:22 Value:J
=================================================="""

#Program for searching all Upper case alphabets only


#RegExpr9.py
import re
mat=re.finditer("[A-Z]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr9.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:2 End Index:3 Value:K
Start Index:9 End Index:10 Value:T
Start Index:10 End Index:11 Value:L
Start Index:14 End Index:15 Value:D
Start Index:19 End Index:20 Value:B
Start Index:21 End Index:22 Value:J
==================================================
"""
#Program for searching all except Upper case alphabets only
#RegExpr10.py
import re
mat=re.finditer("[^A-Z]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr10.py
==================================================
Start Index:1 End Index:2 Value:a
Start Index:3 End Index:4 Value:6
Start Index:4 End Index:5 Value:#
Start Index:5 End Index:6 Value:c
Start Index:6 End Index:7 Value:&
Start Index:7 End Index:8 Value:q
Start Index:8 End Index:9 Value:p
Start Index:11 End Index:12 Value:%
Start Index:12 End Index:13 Value:c
Start Index:13 End Index:14 Value:@
Start Index:15 End Index:16 Value:u
Start Index:16 End Index:17 Value:9
Start Index:17 End Index:18 Value:^
Start Index:18 End Index:19 Value:!
Start Index:20 End Index:21 Value:b
==================================================
"""

340
#Program for searching all Digits only
#RegExpr11.py
import re
mat=re.finditer("[0-9]", "0AaK6#c&qp5TL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr11.py
==================================================
Start Index:0 End Index:1 Value:0
Start Index:4 End Index:5 Value:6
Start Index:10 End Index:11 Value:5
Start Index:18 End Index:19 Value:9
==================================================
"""

#Program for searching all except Digits


#RegExpr12.py
import re
mat=re.finditer("[^0-9]", "0AaK6#c&qp5TL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr12.py
==================================================
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:a
Start Index:3 End Index:4 Value:K
Start Index:5 End Index:6 Value:#
Start Index:6 End Index:7 Value:c
Start Index:7 End Index:8 Value:&
Start Index:8 End Index:9 Value:q
Start Index:9 End Index:10 Value:p
Start Index:11 End Index:12 Value:T
Start Index:12 End Index:13 Value:L
Start Index:13 End Index:14 Value:%
Start Index:14 End Index:15 Value:c
Start Index:15 End Index:16 Value:@
Start Index:16 End Index:17 Value:D
Start Index:17 End Index:18 Value:u
Start Index:19 End Index:20 Value:^
Start Index:20 End Index:21 Value:!
Start Index:21 End Index:22 Value:B
Start Index:22 End Index:23 Value:b
Start Index:23 End Index:24 Value:J
==================================================
"""
#Program for searching all Alphabets (lower case and upper case
alphabets)
#RegExpr13.py

341
import re
mat=re.finditer("[A-Za-z]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr13.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:1 End Index:2 Value:a
Start Index:2 End Index:3 Value:K
Start Index:5 End Index:6 Value:c
Start Index:7 End Index:8 Value:q
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:T
Start Index:10 End Index:11 Value:L
Start Index:12 End Index:13 Value:c
Start Index:14 End Index:15 Value:D
Start Index:15 End Index:16 Value:u
Start Index:19 End Index:20 Value:B
Start Index:20 End Index:21 Value:b
Start Index:21 End Index:22 Value:J
==================================================
"""

#Program for searching all except Alphabets (lower case and upper case
alphabets)
#RegExpr14.py
import re
mat=re.finditer("[^A-Za-z]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr14.py
==================================================
Start Index:3 End Index:4 Value:6
Start Index:4 End Index:5 Value:#
Start Index:6 End Index:7 Value:&
Start Index:11 End Index:12 Value:%
Start Index:13 End Index:14 Value:@
Start Index:16 End Index:17 Value:9
Start Index:17 End Index:18 Value:^
Start Index:18 End Index:19 Value:!
==================================================
"""

#Program for searching Upper Alphabets and digits


#RegExpr15.py

import re

342
mat=re.finditer("[A-Z0-9]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
==================================================

E:\KVR-PYTHON-7AM\REGEX>py RegExpr15.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:2 End Index:3 Value:K
Start Index:3 End Index:4 Value:6
Start Index:9 End Index:10 Value:T
Start Index:10 End Index:11 Value:L
Start Index:14 End Index:15 Value:D
Start Index:16 End Index:17 Value:9
Start Index:19 End Index:20 Value:B
Start Index:21 End Index:22 Value:J
==================================================
"""

#Program for searching for all except Upper Alphabets and digits
#RegExpr16.py
import re
mat=re.finditer("[^A-Z0-9]", "AaK6#c&qpTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
==================================================

E:\KVR-PYTHON-7AM\REGEX>py RegExpr16.py
==================================================
Start Index:1 End Index:2 Value:a
Start Index:4 End Index:5 Value:#
Start Index:5 End Index:6 Value:c
Start Index:6 End Index:7 Value:&
Start Index:7 End Index:8 Value:q
Start Index:8 End Index:9 Value:p
Start Index:11 End Index:12 Value:%
Start Index:12 End Index:13 Value:c
Start Index:13 End Index:14 Value:@
Start Index:15 End Index:16 Value:u
Start Index:17 End Index:18 Value:^
Start Index:18 End Index:19 Value:!
Start Index:20 End Index:21 Value:b
==================================================
"""

#Program for searching for all Alphabets and digits only


#RegExpr17.py

import re

343
mat=re.finditer("[A-Za-z0-9]", "AaK6#9&4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)
"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr17.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:1 End Index:2 Value:a
Start Index:2 End Index:3 Value:K
Start Index:3 End Index:4 Value:6
Start Index:5 End Index:6 Value:9
Start Index:7 End Index:8 Value:4
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:T
Start Index:10 End Index:11 Value:L
Start Index:12 End Index:13 Value:c
Start Index:14 End Index:15 Value:D
Start Index:15 End Index:16 Value:u
Start Index:16 End Index:17 Value:9
Start Index:19 End Index:20 Value:B
Start Index:20 End Index:21 Value:b
Start Index:21 End Index:22 Value:J
==================================================
"""

#Program for searching for all special symbols


#RegExpr18.py
import re
mat=re.finditer("[^A-Za-z0-9]", "A[]?aK6#9&4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"””
==================================================
Start Index:1 End Index:2 Value:[
Start Index:2 End Index:3 Value:]
Start Index:3 End Index:4 Value:?
Start Index:7 End Index:8 Value:#
Start Index:9 End Index:10 Value:&
Start Index:14 End Index:15 Value:%
Start Index:16 End Index:17 Value:@
Start Index:20 End Index:21 Value:^
Start Index:21 End Index:22 Value:!
==================================================
"""

#Program for searching for all Vowels


#RegExpr20.py
import re
mat=re.finditer("[aeiouAEIOU]", "All Silver Tea Cups")
print("="*50)
for m in mat:

344
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

==============================================================
Pre-Defined Character Classes in Regular Expressions
==============================================================
=>Pre-Defined Character Classes defined by Python Language Developers
and they are used in defining (OR) preparing the Search Pattern which
is used for searching in given data and obtains desired result.
=>Syntax:- "\Search Pattern"

1) \w------------>Searches for any Word Character (Alphabet or digit)


(OR) [A-Za-z0-9]
2) \W----------->Searches for special Symbols (except Word Character
(Alphabet or digit) (OR)
3) \d---------->Searches for any digit only (OR) [0-9]
4) \D---------->Searches for all except digits (OR) [^0-9]
5) \s----------->Searching for space character only
6) \S---------->Searching for all except space character

#Program for searching any word Character


#RegExpr21.py
import re
mat=re.finditer("\w", "A[]?aK6#9&4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr21.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:4 End Index:5 Value:a
Start Index:5 End Index:6 Value:K
Start Index:6 End Index:7 Value:6
Start Index:8 End Index:9 Value:9
Start Index:10 End Index:11 Value:4
Start Index:11 End Index:12 Value:p
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:L
Start Index:15 End Index:16 Value:c
Start Index:17 End Index:18 Value:D
Start Index:18 End Index:19 Value:u
Start Index:19 End Index:20 Value:9
Start Index:22 End Index:23 Value:B
Start Index:23 End Index:24 Value:b
Start Index:24 End Index:25 Value:J
==================================================
"""

#Program for searching any special symbols


#RegExpr22.py
import re
mat=re.finditer("\W", "A[]?aK6#9&4pTL%c@Du9^!BbJ")

345
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
==================================================

E:\KVR-PYTHON-7AM\REGEX>py RegExpr22.py
==================================================
Start Index:1 End Index:2 Value:[
Start Index:2 End Index:3 Value:]
Start Index:3 End Index:4 Value:?
Start Index:7 End Index:8 Value:#
Start Index:9 End Index:10 Value:&
Start Index:14 End Index:15 Value:%
Start Index:16 End Index:17 Value:@
Start Index:20 End Index:21 Value:^
Start Index:21 End Index:22 Value:!
==================================================
"""

#Program for searching any digit


#RegExpr23.py
import re
mat=re.finditer("\d", "A[]?aK6#9&4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr23.py
==================================================
Start Index:6 End Index:7 Value:6
Start Index:8 End Index:9 Value:9
Start Index:10 End Index:11 Value:4
Start Index:19 End Index:20 Value:9
==================================================
"""

#Program for searching all except digits


#RegExpr24.py
import re
mat=re.finditer("\D", "A[]?aK6#9&4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr24.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:1 End Index:2 Value:[

346
Start Index:2 End Index:3 Value:]
Start Index:3 End Index:4 Value:?
Start Index:4 End Index:5 Value:a
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:#
Start Index:9 End Index:10 Value:&
Start Index:11 End Index:12 Value:p
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:L
Start Index:14 End Index:15 Value:%
Start Index:15 End Index:16 Value:c
Start Index:16 End Index:17 Value:@
Start Index:17 End Index:18 Value:D
Start Index:18 End Index:19 Value:u
Start Index:20 End Index:21 Value:^
Start Index:21 End Index:22 Value:!
Start Index:22 End Index:23 Value:B
Start Index:23 End Index:24 Value:b
Start Index:24 End Index:25 Value:J
==================================================

"""

#Program for searching for space character


#RegExpr25.py
import re
mat=re.finditer("\s", "A[]?a K6#9 &4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr25.py
==================================================
Start Index:5 End Index:6 Value:
Start Index:10 End Index:11 Value:
==================================================
"""

#Program for searching for all except space character


#RegExpr26.py
import re
mat=re.finditer("\S", "A[]?a K6#9 &4pTL%c@Du9^!BbJ")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr26.py
==================================================
Start Index:0 End Index:1 Value:A
Start Index:1 End Index:2 Value:[

347
Start Index:2 End Index:3 Value:]
Start Index:3 End Index:4 Value:?
Start Index:4 End Index:5 Value:a
Start Index:6 End Index:7 Value:K
Start Index:7 End Index:8 Value:6
Start Index:8 End Index:9 Value:#
Start Index:9 End Index:10 Value:9
Start Index:11 End Index:12 Value:&
Start Index:12 End Index:13 Value:4
Start Index:13 End Index:14 Value:p
Start Index:14 End Index:15 Value:T
Start Index:15 End Index:16 Value:L
Start Index:16 End Index:17 Value:%
Start Index:17 End Index:18 Value:c
Start Index:18 End Index:19 Value:@
Start Index:19 End Index:20 Value:D
Start Index:20 End Index:21 Value:u
Start Index:21 End Index:22 Value:9
Start Index:22 End Index:23 Value:^
Start Index:23 End Index:24 Value:!
Start Index:24 End Index:25 Value:B
Start Index:25 End Index:26 Value:b
Start Index:26 End Index:27 Value:J
=================================================="""

#Program for searching for two digit number


#RegExpr27.py
import re
mat=re.finditer("[0-9]+", "A23a#45KT^L6%c@Du99^!Bb234J")
print("="*50)
for m in mat:
print("Start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group())) print("="*50)

==============================================================
Programmer-Defined Character Classes in Regular Expressions
==============================================================
=>Programmer-Defined Character Classes defined by Programmers and they
are used in defining (OR) preparing the Search Pattern which is used
for searching in given data and obtains desired result.
=>Syntax:- "[ Search Pattern ]"

1) [abc]------------>Searches for either 'a' or 'b' or 'c' only


2) [^abc]---------->Searches for all except either 'a' or 'b' or 'c'
3) [a-z]------------->Searches for all Lower Case Alphabets only
4) [^a-z]----------->Seaches for all except Lower Case Alphabets
5) [A-Z]------------>Searches for all Upper Case Alphabets only
6) [^A-Z]----------->Seaches for all except Upper Case Alphabets
7) [0-9]------------->Searches for all Digits only
8) [^0-9]------------>Searches for all except Digits
9) [A-Za-z]--------->Searches for all Alphabets (Lower and Upper case)
10)[^A-Za-z]------->Searches for all except Alphabets (Lower and Upper
case)
11) [A-Z0-9]-------->Searches for Upper Case Alphabets and Digits only

348
12) [^A-Z0-9]------>Searches for all except Upper Case Alphabets and
Digits only
13) [a-z0-9]-------->Searches for lower Case Alphabets and Digits only
14) [^a-z0-9]------>Searches for all except lower Case Alphabets and
Digits

15) [A-Za-z0-9]---->Seaches for all Alphabets and digits


16) [^A-Za-z0-9]--->Seaches for Special Symbols ( except Alphabets and
digits )

=========================================
Quantifiers in Regular Expressions
=========================================
=>Quantifiers in Regular Expressions are used for searching number of
occurences of the specified value (alphabets or digits or special
symbols) used in search pattern to search in the given data and
obtains desired result.

1) "k"------->It search for only one 'k' at a time


2) "k+"------>It search for either one 'k' more 'k' s
3) "k*"------>It search for either zero 'k' or one 'k' and more 'k'
s
4) "k?"----->>It search for either zero 'k' or one 'k'
5) ". " ---->It searches for all

Note:

==>\ddd or d{3}----->searches for 3 digits


==>\dd.\dd----searhes for 2 integer values and 2 decimal values
==>\d{2,4}----searches for min 2 digit number and max 4 digit number.
==>[A-Za-z]+ ---searches one alphabet or More alphabets.
==>\w+
==>[0-9]+ or \d+

==>\dddddddddd---------(OR)----->\d{10}----->Searches 10 digits
\d{n}------->Searches 'n'
digits
==>\d{m,n}-------->Searches minimum 'm' digits and max 'n' digit number
\d{3,5}--------->searches for min 3 digit number and max 5 digit
number
=>\d{3}.\d{2}---->searching for a floting point number with 3 Digits
Integer part and 2 digit
decimal part.

#Program for searching exatctly one char.


#RegExpr28.py
import re
mat=re.finditer("k", "kvkkvkkkvkv")

349
print("="*50)
for m in mat:
print("start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group()))
print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr28.py
==================================================
start Index:0 End Index:1 Value: k
start Index:2 End Index:3 Value: k
start Index:3 End Index:4 Value: k
start Index:5 End Index:6 Value: k
start Index:6 End Index:7 Value: k
start Index:7 End Index:8 Value: k
start Index:9 End Index:10 Value: k
=================================================="""
#Program for searching exatctly one char or more chars ( k).
#RegExpr29.py
import re
mat=re.finditer("k+", "kvkkvkkkvkv")
print("="*50)
for m in mat:
print("start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group()))
print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr29.py
==================================================
start Index:0 End Index:1 Value: k
start Index:2 End Index:4 Value: kk
start Index:5 End Index:8 Value: kkk
start Index:9 End Index:10 Value: k
==================================================
"""
#Program for searching exatctly one char or more chars ( k).
#RegExpr30.py
import re
mat=re.finditer("k*", "kvkkvkkkvkv")
print("="*50)
for m in mat:
print("start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group()))
print("="*50)

"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr30.py
==================================================
start Index:0 End Index:1 Value: k
start Index:1 End Index:1 Value:
start Index:2 End Index:4 Value: kk
start Index:4 End Index:4 Value:
start Index:5 End Index:8 Value: kkk
start Index:8 End Index:8 Value:
start Index:9 End Index:10 Value: k
start Index:10 End Index:10 Value:
start Index:11 End Index:11 Value:

350
==================================================
"""
#Program for searching exatctly zero char or one char ( k).
#RegExpr31.py
import re
mat=re.finditer("k?", "kvkkvkkkvkv")
print("="*50)
for m in mat:
print("start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group()))
print("="*50)

"""
==================================================
start Index:0 End Index:1 Value: k
start Index:1 End Index:1 Value:
start Index:2 End Index:3 Value: k
start Index:3 End Index:4 Value: k
start Index:4 End Index:4 Value:
start Index:5 End Index:6 Value: k
start Index:6 End Index:7 Value: k
start Index:7 End Index:8 Value: k
start Index:8 End Index:8 Value:
start Index:9 End Index:10 Value: k
start Index:10 End Index:10 Value:
start Index:11 End Index:11 Value:
==================================================
"""
#Program for searching for all
#RegExpr32.py
import re
mat=re.finditer(".", "kvkkvkkkvkv")
print("="*50)
for m in mat:
print("start Index:{} End Index:{} Value:
{}".format(m.start(),m.end(),m.group()))
print("="*50)

"""
==================================================
start Index:0 End Index:1 Value: k
start Index:1 End Index:2 Value: v
start Index:2 End Index:3 Value: k
start Index:3 End Index:4 Value: k
start Index:4 End Index:5 Value: v
start Index:5 End Index:6 Value: k
start Index:6 End Index:7 Value: k
start Index:7 End Index:8 Value: k
start Index:8 End Index:9 Value: v
start Index:9 End Index:10 Value: k
start Index:10 End Index:11 Value: v
==================================================
"""

#Program for validating Mobile Number ( must contain 10 digits)


#mobilevalid.py
import re
while(True):

351
mno=input("Enter ur mobile number:")
if(len(mno)==10):
result=re.search ("\d{10}",mno)
if(result!=None):
print("Ur Mobile Number is valid:")
break
else:
print("Ur Mobile Number should not contains
strs/special symbols")
else:
print("Ur Mobile Number is invalid, bcoz It contains more
than 10 digits:")

#program for obtaining marks of people by using reg ex


#ExtractMarks.py
import re
gd="Rossum is an author of python and marks 88 , Ritche is an author of
c lang and marks 77, Golsing is an author of java and marks 66 and
Travis an author of numpy and marks 55 and Kinney is author of pandas
and marks 46"
marks=re.findall("\d{2}", gd)
for ma in marks:
print("\t{}".format(ma))

#program for obtaining names of people by using reg ex


#ExtractNames.py
import re
gd="Rossum is an author of python , Ritche is an author of c lang,
Golsing is an author of java and Travis an author of numpy and Kinney
is author of pandas"
mat=re.finditer("[A-Z][a-z]+", gd)
for m in mat:
print("start index:{} Value:{}".format(m.start(),m.group()))
print("==========OR================")
names=re.findall("[A-Z][a-z]+", gd)
for name in names:
print("\t{}".format(name))

#program for obtaining names of people by using reg ex


#ExtractNames1.py
import re
gd=input("Enter ur Data:\n")
mat=re.finditer("[A-Z][a-z]+", gd)
for m in mat:
print("start index:{} Value:{}".format(m.start(),m.group()))
print("==========OR================")
names=re.findall("[A-Z][a-z]+", gd)
for name in names:
print("\t{}".format(name))

#program for obtaining names and marks of people by using reg ex


#ExtractMarksNames.py
import re

352
gd="Rossum is an author of python and marks 88 , Ritche is an author of
c lang and marks 77, Golsing is an author of java and marks 66 and
Travis an author of numpy and marks 55 and Kinney is author of pandas
and marks 46 "
names=re.findall("[A-Z][a-z]+",gd)
marks=re.findall("\d{2}", gd)
print("Names of Students")
for name in names:
print("\t{}".format(name))
print("Marks of Students")
for ma in marks:
print("\t{}".format(ma))
print("-"*50)
print("\n\tNames of Students\tMarks of Students")
print("-"*50)
z=zip(names,marks)
for k,v in z:
print("\t{}\t\t\t\t{}".format(k,v))
print("-"*50)

#program for obtaining names and marks and mail id of people by using
reg ex with Files
#ExtractMarksNamesmailswithfiles.py
import re
try:
with open("stud.data","r") as fp:
filedata=fp.read()
names=re.findall("[A-Z][a-z]+",filedata) marks=re.findall("\
d{2}",filedata) mails=re.findall("\S+@\S+",filedata)
print("\nNames of Students\tMarks of Students\tMail-ID")
print("-"*50)
for n,m,mid in zip(names,marks,mails): print("\t{}\t\t\t{}\t\
t{}".format(n,m,mid))
print("-"*50)
except FileNotFoundError:
print("File does not exist")

#program for obtaining names and marks of people by using reg ex with
Files
#ExtractMarksNameswithfiles.py
import re
try:
with open("stud.data","r") as fp:
filedata=fp.read()
names=re.findall("[A-Z][a-z]+",filedata)
marks=re.findall("\d{2}",filedata)
print("-"*50)
print("\n\tNames of Students\tMarks of Students")
print("-"*50)
for n,m in zip(names,marks): print("\t{}\t\t\
t\t{}".format(n,m))
print("-"*50)
except FileNotFoundError:
print("File does not exist")
======================================================
Numpy Programming in Python (numpy module)
======================================================

353
Index

=>Purpose of Numpy Programming in Python


=>What is ndarray of Numpy
=>Differences between Traditional List of python and numpy
=>Number of approaches to create ndarray object
=>Respaping the elements of ndarray of nympy
=>Types of Arrays in Numpy
1-D
2-D
3-D
n-D
=>Basic Indexing and Slicing on ndarray object

=>Arithmetic Operations on ndarray of Numpy(Matrix Operations)


=>Statistical Operation on ndarray of Numpy
=>Mathematical Operation on ndarray of Numpy

=>Advanced mIndexing and Slicing on 1-D, 2-D ..N-D Arrays


=>Filtering the data of ndarray of numpy
=>view and copy of data of ndarray of numpy
=>Sorting and searching the elements of ndarray of numpy
=>Finding Determinant of Matrix

==========================================
Introduction to Numpy
==========================================
Introduction to Numpy:

=>Numpy stands for Numerical Python.


=>Numpy is one of the pre-defined third party module / Library and
numpy module is not a pre-defined module in Python Language.
=>To use numpy as a part of our python program, we must install numpy
module explicitly by using a tool called pip and it present in
(C:\Users\nareshit\AppData\Local\Programs\Python\Python39\Scripts)
=>Syntax for installing any module:

pip install module-name

=>Example: Install numpy module

pip install numpy

=>To use numpy as part of our program, we must import numpy module.
=>A Numpy module is a collection of Variables, Functions and Classes.
===============================================================
History of Numpy:

=>Numpy was developed by studying existing module called "Numeric


Library"(origin for development of numpy module)
=>The Numeric Library was developed by JIM HUNGUNIAN
=>The Numeric Library was not able to solve complex maths
calculations.
=>Numpy module developed by TRAVIS OLIPHANT

354
=>Numpy Module developed in the year 2005
=>Numpy Module developed in C and PYTHON languages.
==============================================================
===================================================
Python Traditional List VS Numpy Module
===================================================
Similarities of python Traditional List VS Numpy Module:

=>An object of list used to store multiple values of same type or


different type and both types (unique +duplicates) in single object.
=>In Numpy Programming, the data is organized in the object of
"ndarray", which is one of the pre-defined class in numpy module. Hence
an object of ndarray can store same type or different type and both
types (unique +duplicates) in single object.
=>The objects of ndarray and list are mutable (changes can takes place)

Differences between Python Traditional List and ndarray object of


Numpy Module:

=>An object of list contains both homogeneous and hetrogeneous values


where as an object of ndarray of numpy can store only similar type of
values(even we store different values, internally they are treated as
similar type by treating all values of type "object" ).
=>On the object of list, we can't perform Vector Operations. where as
on the object of ndarray, we can perform Vector based operations.
=>In large sampling of data, List based applications takes more memory
space where as ndarray object takes less memory space.
=>List based applications are not effiecient bcoz list object values
takes more time to extract or retrive ( they are available at different
Address) where as numpy based applications are efficient bcoz of
ndarray object values takes less to time to extract or retrive( they
are available at same Address).
=>List object can't perform complex mathematical operations where as
an object of ndarray can perform complex mathematical operations.
==========================X==================================

=================================================
Number of approaches to create an object of
ndarray
=================================================
=>We know that ndarray is apre-defined class present in numpy module.
=>The purpose of ndarray class object is that to organize the elements
in the form array and allows us to various mathematical operations.
=>To create an object ndarray, we have 7 Functions are used , which are
present in numpy module. They are
1. array()
2. arange()
3. zeros()
4. ones()
5. full()
6. eye()
7. identity()

1) array():

355
=>This Function is used for converting Traditional Python Objects into
ndrray object.
=>Syntax:- varname=numpy.array( Object,dtype )
Here var name is an object of <class,ndarray>
=>here array() is pre-defined function of numpy module used for
converting Traditional Python Objects into ndrray object.
=>object represents any Traditional Python Objects
=>dtype represents any numpy data type such as
int8,int16,int32,float16, float 32, float64,....etc

Examples:

>>> import numpy as np


>>> l1=[10,20,30,40,50,60]
>>> print(l1,type(l1))-----------------[10, 20, 30, 40, 50, 60] <class
'list'>
>>> a=np.array(l1)
>>> print(a,type(a))----------------[10 20 30 40 50 60] <class
'numpy.ndarray'>
>>> t=(10,20,30,40,50,60,70)
>>> print(t,type(t))--------------(10, 20, 30, 40, 50, 60, 70) <class
'tuple'>
>>> a=np.array(t)
>>> print(a,type(a))--------------[10 20 30 40 50 60 70] <class
'numpy.ndarray'>
>>> d1={10:1.2,20:4.5,30:6.7}
>>> a=np.array(d1)
>>> a----array({10: 1.2, 20: 4.5, 30: 6.7}, dtype=object)

>>> t=(10,20,30,40,50,60)
>>> a=np.array(t)
>>> a--------------array([10, 20, 30, 40, 50, 60])
>>> a.ndim 1
>>> a.dtype----------dtype('int32')
>>> a.shape-------------(6,)
>>> b=a.reshape(3,2)
>>> c=a.reshape(2,3)
>>> b
array([[10, 20],
[30, 40],
[50, 60]])
>>> c
array([[10, 20, 30],
[40, 50, 60]])
>>> print(b,type(b))
[[10 20]
[30 40]
[50 60]] <class 'numpy.ndarray'>
>>> print(c,type(c))
[[10 20 30]
[40 50 60]] <class 'numpy.ndarray'>
>>> b.ndim 2
>>> c.ndim 2
>>> b.shape---------------(3, 2)
>>> c.shape-------------(2, 3)

356
>>> d=a.reshape(3,3)-------ValueError: cannot reshape array of size 6
into shape (3,3)

>>> t1=((10,20),(30,40))
>>> print(t1,type(t1))--------------((10, 20), (30, 40)) <class
'tuple'>
>>> a=np.array(t1)
>>> a
array([[10, 20],
[30, 40]])
>>> a.ndim----------2
>>> a.shape----------(2, 2)

>>> t1=( ((10,20,15),(30,40,25)),( (50,60,18),(70,80,35) ))


>>> print(t1,type(t1))
(((10, 20, 15), (30, 40, 25)), ((50, 60, 18), (70, 80, 35))) <class
'tuple'>
>>> a=np.array(t1)
>>> a
array([[[10, 20, 15],
[30, 40, 25]],

[[50, 60, 18],


[70, 80, 35]]])
>>> print(a)
[[[10 20 15]
[30 40 25]]

[[50 60 18]
[70 80 35]]]
>>> a.ndim
3
>>> a.shape
(2, 2, 3)
>>> b=a.reshape(4,3)
>>> b
array([[10, 20, 15],
[30, 40, 25],
[50, 60, 18],
[70, 80, 35]])
>>> c=a.reshape(3,4)
>>> c
array([[10, 20, 15, 30],
[40, 25, 50, 60],
[18, 70, 80, 35]])
>>> d=a.reshape(3,2,2)
>>> d
array([[[10, 20],
[15, 30]],

[[40, 25],
[50, 60]],

[[18, 70],
[80, 35]]])
>>> d[0]

357
array([[10, 20],
[15, 30]])
>>> d[1]
array([[40, 25],
[50, 60]])
>>> d[2]
array([[18, 70],
[80, 35]])
>>>

2. arange():

Syntax1:- varname=numpy.arange(Value)
Syntax2:- varname=numpy.arange(Start,Stop)
Syntax3:- varname=numpy.arange(Start,Stop,Step)
=>Here var name is an object of <class,ndarray>

=>Syntax-1 creates an object of ndarray with the values from 0 to


value-1
=>Syntax-2 creates an object of ndarray with the values from Start to
Stop-1
=>Syntax-3 creates an object of ndarray with the values from Start to
Stop-1 with equal
Interval of Value-----step
=>arange() always create an object of ndarray in 1-D array only but not
Possible to create directly 2-D and Multi Dimesional Arrays.
=>To create 2-D and Multi Dimesional Arrays, we must use reshape()

Examples:

>>> import numpy as np


>>> a=np.arange(10)
>>> a-----------array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.ndim--------1
>>> a=np.arange(50,62)
>>> print(a,type(a))---[50 51 52 53 54 55 56 57 58 59 60 61] <class
'numpy.ndarray'>
>>> a.ndim------1
>>> a=np.arange(10,23,2)
>>> a-----array([10, 12, 14, 16, 18, 20, 22])
>>> a=np.arange(10,22,2)
>>> a--------array([10, 12, 14, 16, 18, 20])
>>> b=a.reshape(2,3)
>>> c=a.reshape(3,2)
>>> b-----
array([[10, 12, 14],
[16, 18, 20]])
>>> c
array([[10, 12],
[14, 16],
[18, 20]])
>>> b.ndim-------2
>>> c.ndim--------2
>>> b.shape-----(2, 3)
>>> c.shape-----(3, 2)

358
>>> l1=[ [[10,20],[30,40]], [[15,25],[35,45]] ]
>>> l1----------[[[10, 20], [30, 40]], [[15, 25], [35, 45]]]
>>> a=np.arange(l1)----------TypeError: unsupported operand type(s) for
-: 'list' and 'int'
==================================================================
3. zeros():

=>This Function is used for building ZERO matrix either with 1-D or 2-D
or n-D
=>Syntax: varname=numpy.zeros(shape,dtype)

=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D(


Number of Matrices,Number of Rows, Number of Columns)

Examples:

>>> import numpy as np


>>> a=np.zeros(12)
>>> a-----------array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> a=np.zeros(12,dtype=int)
>>> a------------array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> a.reshape(3,4)
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> a.reshape(4,3)
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a.reshape(6,2)
array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]])
>>> a.reshape(2,6)
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])

>>> a.reshape(2,2,2,2)------ValueError: cannot reshape array of size 12


into shape (2,2,2,2)
>>> a.reshape(3,2,2)
array([[[0, 0],
[0, 0]],

[[0, 0],
[0, 0]],

359
[[0, 0],
[0, 0]]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])
>>> a.reshape(2,2,3)
array([[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]]])

>>> import numpy as np


>>> a=np.zeros((3,3),dtype=int)
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((2,3))
>>> a
array([[0., 0., 0.],
[0., 0., 0.]])
>>> a=np.zeros((2,3),int)
>>> a
array([[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((3,2,3),dtype=int)
>>> a
array([[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]]])
>>> print(a,type(a))
[[[0 0 0]
[0 0 0]]

[[0 0 0]
[0 0 0]]

[[0 0 0]
[0 0 0]]] <class 'numpy.ndarray'>

4. ones()

=>This Function is used for building ONEs matrix either with 1-D or 2-D
or n-D
=>Syntax: varname=numpy.ones(shape,dtype)

360
=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D(
Number of Matrices,Number of Rows, Number of Columns)

Examples:

>>> import numpy as np


>>> a=np.ones(10)
>>> print(a,type(a))----------[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] <class
'numpy.ndarray'>
>>> a=np.ones(10,dtype=int)
>>> print(a,type(a))-------------[1 1 1 1 1 1 1 1 1 1] <class
'numpy.ndarray'>
>>> a.shape-----------(10,)
>>> a.shape=(5,2)
>>> a
array([[1, 1],
[1, 1],
[1, 1],
[1, 1],
[1, 1]])
>>> a.ndim-------------- 2
>>> a.shape------------ (5, 2)
>>> a.shape=(2,5)
>>> a
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
>>> a.shape (2, 5)
>>>
>>> a=np.ones((3,4),dtype=int)
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> a=np.ones((4,3),dtype=int)
>>> print(a,type(a))
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]] <class 'numpy.ndarray'>
>>> a.shape----------(4, 3)
>>> a.shape=(3,2,2)
>>> a
array([[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]]])
>>> a=np.ones((4,3,3),dtype=int)
>>> a
array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],

[[1, 1, 1],

361
[1, 1, 1],
[1, 1, 1]],

[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],

[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]])

>>> a[0][0][0]-----------1
>>> a[0,0,0]-----------1
>>> a[0][0,0]------------1
================================================================
5) full()

=>This is function is used for building a matrix by specifying fill


value either 1-D or 2-D or n-D
=>Syntax:-
varname=numpy.full(shape,fill_value,dtype)
=>varname is an obejct of <class, numpy.ndarray>
=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D(
Number of Matrices,Number of Rows, Number of Columns)
=>fill_value can be any number of programmer choice

Examples:

>>> a=np.full(3,1)
>>> a---------array([1, 1, 1])
>>>print(type(a))--------<class,numpy.ndarray>
>>> a=np.full(3,9)
>>> a------------array([9, 9, 9])
>>> a=np.full(6,8)
>>> a-------------array([8, 8, 8, 8, 8, 8])
>>> a.shape=(3,2)
>>> a
array([[8, 8],
[8, 8],
[8, 8]])
>>> a=np.full(6,9)
>>> a----------array([9, 9, 9, 9, 9, 9])
>>> a.reshape(2,3)
array([[9, 9, 9],
[9, 9, 9]])
>>> a=np.full((3,3),9)
>>> a
array([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])
>>> a=np.full((2,3),6)
>>> a
array([[6, 6, 6],
[6, 6, 6]])
>>> a.reshape(3,2)
array([[6, 6],
[6, 6],
[6, 6]])

362
>>> a=np.full((3,3,3),7)
>>> a
array([[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],

[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],

[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]]])
==================================================================
6. eye()

=>This function is used for building Identity matrix or unit matrix.


=>Syntax:- varname=numpy.eye(N,M=None,K=0,dtype)
=>Here N represents number of rows
=>Here M represents number of Columns
=>If we don't represent M value then N value will be taken M values and
prepared Square Unit
Matrix.
=>Here K reporesents Principle diagnol element. if k=0 then it always
points principle diagnol
=>If k=-1,-2,-3...-n represents Bellow Principle diagnol elements.
=>If k=1,2,3.....n represents Above Principle diagnol elements.

Examples:

>>> import numpy as np


>>> #varname=numpy.eye(N,M=None,K=0,dtype
>>> a=np.eye(3)
>>> print(a,type(a))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] <class 'numpy.ndarray'>
>>> a=np.eye(3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(4,3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]
[0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class 'numpy.ndarray'>

363
>>> a=np.eye(5,6,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,k=-1,dtype=int)
>>> print(a,type(a))
[[0 0 0 0]
[1 0 0 0]
[0 1 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-1,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-2,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-3,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-4,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=1,dtype=int)
>>> print(a,type(a))
[[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=2,dtype=int)
>>> print(a,type(a))
[[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]
[0 0 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=3,dtype=int)
>>> print(a,type(a))
[[0 0 0 1 0 0]
[0 0 0 0 1 0]

364
[0 0 0 0 0 1]
[0 0 0 0 0 0]
[0 0 0 0 0 0]] <class 'numpy.ndarray'>
==========================================================
7) identity():

=>This function always bulid Identity or unit matrix


=>Syntax:- varname=numpy.identity(N,dtype)
=>Here N represents Either we can take Rows or Columns and PVM takes as
NXN Matrix (Square Matrix--Unit or Identity)

Examples:

>>> import numpy as np


>>> a=np.identity(3,dtype=int)
>>> print(a,type(a))-------------
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.identity(5,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]] <class 'numpy.ndarray'>
===================================X===================================
=
=========================================
Numpy--Arithmetic Operations
=========================================
=>On the objects of ndarray, we can apply all types of Arithmetic
Operators.
=>To perform Arithmetic Operations on the objects of ndarray in numpy
programming, we use the following functions.
a) add()
b) subtract()
c) multiply()
d) dot()
e) divide()
f) floor_divide()
g) mod()
h) power()
=>All the arithmetic Functions can also be perfomed w.r.t Arithmetic
Operators.

a) add():

Syntax:- varname=numpy.add(ndarrayobj1, ndarrayobj2)


=>This function is used for adding elements of ndarrayobj1, ndarrayobj2
and result can be displayed
Examples:

>>> l1=[ [10,20],[30,40] ]


>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a

365
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.add(a,b)
>>> c
array([[11, 22],
[33, 44]])

>>> x=np.array([[1,2,3],[4,5,6]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> y=np.array([4,4,4])
>>> y
array([4, 4, 4])
>>> z=x+y
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> z=np.add(x,y)
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> k=np.array([[2,3],[4,5]])
>>> k
array([[2, 3],
[4, 5]])
>>> kvr=np.add(x,k)----ValueError: operands could not be broadcast
together with shapes (2,3)
(2,2)

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=a+b # we used operator + instead of add()
>>> c
array([[11, 22],
[33, 44]])
=================================
b) subtract()

Syntax:- varname=numpy.subtract(ndarrayobj1, ndarrayobj2)


=>This function is used for subtracting elements of ndarrayobj1,
ndarrayobj2 and result can be displayed

366
Examples:

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.subtract(a,b)
>>> c
array([[ 9, 18],
[27, 36]])

>>> d=a-b # we used operator - instead of subtract()


>>> d
array([[ 9, 18],
[27, 36]])
===================================
c) multiply():

Syntax:- varname=numpy.multiply(ndarrayobj1, ndarrayobj2)


=>This function is used for performing element-wise multiplication of
ndarrayobj1, ndarrayobj2 and result can be displayed

Examples:
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> c=np.multiply(a,b)
>>> c
array([[ 5, 12],
[12, 12]])

>>> e=a*b # we used operator * instead of multiply()


>>> e
array([[ 5, 12],
[12, 12]])

d) dot()

=>To perform dot Matrix Multiplication, we use dot()

Syntax:- varname=numpy.dot(ndarrayobj1, ndarrayobj2)

=>This function is used for performing actual matrix multiplication of


ndarrayobj1, ndarrayobj2 and result can be displayed

367
Examples:

Examples:
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> d=np.dot(a,b)
>>> d
array([[13, 12],
[31, 30]])

e) divide()

Syntax:- varname=numpy.divide(ndarray1,ndarry2)
=>This function is used for performing element-wise division of
ndarrayobj1, ndarrayobj2 and result can be displayed

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.divide(a,b)
>>> c
array([[10., 10.],
[10., 10.]])

>>> d=a/b # we used operator / instead of divide()


>>> d
array([[10., 10.],
[10., 10.]])

f) floor_divide()

Syntax:- varname=numpy.floor_divide(ndarray1,ndarry2)
=>This function is used for performing element-wise floor division of
ndarrayobj1, ndarrayobj2 and result can be displayed
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])

368
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.floor_divide(a,b)
>>> c
array([[10, 10],
[10, 10]])

>>> d=a//b # we used operator // instead of floor_divide()


>>> d
array([[10, 10],
[10, 10]])

g) mod()

Syntax:- varname=numpy.mod(ndarray1,ndarry2)
=>This function is used for performing element-wise modulo division of
ndarrayobj1, ndarrayobj2 and result can be displayed

Examples:

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.mod(a,b)
>>> c
array([[0., 0.],
[0., 0.]])

-
=>We can also do with operator %
>>> e=a%b
>>> e
array([[0, 0],
[0, 0]], dtype=int32)

h) power():

Syntax:- varname=numpy.power(ndarray1,ndarry2)
=>This function is used for performing element-wise exponential of
ndarrayobj1, ndarrayobj2 and result can be displayed

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a

369
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>>c=np.power(a,b)
>>>print(c)
array([[ 10, 400],
[ 27000, 2560000]],

>>> f=a**b # Instead of using power() we can use ** operator


>>> f
array([[ 10, 400],
[ 27000, 2560000]], dtype=int32)
==================================X=======================

===========================================
Numpy--Statistical Operations
===========================================
=>On the object of ndarray, we can the following Statistical Operations
.
a) amax()
b) amin()
c) mean()
d) median()
e) var()
f) std()
=>These operation we can perform on the entire matrix and we can also
peform on columnwise (axis=0) and Rowwise (axis=1)
a) amax():

=>This functions obtains maximum element of the entire matrix.


=>Syntax1:- varname=numpy.amax(ndarrayobject)

=>Syntax2:- varname=numpy.amax(ndarrayobject,axis=0)--->obtains
max

=>Syntax3:- varname=numpy.amax(ndarrayobject,axis=1)--->obtains
max

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> max=np.amax(A)
>>> cmax=np.amax(A,axis=0)
>>> rmax=np.amax(A,axis=1)
>>> print("Max element=",max)-----------Max eleemnt= 4
>>> print("Column Max eleemnts=",cmax)---Column Max eleemnts= [4 4 3]
>>> print("Row Max eleemnts=",rmax)---Row Max eleemnts= [3 4 4]

b) amin():

370
=>This functions obtains minmum element of the entire matrix.
=>Syntax1:- varname=numpy.amin(ndarrayobject)

=>Syntax2:- varname=numpy.amin(ndarrayobject,axis=0)--->obtains
min

=>Syntax3:- varname=numpy.amin(ndarrayobject,axis=1)--->obtains
min
Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> min=np.amin(A)
>>> cmin=np.amin(A,axis=0)
>>> rmin=np.amin(A,axis=1)
>>> print("Min eleemnt=",min)---Min eleemnt= 1
>>> print("Column Min eleemnts=",cmin)---Column Min eleemnts= [1 2 1]
>>> print("Row Min eleemnts=",rmin)---Row Min eleemnts= [1 1 2]

c) mean():

=>This is used for cal mean of the total matrix elements.


=>The formula for mean=(sum of all elements of matrix) / total number
of elements.
Syntax1:- varname=numpy.mean(ndarrayobject)
Syntax2:- varname=numpy.mean(ndarrayobject,axis=0)--->Columnwise
Mean
Syntax3:- varname=numpy.mean(ndarrayobject,axis=1)--->Rowwise Mean

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> m=np.mean(A)
>>> cm=np.mean(A,axis=0)
>>> rm=np.mean(A,axis=1)
>>> print("Mean=",m)---------Mean= 2.4444444444444446
>>> print("Column Mean=",cm)-----Column Mean= [2.66666667 2.66666667
2. ]
>>> print("Row Mean=",rm)---Row Mean= [ 2. 2.33333333
3. ]

d) median()

=>This is used for calculating / obtaining median of entire matrix


elements.

371
=>Median is nothing but sorting the given data in ascending order and
select middle element.
=>If the number sorted elements are odd then center or middle element
becomes median.
=>If the number sorted elements are even then select center or middle
of two elements, add them and divided by 2 and that result becomes
median.

Syntax1:- varname=numpy.median(ndarrayobject)

Syntax2:- varname=numpy.median(ndarrayobject,axis=0)

Syntax3:- varname=numpy.median(ndarrayobject,axis=1)

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> md=np.median(A)
>>> cmd=np.median(A,axis=0)
>>> rmd=np.median(A,axis=1)
>>> print("Median=",md)----Median= 2.0
>>> print("Column Median=",cmd)---Column Median= [3. 2. 2.]
>>> print("Row Median=",rmd)------Row Median= [2. 2. 3.]
>>> l1=[[2,3],[4,1]]
>>> A=np.array(l1)
>>> print(A)
[[2 3]
[4 1]]
>>> md=np.median(A)
>>> cmd=np.median(A,axis=0)
>>> rmd=np.median(A,axis=1)
>>> print("Median=",md)---Median= 2.5
>>> print("Column Median=",cmd)---Column Median= [3. 2.]
>>> print("Row Median=",rmd)---Row Median= [2.5 2.5]

e) var():

Variance= sqr(mean-xi) / total number of elements


here 'xi' represents each element of matrix.

Syntax1:- varname=numpy.var(ndarrayobject)

Syntax2:- varname=numpy.var(ndarrayobject,axis=0)

Syntax3:- varname=numpy.var(ndarrayobject,axis=1)

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)

372
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)----Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556
0.88888889
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556
0.66666667]

f) std()

standard deviation=sqrt(var)

Syntax1:- varname=numpy.std(ndarrayobject)

Syntax2:- varname=numpy.std(ndarrayobject,axis=0)

Syntax3:- varname=numpy.std(ndarrayobject,axis=1)

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)---Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556
0.88888889
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556
0.66666667]

>>> sd=np.std(A)
>>> csd=np.std(A,axis=0)
>>> rsd=np.std(A,axis=1)
>>> print("std=",sd)---std= 1.0657403385139377
>>> print(" column std=",csd)--- column std= [1.24721913 0.94280904
0.81649658]
>>> print("Row std=",rsd)--Row std= [0.81649658 1.24721913 0.81649658]
==========================X=====================================

NOTE:

>>> import statistics


>>> l=[10,20,10,30,40,10,50,10]
>>> statistics.mode(l)
10
>>> l=[10,20,10,30,40,10,50,10,20,20,20]
>>> statistics.mode(l)
10

373
>>> l=[20,10,10,30,40,10,50,10,20,20,20]
>>> statistics.mode(l)
20
>>> statistics.multimode(l)
[20, 10]
>>> l=[20,10,10,30,40,10,50,10,20,20,20,10]
>>> statistics.multimode(l)
[10]
>>>

=================================================
Numpy---Basic Indexing
=================================================
==>If we want to access Single element of 1D,2D and N-D arrays we must
use the concept of Basic Indexing.

=>Accessing Single Element 1D-Array :

=>Syntax:- ndarrayname [ Index ]

=>Here 'index' can be either either +ve or -ve indexing

Examples:

>>> a=np.array([10,20,30,40,50,60])
>>> a
array([10, 20, 30, 40, 50, 60])
>>> a[0]
10
>>> a[3]
40

=>Accessing single Element of 2D :

=>Syntax:- ndarrayobj[ row index,column index]

Examples:-

>>>import numpy as np
>>> a=np.array([10,20,30,40,50,60])
>>> b=a.reshape(2,3)
>>> b
array([[10, 20, 30],
[40, 50, 60]])
>>> b[0,0]
10
>>> b[0,1]
20
>>> b[1,2]
60

======================================================================
=>Accessing single Element of 3D :

374
Syntax:- ndarrayobj[ Index of matrix , row index , column index ]

Examples:

>>> a=np.array([10,20,30,40,50,60,70,80])
>>> b=a.reshape(2,2,2)
>>> b
array([[[10, 20],
[30, 40]],

[[50, 60],
[70, 80]]])

>>> b[0,0,0]-----------10
>>> b[-1,0,0]---------50
>>> b[-2,1,1]---------40

=================================================
Numpy---Advanced Indexing
=================================================
==>If we want to access multiple elements, which are not in order
(arbitrary elements) of 1D,2D and N-D arrays we must use the concept of
Advanced Indexing.
=>If we want access the elements based on some condition then we can't
use basic indexing and Basic Slicing Operations. To fullfill such type
of requirements we must use advanced Indexing.

=>Accessing Multiple Arbitrary Elements ---1D :

=>Syntax:- ndarrayname [ x ]

=>Here 'x' can be either ndarray or list which represents required


indexes of arbitrary elements.

Examples:

>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
#access 10 30 and 80 elements
# here indexes of 10 30 and 80 are 0 2 7
>>>lst=[0,2,7] here [0,2,7] are indexes of 10 30 and 80
>>> indexes=np.array(lst) # here lst converted into ndarray object
>>> print(indexes)---------[0 2 7]
>>> print(a[indexes])--------------[10 30 80]
(OR)
>>> ind=[0,2,7] # prepare the list of indexes of arbitray
elements(10,30,80) of ndarray and pass to ndarray
>>> print(a[ind]) -----------[10 30 80]
Examples:

Q1-->Access 20 30 80 10 10 30
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]

375
>>> ind=[1,2,7,0,0,2] # [1,2,7,0,0,2] are the indexes of 20 30 80 10 10
30
>>> print(a[ind])----------------[20 30 80 10 10 30]

=>Accessing Multiple Arbitrary Elements ---2D :

=>Syntax:- ndarrayobj[ [row indexes],[column indexes] ]

Examples:-

>>>import numpy as np
>>>mat=np.array([ [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16] ] )
>>> print(mat)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

Q1) Access the principle diagnal elements 1 6 11 16

Ans:- mat[ [0,1,2,3],[0,1,2,3] ]


=>When the above statement is executed, The PVM takes internally as
mat[ (0,0), (1,1), (2,2),(3,3) ]-------- 1 6 11 16

>>> mat[ [0,1,2,3],[0,1,2,3] ]-----------array([ 1, 6, 11, 16])

Q2) Access the elements 6 14


Ans: mat[ [1,3] , [1,1] ]
=>When the above statement is executed, The PVM takes internally as
mat[ (1,1),(3,1) ]

>>> mat[[1,3],[1,1]]-----------array([ 6, 14])


======================================================================
=>Accessing Multiple Arbitrary Elements ---3D :

Syntax:- ndarray[ [Indexes of 2Dmatrix],[row indexes],[column


indexes] ]

Examples:

>>>import numpy as np
>>>l1=[ [ [1,2,3,4],[5,6,7,8],[9,10,11,12] ],[
[13,14,15,16],[17,18,19,20],[21,22,23,24] ] ]
>>>mat3d=np.array(l1)
>>>print(mat3d)
>>> print(mat3d)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

[[13 14 15 16]
[17 18 19 20]

376
[21 22 23 24]]]
>>> mat3d.ndim
3
>>> mat3d.shape
(2, 3, 4)

Q1) Access the elements 1 14 24


Ans:- mat3d[ [0,1,1], [0,0,2], [0,1,3] ]

When the above statement is executed, Internally PVM takes as follows.


=>mat3d[ (0,0,0),(1,0,1),(1,2,3) ]-Gives-->1 14 24

Q1) Access the elements 10 16


>>> mat3d[[-2,-1],[-1,-3],[-3,-1]]----------array([10, 16])
====================================================
OR
========
>>> l1=[ [ [1,2,3,4],[5,6,7,8],[9,10,11,12] ],[
[13,14,15,16],[17,18,19,20],[21,22,23,24] ] ]
>>> a=np.array(l1)
>>> a
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],

[[13, 14, 15, 16],


[17, 18, 19, 20],
[21, 22, 23, 24]]])
>>> #ndarrayobj[ [MatrixIndex],[Row Index],[Col Index] ]---Syntax
>>> #ndarrayobj[ [MatrixIndex],[Row Index],[Col Index] ]
>>> #access 1,8,13,20
>>> matind=(0,0,1,1)
>>> rowind=(0,1,0,1)
>>> colind=(0,3,0,3)
>>> a[matind,rowind,colind]
array([ 1, 8, 13, 20])
>>> a[ [0,0,0,1,1,1],[0,1,2,0,1,2],[0,1,2,0,1,2] ]
array([ 1, 6, 11, 13, 18, 23])
===========================X==========================================
a=np.array([10,20,30,40,50,60,70,80,15,25,35,45,55,65,75,85])
print(a)

a.shape=(2,2,2,2)
print(a)
[[[[10 20]
[30 40]]

[[50 60]
[70 80]]]

[[[15 25]
[35 45]]

[[55 65]
[75 85]]]]

377
#access 10 from a---4-D
a[0][0][0][0]------------10
# access 10 and 40 from a---4D
a[[0,0],[0,0],[0,1],[0,1]]----array([10, 40])
# access 60,55 and 15 from a---4D
a[ [0,1,1],[1,1,0],[0,0,0],[1,0,0] ]----array([60, 55, 15])
===========================X===========================================

=======================================================
Numpy---Indexing and Slicing Operations of 1D,2D and 3D array
=======================================================

1D Arrays Slicing:

Syntax:- 1dndrrayobj[begin:end:step]

Examples:

>>> a=np.array([10,20,30,40,50,60,70])
>>> a------------array([10, 20, 30, 40, 50, 60, 70])
>>> a[::-1]-----------array([70, 60, 50, 40, 30, 20, 10])
>>> a[::]-----------array([10, 20, 30, 40, 50, 60, 70])

2D Arrays Slicing:

Syntax:- ndrrayobj[i,j]
here 'i' represents Row Index
here 'j' represents Column Index

Syntax:- 2dndrrayobj[Row Index, Column Index]

Syntax:- 2dndrrayobj[begin:end:step, begin:end:step]

Examples:

>>> a=np.array([[10,20,30],[40,50,60]])
>>> a
array([[10, 20, 30],
[40, 50, 60]])
>>> a[0,0]
10
>>> a[0:,0:1]
array([[10],
[40]])
>>> a[0:,1:2]
array([[20],
[50]])
>>> a[1:,:]
array([[40, 50, 60]])
===============================================================
3D Arrays Slicing

Syntax:- 3dndrrayobj[i,j,k]

here 'i' represents Which 2D matrix ( Matrix Number-->0 1 2 3 4


5...... )
here 'j' represents which Rows in that 2D matrix

378
here 'k' represents which Columns in that 2D matrix
(OR)
Syntax:- 3dndrrayobj[ Matrix Index, Row Index, Column Index ]
(OR)
Syntax:- 3dndrrayobj[begin:end:step, begin:end:step,
begin:end:step ]

Examples:

>>> lst=[ [ [1,2,3],[4,5,6],[7,8,9] ],[


[13,14,15],[16,17,18],[19,20,21] ] ]
>>> print(lst)
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[13, 14, 15], [16, 17, 18], [19,
20, 21]]]
>>> arr2=np.array(lst)
>>> print(arr2)
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]

[[13 14 15]
[16 17 18]
[19 20 21]]]
>>> arr2.ndim
3
>>> arr2.shape
(2, 3, 3)
>>> arr2[:,:,0:1]
array([[[ 1],
[ 4],
[ 7]],

[[13],
[16],
[19]]])
>>> arr2[:,:,:1]
array([[[ 1],
[ 4],
[ 7]],

[[13],
[16],
[19]]])
>>> arr2[: , 0:2, 1:3]
array([[[ 2, 3],
[ 5, 6]],

[[14, 15],
[17, 18]]])
>>> arr2[: , :2, 1:]
array([[[ 2, 3],
[ 5, 6]],

[[14, 15],
[17, 18]]])

=====================================================

379
NumPy Array Copy vs View
=====================================================
=>The Difference Between Copy and View

=>The main difference between a copy and a view of an array is that the
copy is a new array, and the view is just a view of the original array.
=>The copy owns the data and any changes made to the copy will not
affect original array, and any changes made to the original array will
not affect the copy. modfifications are Independent ( Like Shallow
Copy)

=>Syntax:- varname=ndrrayobj.copy()
(OR)
ndarrayobj2=numpy.copy(ndarrayobj1)

=>The view does not own the data and any changes made to the view will
affect the original array, and any changes made to the original array
will affect the view.
=>Syntax:- varname=ndrrayobj.view()

COPY:

Example

# Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [1 2 3 4 5]

NOTE: The copy SHOULD NOT be affected by the changes made to the
original array.

VIEW:

Example

#Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [42 2 3 4 5]

NOTE : The view SHOULD be affected by the changes made to the original
array.

# Make Changes in the VIEW:

380
Example

# Make a view, change the view, and display both arrays:


import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr) # [31 2 3 4 5]
print(x) # [31 2 3 4 5]

NumPy Sorting Arrays

=>Sorting is nothing arranging the elements in an ordered sequence.


=>Ordered sequence is any sequence that has an order corresponding to
elements, like numeric or alphabetical, ascending or descending.
=>The NumPy ndarray object has a function called sort(), that will sort
a specified array.

Examples:

import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr)) # [0 1 2 3]

import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr)) # ['apple' 'banana' 'cherry']

import numpy as np
arr = np.array([True, False, True])
print(np.sort(arr)) # [False True True]

Sorting a 2-D Array

If you use the sort() method on a 2-D array, both columns and Rows of
nd array will be sorted.

Examples:

import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
#output
[[2 3 4]
[0 1 5]]

l1=[13,24,25,67,68,34,31,-12,4,89,12,67,-34,0,45,3]
a=np.array(l1)
print(a)--------------array([ 13, 24, 25, 67, 68, 34, 31, -12,
4, 89, 12, 67, -34,
0, 45, 3])

np.sort(a)[::-1]-------------array([ 89, 68, 67, 67, 45, 34, 31,


25, 24, 13, 12, 4, 3,
0, -12, -34])

381
np.sort(a)[::-1][3:6]-----------array([67, 45, 34])

a=a.reshape(4,4)
print(a) ------------ array([[ 13, 24, 25, 67],
[ 68, 34, 31, -12],
[ 4, 89, 12, 67],
[-34, 0, 45, 3]])

np.sort(a)-----------array([[ 13, 24, 25, 67],


[-12, 31, 34, 68],
[ 4, 12, 67, 89],
[-34, 0, 3, 45]])

np.sort(a,axis=0)----------array([[-34, 0, 12, -12],


[ 4, 24, 25, 3],
[ 13, 34, 31, 67],
[ 68, 89, 45,
67]])

np.sort(a,axis=0)[:,2:3]------------array([[12],
[25],
[31],
[45]])
=====================================X================================

===============================================
Numpy--selecting the elements based on condition
(OR)
Creating Filter Directly From ndArray
===============================================
=>To select any element from ndarray object, we have two approaches.
They are

Approach-1:

=>Prepare Boolean Array ( It contains True or False. True represents


Condition
satisfied and False represents Condition not satisfied]

Syntax:- varname=ndarrayobject with condition

varname is called boolean array.

=>Pass the Boolean Array to the ndarray object. so that we can get
those elements from ndarray which satisfies with the entry True(or) we
can get those elements from ndarray corresponding True entries of
Boolean array.

Syntax: ndarray [ Boolean Array ]

Approach-2:

382
=>In this approach, we directly pass Boolean array values to the
ndarray for getting required elements based on condition.

Syntax: ndarray[ndarrayobject with condition]

Examples:

Q1) Select the Possitive Elements from ndarray


>>> import numpy as np
>>> l=[10,21,-34,23,-45,30,-40]
>>> print(l)--------------[10, 21, -34, 23, -45, 30, -40]
>>> a=np.array(l)
>>> a------------array([ 10, 21, -34, 23, -45, 30, -40])
>>> b=a>0 # Boolean Array
>>> print(b)----[ True True False True False True False]
>>> a[b]-------array([10, 21, 23, 30])
===================OR=========================
>>> a[ a>0 ]-----------array([10, 21, 23, 30])

Q2) Select the Negative Elements from ndarray


>>> l=[10,21,-34,23,-45,30,-40]
>>> a=np.array(l)
>>> a---------- array([ 10, 21, -34, 23, -45, 30, -40])
>>> b=a<0 # Boolean Array
>>> b---- array([False, False, True, False, True, False,
True])
>>> a[b]------- array([-34, -45, -40])
=================OR=============
>>> a[a<0]-------------- array([-34, -45, -40])

Q3) Select the Even and Odd Elements from ndarray


>>> a=np.array([11,20,33,31,41,47,46,12,13])
>>> a------------------array([11, 20, 33, 31, 41, 47, 46, 12, 13])
>>> a[a%2==0]-----------------array([20, 46, 12])
>>> a[a%2!=0]-----------------array([11, 33, 31, 41, 47, 13])

>>> a=np.array([10,20,30,40,50,60,70,80,90])
>>> b=a.reshape(3,3)
>>> b
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
#Get Multiples of 3
>>> m3=(b%3==0)
>>> m3 #----------------------Boolean array
array([[False, False, True],
[False, False, True],
[False, False, True]])
>>> b[m3]--------------------------array([30, 60, 90])
======================OR===========================
>>> b[b%3==0]-------------------array([30, 60, 90])

383
======================================
Pandas
======================================
Introduction to Pandas:

=>Pandas is an open source Python Library / Module providing high


performance and data
manipulation and Analysis Tool.

384
=>The word PANDAs derived from PANel DAta
=>The pandas concept developed by WES MCKinney in the year 2008.
=>The Traditional Python Programming does not contain any Module for
Data Analysis and
Now Python Programming uses Pandas as a Data anaysis tool.
=>Python Pandas can be used in wide range of fields like Financial
Services, Statistics , retail
maketing sectors..etc as data analysis tool
=>pandas module developed in C and Python Languages.

Instalation of Pandas:

=>The standard python software / Distribution (CPYTHON) does not


contain any module for data analysis and now we are using third party
module called PANDAS and whose module name is "pandas"
=>Programatically to use pandas as part of our python program, we must
install pandas module by using pip tool.

Syntax:- pip install module name

Example:- pip install pandas

---
Key Features of Pandas:-----> Series DataFrame

1) Fast and Efficient Data Frame with default and costomized indexing
2) Tools for loading the data in in-memory data objects( objects of
Series, DataFrame )
3) We can access the data from pandas by using Labeled Based Slicing
and indexing.
4) Columns from in-memory data objects( objects of Series, DataFrame
) can be deleted and inserted

====================================
Series
====================================
=>It is a One-Dimensional Labelled Array Capable of Storing / Holding
Homogeneous data of any type (Integer, String, float,.........Python
objects etc).
=>The Axis Labels are collectively called Index.
=>Pandas Series is nothing but a column value in excel sheet.
=>Pandas Series Values are Mutable.
=>Pandas Series contains Homogeneous Data ( Internally even we store
different types values , They are treated as object type)

Creating a Series

=>A Series object can be created by using the folowing Syntax:


Syntax:-

varname=pandas.Series(object, index, dtype)

385
Explanation:-

=>Here varname is an object of <class, pandas.core.series.Series >


=>pandas is module name
=>Series() is pre-defined Function in pandas module and it is used for
creating an object of Series class.
=>'object' can either int, float, complex, bool, str, bytes,
bytearray,range, list,ndarray,dict .....etc (But not set type bcoz they
are un-ordered)
=>'index' represents the position of values present Series object. The
default value of Index starts from 0 to n-1, Here n represents number
of values in Series object. Programatically we can give our own Index
Values.
=>'dtype' represents data type (Ex:- int32, ,int64, float32,
float64...etc)

Examples:- Create a series for 10 20 30 40 50 60

>>> import pandas as pd


>>> import numpy as np
>>> lst=[10,20,30,40,50,60]
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 20
2 30
3 40
4 50
5 60
dtype: int64 <class 'pandas.core.series.Series'>

>>> lst=[10,20,30,40,50,60]
>>> s=pd.Series(lst,dtype=float)
>>> print(s,type(s))
0 10.0
1 20.0
2 30.0
3 40.0
4 50.0
5 60.0
dtype: float64 <class 'pandas.core.series.Series'>

>>> lst=["Rossum","Gosling","Travis","MCKinney"]
>>> a=np.array(lst)
>>> a ------array(['Rossum', 'Gosling', 'Travis', 'MCKinney'],
dtype='<U8')
>>> print(a, type(a))--['Rossum' 'Gosling' 'Travis' 'MCKinney'] <class
'numpy.ndarray'>
>>> s=pd.Series(a)
>>> print(s,type(s))
0 Rossum
1 Gosling
2 Travis
3 MCKinney
dtype: object <class 'pandas.core.series.Series'>

>>>lst=[10,"Rossum",34.56,"Author"]

386
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 Rossum
2 34.56
3 Author
dtype: object <class 'pandas.core.series.Series'>

Creating an Series object with Programmer-defined Index

>>> lst=[10,"Rossum",34.56,"Author"]
>>> print(lst)--------[10, 'Rossum', 34.56, 'Author']
>>> s=pd.Series(lst,index=["Stno","Name","Marks","Desg"])
>>> print(s)
Stno 10
Name Rossum
Marks 34.56
Desg Author
dtype: object
>>> print(s["Stno"])-------10

>>> lst=["Rossum","Gosling","Travis","MCKinney"]
>>> s=pd.Series(lst,index=[100,200,300,400])
>>> print(s,type(s))
100 Rossum
200 Gosling
300 Travis
400 MCKinney
dtype: object <class 'pandas.core.series.Series'>

Creating a Series object from dict

=>A dict object can be used for creating a series object


=>If we use dict object in Series() then keys can be taken as Indices
(Or Indexes)
automatically and corresponding values of dict can be taken as
Series data.

Examples:

>>> import pandas as pd


>>> d1={"sub1":"Python","sub2":"Java","sub3":"Data
Science","sub4":"ML"}
>>> print(d1)--{'sub1': 'Python', 'sub2': 'Java', 'sub3': 'Data
Science', 'sub4': 'ML'}
>>> s=pd.Series(d1)
>>> print(s)
sub1 Python
sub2 Java
sub3 Data Science
sub4 ML
dtype: object
>>> d2={"RS":2.3,"JG":1.2,"MCK":4.5,"TOLI":2.4}

387
>>> print(d2)---{'RS': 2.3, 'JG': 1.2, 'MCK': 4.5, 'TOLI': 2.4}
>>> s=pd.Series(d2)
>>> print(s)
RS 2.3
JG 1.2
MCK 4.5
TOLI 2.4
dtype: float64
==========================X==============================

==========================================
DataFrame in Pandas
==========================================
=>A DataFrame is 2-Dimensional Data Structure to organize the data .
=>In Otherwords a DataFrame Organizes the data in the Tabular Format,
which is
nothing but Collection of Rows and Columns.
=>The Columns of DataFrame can be Different Data Types or Same Type
=>The Size of DataFrame can be mutable.

================================================
Number of approaches to create DataFrame
================================================
=>To create an object of DataFrame, we use pre-defined DataFrame()
which is present in pandas Module and returns an object of DataFrame
class.
=>We have 5 Ways to create an object of DataFrame. They are
a) By using list / tuple
b) By using dict
c) By using Series
d) By using ndarray of numpy
e) By using CSV File (Comma Separated Values)

-
=>Syntax for creating an object of DataFrame in pandas:

varname=pandas.DataFrame(object,index,columns,dtype)

Explanation:

=>'varname' is an object of <class,'pandas.core.dataframe.DataFrame'>


=>'pandas.DataFrame()' is a pre-defined function present in pandas
module and it is used to create an object of DataFrame for storing
Data sets.
=>'object' represents list (or) tuple (or) dict (or) Series (or)
ndarray (or) CSV file
=>'index' represents Row index and whose default indexing starts from
0,1,...n-1
where 'n' represents number of values in DataFrame object.
=>'columns' represents Column index whose default indexing starts from
0,1..n-1
where n number of columns.
=>'dtype' represents data type of values of Column Value.
=======================================================
Creating an object DataFrame by Using list / tuple

388
>>>import pandas as pd
>>>lst=[10,20,30,40]
>>>df=pd.DataFrame(lst)
>>>print(df)
0
0 10
1 20
2 30
3 40

lst=[[10,20,30,40],["RS","JS","MCK","TRV"]]
df=pd.DataFrame(lst)
print(df)
0 1 2 3
0 10 20 30 40
1 RS JS MCK TRV

lst=[[10,'RS'],[20,'JG'],[30,'MCK'],[40,'TRA']]
df=pd.DataFrame(lst)
print(df)
0 1
0 10 RS
1 20 JG
2 30 MCK
3 40 TRA

lst=[[10,'RS'],[20,'JG'],[30,'MCK'],[40,'TRA']]
df=pd.DataFrame(lst, index=[1,2,3,4],columns=['Rno','Name'])
print(df)

Rno Name
1 10 RS
2 20 JG
3 30 MCK
4 40 TRA

tpl=( ("Rossum",75), ("Gosling",85), ("Travis",65),


("Ritche",95),("MCKinney",60) )
df=pd.DataFrame(tpl, index=[1,2,3,4,5],columns=['Name','Age'])
print(df)
Name Age
1 Rossum 75
2 Gosling 85
3 Travis 65
4 Ritche 95
5 MCKinney 60

Creating an object DataFrame by Using dict object

=>When we create an object of DataFrame by using Dict , all the keys


are taken as Column Names and Values of Value are taken as Data.

Examples:

>>> import pandas as pd

389
>>>
dictdata={"Names":["Rossum","Gosling","Ritche","McKinney"],"Subjects":[
"Python","Java","C","Pandas"],"Ages":[65,80,85,55] }
>>> df=pd.DataFrame(dictdata)
>>> print(df)
Names Subjects Ages
0 Rossum Python 65
1 Gosling Java 80
2 Ritche C 85
3 McKinney Pandas 55
>>> df=pd.DataFrame(dictdata,index=[1,2,3,4])
>>> print(df)
Names Subjects Ages
1 Rossum Python 65
2 Gosling Java 80
3 Ritche C 85
4 McKinney Pandas 55

Creating an object DataFrame by Using Series object

>>> import pandas as pd


>>> sdata=pd.Series([10,20,30,40])
>>> df=pd.DataFrame(sdata)
>>> print(df)
0
0 10
1 20
2 30
3 40
>>>
sdata=pd.Series({"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]})
>>> print(sdata)
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
dtype: object

>>> df=pd.DataFrame(sdata)
>>> print(df)
0
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
>>> ddata={"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]}
>>> df=pd.DataFrame(ddata)
>>> print(df)
IntMarks ExtMarks
0 10 80
1 20 75
2 30 65
3 40 50

Creating an object DataFrame by Using ndarray object

>>> import numpy as np


>>> l1=[[10,60],[20,70],[40,50]]
>>> a=np.array(l1)
>>> df=pd.DataFrame(a)
>>> print(df)

390
0 1
0 10 60
1 20 70
2 40 50
>>> df=pd.DataFrame(a,columns=["IntMarks","ExtMarks"])
>>> print(df)
IntMarks ExtMarks
0 10 60
1 20 70
2 40 50

e) By using CSV File(Comma Separated Values)

import pandas as pd1


df=pd1.read_csv("D:\KVR-JAVA\stud.csv")
print("type of df=",type(df)) #type of df= <class
'pandas.core.frame.DataFrame'>
print(df)
OUTPUT
stno name marks
0 10 Rossum 45.67
1 20 Gosling 55.55
2 30 Ritche 66.66
3 40 Travis 77.77
4 50 KVR 11.11

=======================================================
Accesssing the Data of DataFrame
=======================================================
1) DataFrameobj.head(no.of rows)
2) DataFrameobj.tail(no.of rows)

3) DataFrameobj.describe()

4) DataFrameobj.shape

5) DataFrameobj [start:stop:step]

6) DataFrameobj["Col Name"]

7) DataFrameobj[ ["Col Name1","Col Name-2"...."Col Name-n"] ]

8) DataFrameobj[ ["Col Name1","Col Name-2"...."Col Name-n"]]


[start:stop:step]
9) DataFrameobj.iterrows()
===================================================
Understabding loc() ----- here start and stop index Included and
Col Names can be used(but not
column numbers]

1) DataFrameobj.loc[row_number]
2) DataFrameobj.loc[row_number,[Col Name,.........] ]
3) DataFrameobj.loc[start:stop:step]
4) DataFrameobj.loc[start:stop:step,["Col Name"] ]

391
5) DataFrameobj.loc[start:stop:step,["Col Name1", Col Name-2......."] ]
6) DataFrameobj.loc[start:stop:step,"Col Name1" : Col Name-n"]

Understabding iloc() ----- here start index included and stop index
excluded and
Col Numbers must be used(but
not column names]

1) DataFrameobj.iloc[row_number]
2) DataFrameobj.iloc[row_number,Col Number.........]
3) DataFrameobj.iloc[row_number,[Col Number1,Col Number2............] ]
3) DataFrameobj.iloc[row start:row stop, Col Start: Col stop]
4) DataFrameobj.iloc[row start:row stop,Col Number ]
5) DataFrameobj.iloc[ [row number1, row number-2.....] ]
6) DataFrameobj.iloc[ row start: row stop , [Col Number1,Col
Number2............] ]
6) DataFrameobj.iloc[ : , [Col Number1,Col Number2............] ]
=======================================================================
Adding Column Name to Data Frame
=======================================================================
1) dataframeobj['new col name']=default value
2) dataframeobj['new col name']=expression
=======================================================================
Removing Column Name from Data Frame
=======================================================================
1)dataframe.drop(columns="col name")
2)dataframe.drop(columns="col name",inplace=True)
=======================================================================
sorting the dataframe data
=======================================================================
1) dataframeobj.sort_values("colname")
2) dataframeobj.sort_values("colname",ascending=False)
3) dataframeobj.sort_values(["colname1","col name2",...col name-n] )
=======================================================================
knowing duplicates in dataframe data
=======================================================================
1) dataframeobj.duplicated()---------------gives boolean result
=======================================================================
Removing duplicates from dataframe data
=======================================================================
1) dataframeobj.drop_duplicates()
2) dataframeobj.drop_duplicates(inplace=True)
=======================================================================
Data Filtering and Conditional Change
=======================================================================
1) dataframeobj.loc[ simple condition]

Ex: df.loc[ df["maths"]>75 ]

2) dataframeobj.loc[ compund condition]


Ex: df.loc[ (df["maths"]>60) & (df["maths]<85)
]
Ex: df.loc[ (df["percent"]>=60) & (df["percent"]<=80),
["grade"]]="First" # cond updattion.

392
=======================================================================

13-jul-2022

==================================================
DataFrame--GroupBy
==================================================
=>The Group By mechanism in the Pandas provides a way to break a
DataFrame into different groups or chunks based on the values of single
or multiple columns.
=>Let‟s understand with some examples.
Assume we have a DataFrame,

ID Name Age City Experience

11 Jack 44 Sydney 19
12 Riti 41 Delhi 17
13 Aadi 46 Mumbai 11
14 Mohit 45 Delhi 15
15 Veena 43 Delhi 14
16 Shaunak 42 Mumbai 17
17 Manik 42 Sydney 14
18 Vikas 42 Delhi 11
19 Samir 42 Mumbai 15
20 Shobhit 40 Sydney 12

=>This DataFrame has a column „City‟ which has three unique values
like, “Delhi”, “Mumbai” and “Sydney”. We want to create different
groups out of this DataFrame based on the column “City” values.
=>As this column has only three unique values, so there will be three
different groups.
=>Group 1 will contain all the rows for which column “City” has the
value “Delhi” i.e.

ID Name Age City Experience

12 Riti 41 Delhi 17
14 Mohit 45 Delhi 15
15 Veena 43 Delhi 14
18 Vikas 42 Delhi 11

Group 2 will contain all the rows for which column “City” has the value
“Mumbai” i.e.

ID Name Age City Experience

13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15

393
Group 3 will contain all the rows for which column “City” has the value
“Sydney” i.e.

ID Name Age City Experience


11 Jack 44 Sydney 19
17 Manik 42 Sydney 14
20 Shobhit 40 Sydney 12

The groupby() method of DataFrame, gives us an iterable object of group


Name and contents. We can also select individual groups too. It also
provides a way to group large amounts of data and compute operations on
these groups. For example, by using the GroupBy mechanism for the above
DataFrame, we can get the,

Mean Experience of employees for each Group.


Mean Age of employees for each Group.
Maximum Experience of an employee for each Group.
Minimum Experience of an employee for each Group.
Maximum Age of an employee for each Group.
Minimum Age of an employee for each Group.
and many more things….

DataFrame.groupby() method

DataFrame‟s groupby() method accepts column names as arguments. Based


on the column values, it creates several groups and returns a
DataFrameGroupBy object that contains information about these groups.

For example, let‟s create groups based on the column “City”,

# Create Groups based on values in column 'city'


groupObj = df.groupby('City')
print(groupObj)

Output

<pandas.core.groupby.generic.DataFrameGroupBy object at
0x000002895CA14048>

The groupby() function created three groups because column „City‟ has
three unique values. It returned a DataFrameGroupBy object with
information regarding all three groups.

Iterate over all the DataFrame Groups

DataFrame‟s groupby() function returns a DataFrameGroupBy object, which


contains the information of all the groups. The DataFrameGroupBy is an
iterable object. It means using a for loop, we can iterate over all the
created Groups,

394
# Iterate over all the groups
for grpName, rows in df.groupby('City'):
print("Group Name: ", grpName)
print('Group Content: ')
print(rows)

Output:

Group Name: Delhi


Group Content:
Name Age City Experience
ID
12 Riti 41 Delhi 17
14 Mohit 45 Delhi 15
15 Veena 43 Delhi 14
18 Vikas 42 Delhi 11
Group Name: Mumbai
Group Content:
Name Age City Experience
ID
13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15
Group Name: Sydney
Group Content:
Name Age City Experience
ID
11 Jack 44 Sydney 19
17 Manik 42 Sydney 14
20 Shobhit 40 Sydney 12

=>We iterated over the DataFrameGroupBy object using a for loop. For
each of the groups, it returns a tuple. This tuple contains the group
Name and a DataFrame containing the rows in that Group.
=>In our example, the group names were the unique values of “City”
Column i.e. “Delhi”, “Mumbai” and “Sydney”. So, basically, a group was
created for each city, and the group name is the corresponding city
name.

Get first row of each Group

=>DataFrame‟s groupby() function returns a DataFrameGroupBy object,


which contains the information of all the groups. The DataFrameGroupBy
object also provides a function first(), and it returns a DataFrame
containing the first row of each of the Group.
=>The pandas.groupby().nth() function is used to get the value
corresponding the nth row for each group. To get the first value in a
group, pass 0 as an argument to the nth() function.

For example

# Get first row of each group


firstRowDf = df.groupby('City').first()
print(firstRowDf)

Output:

395
Name Age Experience
City
Delhi Riti 41 17
Mumbai Aadi 46 11
Sydney Jack 44 19
There were three unique values in the column “City”, therefore 3 groups
were created. The first() function fetched the first row of each of the
Group and returned a DataFrame populated with that. The returned
DataFrame has a row for each of the city and it is the first row from
each of the city groups.

Get the count of number of DataFrame Groups

The DataFrameGroupBy object also provides a function size(), and it


returns the count of rows in each of the groups created by the
groupby() function. For example,

# Get the size of DataFrame groups


print(df.groupby('City').size())

Output:

Delhi 4
Mumbai 3
Sydney 3
dtype: int64
As there were three unique values in the column “City”, therefore 3
groups were created by groupby() function. The size() function returned
a Series containing the count of number of rows for each of the group.

Get a specific DataFrame Group by the group name

DataFrame‟s groupby() function returns a DataFrameGroupBy object, which


contains the information of all the groups. The DataFrameGroupBy object
also provides a function get_group(). It accepts a group name as an
argument and returns a DataFrame containing only rows for that group.
For example, for our DataFrame, the groupby(“City”) function created
three objects and returned a DataFrameGroupBy object. The group names
were the unique values in column “City” i.e. “Delhi”, “Mumbai” and
“Sydney”. So, let‟s select the rows of Group named “Mumbai”,

# Get a specific group by the group name


specificGroup = df.groupby('City').get_group('Mumbai')
print(specificGroup)

Output:

Name Age City Experience


ID
13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17

396
19 Samir 42 Mumbai 15

It returned a DataFrame containing all the rows for “Mumbai” group.

Statistical operations on the DataFrame GroupBy object

DataFrame‟s groupby() function returns a DataFrameGroupBy object, which


contains the information of all the groups. The DataFrameGroupBy object
also provides a function mean(). It returns the mean values of all
numeric columns for each Group. For example,

# Get the mean of all numeric columns in each of the group


meanValues = df.groupby('City').mean()
print(meanValues)

Output:

Age Experience
City
Delhi 42.750000 14.250000
Mumbai 43.333333 14.333333
Sydney 42.000000 15.000000
Our DataFrame has two numeric columns „Age‟ and „Experience‟. The
mean() function calculated the mean values for these columns in each of
the groups and returned a DataFrame. Basically, this DataFrame contains
the mean of employees‟ age and Experience of employees in each of the
three cities.

If we are interested in mean values of a single column only, then we


can first select the column and later call the mean() function. For
example,

# Get the mean Age of employees


# in each of the three cities
meanAge = df.groupby('City')['Age'].mean()
print(meanAge)

Output:

City
Delhi 42.750000
Mumbai 43.333333
Sydney 42.000000
Name: Age, dtype: float64
It returned the mean Age of employees in each of the three cities.
Apart from mean() function, the DataFrameGroupBy object also provides
many other functions for aggregations.

Get the count of number of DataFrame Groups

397
The DataFrameGroupBy object also provides a function size(), and it
returns the count of rows in each of the groups created by the
groupby() function. For example,

# Get the size of DataFrame groups


print(df.groupby('City').size())

Output:

Delhi 4
Mumbai 3
Sydney 3
dtype: int64

As there were three unique values in the column “City”, therefore 3


groups were created by groupby() function. The size() function returned
a Series containing the count of number of rows for each of the group.

Get a specific DataFrame Group by the group name

DataFrame‟s groupby() function returns a DataFrameGroupBy object, which


contains the information of all the groups. The DataFrameGroupBy object
also provides a function get_group(). It accepts a group name as an
argument and returns a DataFrame containing only rows for that group.
For example, for our DataFrame, the groupby(“City”) function created
three objects and returned a DataFrameGroupBy object. The group names
were the unique values in column “City” i.e. “Delhi”, “Mumbai” and
“Sydney”. So, let‟s select the rows of Group named “Mumbai”,

# Get a specific group by the group name


specificGroup = df.groupby('City').get_group('Mumbai')
print(specificGroup)
Output:

Name Age City Experience


ID
13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15
It returned a DataFrame containing all the rows for “Mumbai” group.

Statistical operations on the DataFrame GroupBy object

DataFrame‟s groupby() function returns a DataFrameGroupBy object, which


contains the information of all the groups. The DataFrameGroupBy object
also provides a function mean(). It returns the mean values of all
numeric columns for each Group. For example,

398
# Get the mean of all numeric columns in each of the group
meanValues = df.groupby('City').mean()
print(meanValues)
Output:

Age Experience
City
Delhi 42.750000 14.250000
Mumbai 43.333333 14.333333
Sydney 42.000000 15.000000

Our DataFrame has two numeric columns „Age‟ and „Experience‟. The
mean() function calculated the mean values for these columns in each of
the groups and returned a DataFrame. Basically, this DataFrame contains
the mean of employees‟ age and Experience of employees in each of the
three cities.

If we are interested in mean values of a single column only, then we


can first select the column and later call the mean() function. For
example,

# Get the mean Age of employees


# in each of the three cities
meanAge = df.groupby('City')['Age'].mean()
print(meanAge)
Output:

City
Delhi 42.750000
Mumbai 43.333333
Sydney 42.000000
Name: Age, dtype: float64
It returned the mean Age of employees in each of the three cities.
Apart from mean() function, the DataFrameGroupBy object also provides
many other functions for aggregations.

import pandas as pd
# List of Tuples
empoyees = [(11, 'Jack', 44, 'Sydney', 19) ,
(12, 'Riti', 41, 'Delhi' , 17) ,
(13, 'Aadi', 46, 'Mumbai', 11) ,
(14, 'Mohit', 45, 'Delhi' , 15) ,
(15, 'Veena', 43, 'Delhi' , 14) ,

399
(16, 'Shaunak', 42, 'Mumbai', 17 ),
(17, 'Manik', 42, 'Sydney', 14 ),
(18, 'Vikas', 42, 'Delhi', 11 ),
(19, 'Samir', 42, 'Mumbai', 15 ),
(20, 'Shobhit', 40, 'Sydney', 12)]
# Create a DataFrame object
df = pd.DataFrame( empoyees,
columns=['ID', 'Name', 'Age', 'City',
'Experience'])
df = df.set_index('ID')
# Display the DataFrame
print(df)
print(" ")
for grpName, rows in df.groupby('City'):
print("Group Name: ", grpName)
print('Group Content: ')
print(rows)
print("-"*50)
print(" ")
firstRowDf = df.groupby('City').nth(1)
print(firstRowDf)

========================================
Multi Threading in Python
========================================
=>The purpose of Multi Threading is " To provide Concurrent Execution "
=>The concurrent execution is nothing but Simultaneous or Parallel
Execution.
=>The Advantage of Concurrent Execution is that always takes Less
Execution Time.

=>In the context of Programming Languages, we have 2 types of


Languages. They are
a) Process Based Applications
b) Thread Based Applications.

a) Process Based Applications:

=>Process Based Applications execution environment contains Single


Thread
=>Process Based Applications provides Sequential Execution
=>Process Based ApplicationsTakes More Execution Time
=>Process Based Applications are treated as Heavy Weight Application.
Examples: C,CPP...etc

b) Thread Based Applications.

=>Thread Based Applications are those whose execution environment


contains Single Thread
(by deafult) and allows us create Multiple Threads programatically.
=>Thread Based Applications provides Sequential Execution (by default)
also provides
Concurrent Execution programatically.
=>Thread Based Applications Takes Less Execution Time

400
=>Thread Based Applications are treated as Light Weight Applications.

Examples: Python, Java . C#.Net...etc

=========================================
Intruduction to Thread Based Applications
=========================================
=>The purpose of multi threading is that "To provide Concurrent /
Simultaneous
execution / Paralllel Execution".
=>Concurrent Execution is nothing but executing the operations all at
once.
=>The advantage of Concurrent execution is that to get less execution
time.
=>If a Python Program contains multiple threads then it is called Multi
Threading program.

=>Def. of thread:

=>A flow of Control is called thread.


=>The purpose of thread is that "To Perform certain operation whose
logic
developed in Functions / Methods concurently."

=>By default Every Python contains Single Thread and whose name is
"MainThread" and It provides Sequential Execution.
=>Programtically, In a Python Program we can create multiple sub /
Child
threads and whose purpose is that "To execute operations whose
logic is written in Functions / Methods Concurrently ".
=>Hence Programatically a Python Program contains two types of Threads.
They are
a) MainThread
b) Sub / Child Threads
=>MainThread is created / Initiated by PVM ,when program exeuction
starts and the role of mainThread is to execute main program statements
and Monitor the exeuction status of Sub threads.
=>The Sub / Child Threads always executes operations whose logic is
written in Functions / Methods Concurrently ".
=====================================X=================================
=
#Program for showing "mainthread" in python program
#Thdemo1.py
import threading
print("Default Name of thread=",threading.current_thread().name)

#Program for showing "mainthread" in python program


#Thdemo2.py
import threading

def fun1():
print("Line-6-I am from fun1() execured by
:",threading.current_thread().name)

401
def fun2():
print("Line-9-I am from fun2() execured by
:",threading.current_thread().name)

def fun3():
print("Lin-12-I am from fun3() execured by
:",threading.current_thread().name)

def fun4():
print("Line-15-I am from fun1() execured by
:",threading.current_thread().name)

#main program
print("Line-18-Default Name of thread in main
program=",threading.current_thread().name)
fun1()
print("Line-20-Default Name of thread in main
program=",threading.current_thread().name)
fun2()
print("Line-22-Default Name of thread in main
program=",threading.current_thread().name)
fun3()
print("Line-24-Default Name of thread in main
program=",threading.current_thread().name)
fun4()

#NonThreads.py
import time, threading
def squares(lst):
for val in lst:
print("square({})={} generated by
:{}".format(val,val**2,threading.current_thread().name))
time.sleep(1)
def cubes(lst):
for val in lst:
print("cube({})={} generated by
:{}".format(val,val**3,threading.current_thread().name))
time.sleep(1)

#main program
bt=time.time()
print("Default Name of thread in main
program=",threading.current_thread().name)
lst=[3,-5,12,4,16,19,6,9]
squares(lst)
cubes(lst)
print("\nProgram ended")
et=time.time()
print("Total Execution of non-threading program=",(et-bt))
#ThreadsApp.py
import time, threading
def squares(lst):
for val in lst:
print("square({})={} generated by
:{}".format(val,val**2,threading.current_thread().name))
time.sleep(1)

402
def cubes(lst):
for val in lst:
print("cube({})={} generated by
:{}".format(val,val**3,threading.current_thread().name))
time.sleep(1)

#main program
bt=time.time()
print("Default Name of thread in main
program=",threading.current_thread().name)
lst=[3,-5,12,4,16,19,6,9]
#Create sub threads
t1=threading.Thread(target=squares,args=(lst, ) ) # t1---Thread-1
t2=threading.Thread(target=cubes,args=(lst, ) ) # t2---Thread-2
t1.start()
t2.start()
t1.join()
t2.join() print("\
nProgram ended")
et=time.time()
print("Total Execution of threading program=",(et-bt))

====================================================
Module Name for developing thread based applications
====================================================
=>To develop any thread based applications, must use a pre-defined
module called "threading".
==========================
=>Details of threading module
==========================
=>Functions in threading Module

1) current_thread():

=>This Function is used for finding thread name which is running


Syntax:- varname=threading.current_thread().name

2) active_count():

=>This Function is used for counting number threads which are running
Syntax: varname=threading.active_count()

=>Class Name in threading Module: Thread:

1) Thread(target,args): This Constructor is used for creating an object


of child thread by specifying target function which is executed by
child thread and also specifying values passing to target function in
the form of tuple.
Syntax:- childthreadname=threading.Thread(target=functioname,
args=(val1,val2..val-n) )
Example: t1=threading.Thread(target=table,args=(10,) )

2) setName(str) or name

403
This function is used for setting user-friendly name to thread
instead of giving default thread name
Syntax: childthreadname.setName(str)
(OR)
Syntax: childthreadobj . name=str

Examples: t1.setName("Rossum")
or
t1.name="Rossum"

3) getName() (or) name


=>This function is used for obtaing name of thread.
=>Syntax:- threadobj.getName()
(or)
threadobj.name
Example: - t1=threading.Thread(target=multable,args=(19,))
print(t1.getName()) # Thread-1
(or)
print(t1.name) # Thread-1

4) start():
This function is used for dispatching or sending the child
thread to targeted function by passing the values as args in the form
of tuple
Syntax: childthreadname.start()
Example: t1.start()

5) is_alive(): This Function can be used to check the exeution status


of child thread.
This Function returns True provided the thread is under
execution / running
This Function returns False provided the thread is not yet
strated or completed execution
Syntax:- threadobj.is_alive()

6) join(): This function is used for making the child threads to join
with main thread after their completion of execution.
Syntax: childthreadname1.join()
childthreadname2.join()

-
childthreadname-n.join()

================================================================
Number of approaches to develop thread based applications
================================================================
=>We have two approaches to develop thread based applications. They are

1. By Using Functional Approach

404
2. By Using Object Oriented Approach

1. By Using Functional Approach

Step-1: import threading module


Step-2: Define a Function with Block of Statements and it is
executed by sub thread.
Step-3: create an object of Thread class ( Nothing but creating sub
thread )
Step-4 : Dispatch the sub thread ( start the sub thread) by using
start()

Examples:

#ThreadProgEx5.py
import threading # Step-1
def fun1(): # Step-2
print("-"*50)
print("Name of the thread executing
fun1={}".format(threading.current_thread().name))
for i in range(1,10):
print("\tVal of i=",i)
time.sleep(1)
print("-"*50)

#main program
t1=threading.Thread(target=fun1)#creating sub thread--t1--Thread-1 ----
Step-3
t1.start() # Step-4
======================================================================
2. By Using Object Oriented Approach

Step-1: import threading module


Step-2: Define Programmer-defined class
Step-3: Defijned Programmer-defined method inside of Programmer-
defined class
Step-4: create sub thread obj in main program
step-5: start the sub thread.

Examples:

#ThreadProgEx8.py
import threading # Step-1
class Kvr: # step-2
def init (self,n):
self.n=n
def fun1(self): # step-3
print("fun1() from Kvr Class")
print("val of n=",self.n)
print("Name of sub thread in fun1() of
Kvr=",threading.current_thread().name)

#main program
k=Kvr(50)
t1=threading.Thread(target=k.fun1 ) # step-4

405
t1.name="Rossum"
t1.start() # step-5

#NumGenEx1.py
import threading,time # Step-1
def generate(): # Step-2
print("-"*50)
print("Name of thread in
generate()=",threading.current_thread().name)
n=int(input("Enter How Many Number u want to generate:"))
if(n<=0):
print("{} is invalid".format(n))
else:
print("-"*50)
print("Number within:{}".format(n))
print("-"*50)
for i in range(1,n+1):
print("\tValue of i={}".format(i))
time.sleep(1)
else:
print("-"*50)

#main program
t1=threading.Thread(target=generate) # Step-3
print("Execution status of t1 before start=",t1.is_alive())
t1.start() # step-4
print("Execution status of t1 after start=",t1.is_alive())
t1.join()
print("Line:25--Execution status of t1 after
completion=",t1.is_alive())

#NumGenEx2.py
import threading,time # Step-1
def generate(n): # Step-2
print("-"*50)
print("Name of thread in
generate()=",threading.current_thread().name)
if(n<=0):
print("{} is invalid".format(n))
else:
print("-"*50)
print("Number within:{}".format(n))
print("-"*50)
for i in range(1,n+1):
print("\tValue of i={}".format(i))
time.sleep(1)
else:
print("-"*50)

#main program
t1=threading.Thread(target=generate, args=(15,) ) # Step-3
print("Execution status of t1 before start=",t1.is_alive())
t1.start() # step-4
print("Execution status of t1 after start=",t1.is_alive())
t1.join()

406
print("Line:25--Execution status of t1 after
completion=",t1.is_alive())

#ThreadProgEx1.py
import threading
tname=threading.current_thread()
print("Thread Name=",tname.name)
print(" OR ")
print("Thread Name=",threading.current_thread().name)

# Here 'name' attribute next version of getName() and it obtains name


of thread.

#ThreadProgEx2.py
import threading
tname=threading.current_thread()
print("Thread Name=",tname.name)
print(" OR ")
print("Thread Name=",threading.current_thread().name)
nt=threading.active_count()
print("Number of threads in this program=",nt) # 1

# Here 'name' attribute next version of getName() and it obtains name


of thread.

#ThreadProgEx3.py
import threading
def fun1():
print("-"*50)
print("i am from fun1:")
print("Name of the thread executing
fun1={}".format(threading.current_thread().name))
print("-"*50)

#main program
print("Name of the thread executing in main
prog={}".format(threading.current_thread().name))
t1=threading.Thread(target=fun1)#creating sub thread--t1--Thread-1
print("Execution status of t1 before start()=",t1.is_alive())
t1.start()
print("Execution status of t1 after start()=",t1.is_alive())

#ThreadProgEx4.py
import threading
def fun1():
print("-"*50)
print("i am from fun1:")
print("Name of the thread executing
fun1={}".format(threading.current_thread().name))
print("-"*50)

#main program
print("Name of the thread executing in main
prog={}".format(threading.current_thread().name))
t1=threading.Thread(target=fun1)#creating sub thread--t1--Thread-1

407
print("Name of Sub thread=",t1.name) # Thread-1
t1.name="HYD"
print("Name of Sub thread=",t1.name) # HYD
t1.start()

#ThreadProgEx5.py
import threading,time
def fun1():
print("-"*50)
print("Name of the thread executing
fun1={}".format(threading.current_thread().name))
for i in range(1,10):
print("\tVal of i=",i)
time.sleep(1)
print("-"*50)

#main program
print("Name of the thread executing in main
prog={}".format(threading.current_thread().name))
t1=threading.Thread(target=fun1)#creating sub thread--t1--Thread-1
print("Execution status of sub thread before start=",t1.is_alive()) #
False
t1.start()
print("Execution status of sub thread after start=",t1.is_alive()) #
True
t1.join()
print("Line-18: Execution status of sub thread after
completion=",t1.is_alive()) # False

#ThreadProgEx6.py
import threading
class Kvr:
def fun1(self):
print("fun1() from Kvr Class")
print("Name of sub thread in fun1() of
Kvr=",threading.current_thread().name)

#main program
k=Kvr()
t1=threading.Thread(target=k.fun1)
t1.name="Rossum"
t1.start()

#ThreadProgEx7.py
import threading # Step-1
class Kvr: # step-2
def fun1(self,n): # step-3
print("fun1() from Kvr Class")
print("val of n=",n)
print("Name of sub thread in fun1() of
Kvr=",threading.current_thread().name)

#main program
t1=threading.Thread(target=Kvr().fun1,args=(50,) ) # step-4
t1.name="Rossum"

408
t1.start() # step-5

#ThreadProgEx8.py
import threading # Step-1
class Kvr: # step-2
def init (self,n):
self.n=n
def fun1(self): # step-3
print("fun1() from Kvr Class")
print("val of n=",self.n)
print("Name of sub thread in fun1() of
Kvr=",threading.current_thread().name)

#main program
k=Kvr(50)
t1=threading.Thread(target=k.fun1 ) # step-4
t1.name="Rossum"
t1.start() # step-5

====================================================
Module Name for developing thread based applications
====================================================
=>To develop any thread based applications, must use a pre-defined
module called "threading".
==========================
=>Details of threading module
==========================
=>Functions in threading Module

1) current_thread():

=>This Function is used for finding thread name which is running


Syntax:- varname=threading.current_thread().name

2) active_count():

=>This Function is used for counting number threads which are running
Syntax: varname=threading.active_count()

=>Class Name in threading Module: Thread:

1) Thread(target,args): This Constructor is used for creating an object


of child thread by specifying target function which is executed by
child thread and also specifying values passing to target function in
the form of tuple.
Syntax:- childthreadname=threading.Thread(target=functioname,
args=(val1,val2..val-n) )
Example: t1=threading.Thread(target=table,args=(10,) )

2) setName(str) or name

This function is used for setting user-friendly name to thread


instead of giving default thread name
Syntax: childthreadname.setName(str)

409
(OR)
Syntax: childthreadobj . name=str

Examples: t1.setName("Rossum")
or
t1.name="Rossum"

3) getName() (or) name


=>This function is used for obtaing name of thread.
=>Syntax:- threadobj.getName()
(or)
threadobj.name
Example: - t1=threading.Thread(target=multable,args=(19,))
print(t1.getName()) # Thread-1
(or)
print(t1.name) # Thread-1

4) start():
This function is used for dispatching or sending the child
thread to targeted function by passing the values as args in the form
of tuple
Syntax: childthreadname.start()
Example: t1.start()

5) is_alive(): This Function can be used to check the exeution status


of child thread.
This Function returns True provided the thread is under
execution / running
This Function returns False provided the thread is not yet
strated or completed execution
Syntax:- threadobj.is_alive()

6) join(): This function is used for making the child threads to join
with main thread after their completion of execution.
Syntax: childthreadname1.join()
childthreadname2.join()

-
childthreadname-n.join()

7) run(): It is one of null body method of thread class


It is used for defining logic of python program, which is
executed by child thread
This method must be overridden inside of sub class of
Thread class .
Syntax: class <classname>(threading.Thread):
def run(self):

Examples:

410
#ThreadRunEx1.py
import threading
class Hyd(threading.Thread):
def run(self):
print("i am from run() and thread
name=",threading.current_thread().name)

# main program
h=Hyd()
h.name="KVR"
h.start()

================================================
Synchronization in Multi Threading
(OR)
Locking concept in Threading
================================================
=>When multiple threads are operating / working on the same
resource(function / method) then by default we get dead lock result /
race condition / wrong result / non-thread safety result.
=>To overcome this dead lock problems, we must apply the concept
Synchronization concept.
=>The advantage of synchronization concept is that to avoid dead lock
result and provides Thread Safety Result.
=>In Python Programming, we can obtain synchronization concept by using
locking and un-locking concept.

=>Steps for implementing Synchronization Concept:

1) obtain / create an object of Lock class, which is present in


threading module.
Syntax:-
lockobj=threading.Lock()
2) To obtain the lock on the sharable resource, we must use acquire()
Syntax:
lockobj.acquire()
Once current object acquire the lock, other thread objects are
made wait until curent thread object releases the lock.
3) To un-lock the sharable resource/current object, we must use
release()
Syntax:

lockobj.release()

Once current object releases the lock, other objects are


permitted into shrable resource. This process of aquiring the releasing
the lock will be continued until all the objects completed their
execution.

#nonsyncex1funs.py
import threading,time
def table(n):
print("Name of the thread=",threading.current_thread().name)
if(n<=0):

411
print("{} is invalid input:".format(n))
else:
print("-"*50)
print("Mul table for :{}".format(n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
time.sleep(1)
else:
print("-"*50)

#main program
#Create multiple sub threads
t1=threading.Thread(target=table,args=(19,) )
t2=threading.Thread(target=table,args=(9,) )
t3=threading.Thread(target=table,args=(-6,) )
t4=threading.Thread(target=table,args=(8,) )
#dispatch the threads
t1.start()
t2.start()
t3.start()
t4.start()

#nonsyncex1oops.py
import threading,time
class MulTable:
def table(self,n):
self.n=n
print("Name of the
thread=",threading.current_thread().name)
if(self.n<=0):
print("{} is invalid input:".format(self.n))
else:
print("-"*50)
print("Mul table for :{}".format(self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} =
{}".format(self.n,i,self.n*i))
time.sleep(1)
else:
print("-"*50)

#main program
#Create multiple sub threads
t1=threading.Thread(target=MulTable().table,args=(19,) )
t2=threading.Thread(target=MulTable().table,args=(9,) )
t3=threading.Thread(target=MulTable().table,args=(-6,) )
t4=threading.Thread(target=MulTable().table,args=(8,) )
#dispatch the threads
t1.start()
t2.start()
t3.start()
t4.start()

#syncex1funs.py
import threading,time
def table(n):

412
L.acquire() # step-2
print("Name of the thread=",threading.current_thread().name)
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*50)
print("Mul table for :{}".format(n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
time.sleep(1)
else:
print("-"*50)
L.release() # step-3

#main program
L=threading.Lock() # Step-1
#Create multiple sub threads
t1=threading.Thread(target=table,args=(19,) )
t2=threading.Thread(target=table,args=(9,) )
t3=threading.Thread(target=table,args=(-6,) )
t4=threading.Thread(target=table,args=(8,) )
#dispatch the threads
t1.start()
t2.start()
t3.start()
t4.start()

#syncex1oops.py
import threading,time
class MulTable:
L=threading.Lock() # Class Level Variable Name--Step-1
def table(self,n):
MulTable.L.acquire() # Step-2
self.n=n
print("Name of the
thread=",threading.current_thread().name)
if(self.n<=0):
print("{} is invalid input:".format(self.n))
else:
print("-"*50)
print("Mul table for :{}".format(self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} =
{}".format(self.n,i,self.n*i))
time.sleep(1)
else:
print("-"*50)
MulTable.L.release() # Step-3
#main program
#Create multiple sub threads
t1=threading.Thread(target=MulTable().table,args=(19,) )
t2=threading.Thread(target=MulTable().table,args=(9,) )
t3=threading.Thread(target=MulTable().table,args=(-6,) )
t4=threading.Thread(target=MulTable().table,args=(8,) )
#dispatch the threads
t1.start()

413
t2.start()
t3.start()
t4.start()

#syncex2oops.py
import threading,time
class MulTable:
L=threading.Lock() # Class Level Variable Name--Step-1
def table(self,n):
self.L.acquire() # Step-2
self.n=n
print("Name of the
thread=",threading.current_thread().name)
if(self.n<=0):
print("{} is invalid input:".format(self.n))
else:
print("-"*50)
print("Mul table for :{}".format(self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} =
{}".format(self.n,i,self.n*i))
time.sleep(1/8)
else:
print("-"*50)
self.L.release() # Step-3
#main program
#Create multiple sub threads
t1=threading.Thread(target=MulTable().table,args=(19,) )
t2=threading.Thread(target=MulTable().table,args=(9,) )
t3=threading.Thread(target=MulTable().table,args=(-6,) )
t4=threading.Thread(target=MulTable().table,args=(8,) )
#dispatch the threads
t1.start()
t2.start()
t3.start()
t4.start()
#syncex2runoops.py
import threading,time
class MulTable(threading.Thread):
L=threading.Lock() # Class Level Variable Name--Step-1
def setn(self,n):
self.n=n
def run(self):
self.L.acquire() # Step-2
print("Name of the
thread=",threading.current_thread().name)
if(self.n<=0):
print("{} is invalid input:".format(self.n))
else:
print("-"*50)
print("Mul table for :{}".format(self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} =
{}".format(self.n,i,self.n*i))
time.sleep(0.1)
else:

414
print("-"*50)
self.L.release() # Step-3
#main program
#Create multiple sub threads
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
t1.setn(10)
t2.setn(-60)
t3.setn(8)
t4.setn(19)
#dispatch the threads
t1.start()
t2.start()
t3.start()
t4.start()

#ReservationEx1.py
import threading
class Train:
@classmethod
def getlock(cls):
cls.L=threading.Lock()
def init (self,seats):
self.seats=seats
def reservation(self,nos):
self.L.acquire()
print("
")
if(nos>self.seats):
print("Hi, {}, {} seats are not available
".format(threading.current_thread().name,nos))
else:
self.seats=self.seats-nos
print("Hi, {}, {} seats Reserved
".format(threading.current_thread().name,nos))
print("
")
print("Number of seats Available={}".format(self.seats))
print("
")
self.L.release()
#Main program
Train.getlock()
t=Train(20)
t1=threading.Thread(target=t.reservation,args=(50,))
t2=threading.Thread(target=t.reservation,args=(26,))
t3=threading.Thread(target=t.reservation,args=(16,))
t4=threading.Thread(target=t.reservation,args=(9,))
t5=threading.Thread(target=t.reservation,args=(1,))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()

415
======================================
Decorators in Python
======================================
=>Decorator is one of the Function which will provides Additional
Processing capability to the normal Function value and returns the
modified value.

Syntax:-

def functionname1( functionname ): # Decorator


def innerfunctionname():
val=functionname()

#do the operationon ' val '

return resut # Inner Funtion must return


modified value
return innerfunctionname # Decorator returns inner
function name
=>here functionname1 is called Decorator function
=>here Functionname as a formal parameter . Every decorator function
must take normal function as parameter.

#non-dec.py
def getval(): # Normal Function
return (float(input("Enter Value of n:")))

def sqrtvalue() : # Normal Function


n=getval()
return (n**0.5)

#main program

res=sqrtvalue()
print("Square Root=",res)

#dec1.py
def getval(): # Normal Function
return (float(input("Enter Value of n:")))

def sqrtvalue(kvr ): # Decorator


def processvalue():
n=kvr()
res=n**0.5
return res
return processvalue

#main program
hyd=sqrtvalue( getval)
result=hyd()
print("Result=",result)

#dec2.py
def getval(): # Normal Function

416
return (float(input("Enter Value of n:")))

def sqrtvalue(kvr ): # Decorator


def processvalue():
n=kvr()
res=n**0.5
return res
return processvalue

#main program
hyd=sqrtvalue( getval)
print("Result=",hyd())

#dec3.py

def sqrtvalue(kvr ): # Decorator


def processvalue():
n=kvr()
res=n**0.5
return res
return processvalue

@sqrtvalue
def getval(): # Normal Function
return (float(input("Enter Value of n:")))

#main program
print("Result=",getval())

#dec4.py

def cube(hyd):
def calculate():
n=hyd()
res=n**3
return res
return calculate

@cube
def getn():
return float(input("Enter Value:"))

#main program
print("Cube=",getn())

#dec5.py
def cube(hyd):
def calculate():
n=hyd()
res=n**3
return res
return calculate
def sqr(kvr): # Decorator

417
def processval():
n=kvr()
res=n**2
return res
return processval

@sqr
@cube
def getn():
return float(input("Enter Value:"))

#main program
print("SquareValue=",getn())

========================
Iterators in Python
========================

Why should WE use Iterators:

=>In modern days, we have a lot of data in our hands, and handling this
huge amount of data creates problems for everyone who wants to do some
sort of analysis with that data.So, If you‟ve ever struggled with
handling huge amounts of data, and your machine running out of memory,
then WE use the concept of Iterators in Python.
=>Therefore, Rather than putting all the data in the memory in one
step, it would be better if we could work with it in bits or some small
chunks, dealing with only that data that is required at that moment. As
a result, this would reduce the load on our computer memory
tremendously. And this is what exactly the iterators do.
=>Therefore, you can use Iterators to save a ton of memory, as
Iterators don‟t compute their items when they are generated, but only
when they are called upon.

=>Iterator in python is an object that is used to iterate over iterable


objects like lists, tuples, dicts, and sets.
=>The iterator object is initialized using the iter() method. It uses
the next() method for iteration.
=>Here iter() is used for converting Iterable object into Iterator
object.
=>next() is used for obtaining next element of iterator object and if
no next element then we get an exception called StopIteration.

Examples:

s = 'Python'
itobj = iter(s)
while True:
try:
item = next(s) # Iterate by calling next
print(item)
except StopIteration: # exception will happen when
iteration will over

418
break
======================================================
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
=======================================================

#IterEx1.py
import sys
lst=[10,20,30,40,50,60,70,80,90] # Iterable Object
print("Size of lst=",sys.getsizeof(lst))
for val in lst:
print("\t",val)
print(" ")
itlst=iter(lst) # Here itlst is an object of <class,
"list_Iterator">
print(type(itlst), sys.getsizeof(itlst))
while(True):
try:
print(next(itlst))
except StopIteration:
break

#IterEx2.py
import sys
tpl=(10,20,30,40,50,60,70,80,90,"python") # Iterable Object
print("Tuple Values")
print("Size of lst=",sys.getsizeof(tpl))
for val in tpl:
print("\t",val)
print(" ")
itlst=iter(tpl) # Here itlst is an object of <class,
"tuple_Iterator">
print("Iterator Values")
print(type(itlst), sys.getsizeof(itlst))
while(True):
try:
print(next(itlst))
except StopIteration:
break

==============================================
Network Programming Python
==============================================
=>Purpose of Network Programming is that " To share the data between
multiple machines which available in network".
=>To develop any Networking Application, we need develop two types of
program. They are
1. Server Side Program

419
2. Client Side Program

Def. of Server Side Program:

=>Server Side Program is one, which receives the request the from
Client Side Program, Process and gives Response Back Client Side
Program.

Def. of Client Side Program:

=> Client Side Program is one, which always makes a request to the the
Server Side Program, Process and obtains result from Server Side
Program.

Def. of Portno:

=>A Port Number is one the logical Numerical ID, where Server Side
Program is running.
Hence DNSor IP Address Gives in which machine Server Side Program
Reside and Portno gives Running Location( DNS/IP Address, portno)

================================================================
Steps for Developing Server and Client Side Applications
================================================================

Steps for Developing Server Side Applications

1) import socket

420
2) Every Server Side Program Must starts and Bind with certain DNS and
Portno
3) Every Server Side Program Must be configuared in such way that to
how many clients it can
communicate.
4) Every Server Side Program must ACCEPT Client Side Program Request
5) Every Server Side Program must Read Requested Data and PROCESS
Client Side Program
request.
6) Every Server Side Program must gives Response Back to Client Side
Program

NOTE: As long as Client Side Program Makes a request, The Server Side
Program must Perform Ste-4, 5 and 6 .

Steps for Developing Client Side Applications

Step-1: import socket


Step-2: Every Client Side Program must get the connection From Server
Side Program by
passing (DNS/IP Address, portno)

Step-3: Every Client Side Program makes a request to Server Side


Program.
Step-4: Every Client Side Program must receive the response from Server
Side Program..

NOTE:

=>If client want to perform multiple requests and Responses , Client


Side Program must perform Step-3 and Step-4.
=====================================X=================================
===

===================================================
Module Name for developing Networking Applications
===================================================
=>For developing Networking Applications in python programming, we must
use a module called "socket".
=>socket module contains following Functions

1. socket()

=>This function is used creating an object socket


=>Syntax: varname=socket.scoket()
here varname is an object of socket class

Examples: s=socket.socket()

2.bind()

421
=>This Program is used for making the Server Side Program (socket
object) to reside and run at Certain Machine and Port Number.
=>Syntax: sockobj.bind( ( "DNS/IP Address",portno ) )
Example: s.bind(("localhost",8888)

3.listen()

=>This is function is used for making the Server Side Program to


communicate with how number of clients.
=>Syntax: sockobj.listen(number of clients)
=>Examples: s.listen(2)

4.accept()

=>This program is used for accepting the client Request and Server Side
Program got connected with Client Side Program.
Syntax:- var1,var2=sockobj.accept()
=>Here Var1 represent Client Side Socket object and Var2 represents
address of client.
Examples: CSobj,CSaddr=sockobj.accept()

5.recv() with decode()

=>This Function is used for Receving Client Program request at Server


Side Program and it can also be used at Cliet Side Program to receive
Server Side Program response.
=>Syntax:- varname=CSobj.recv(1024/2048/4096).decode()

6.send() with encode()

=>This Function is used for sending the request from Client Side to
Server Side Program and also sending response from server side program
client side program.
=>Syntax:- CSobj.send(str(anyval).encode())

7.connect()

=>This Function is used for obtaining the connection from server side
program by client side program.
Syntax:- socketobj.connect(("DNS/IP Address",portno) )
Examples: sockobj.connect( ("localhost/127.0.0.1",8888))

#ClientProg1.py
import socket
s=socket.socket()
s.connect(("localhost",8888))

422
print("CSP got connection from SSP")
s.send("Hello Server, I am from Client Side:".encode())

#ServerProg1.py
import socket
s=socket.socket()
s.bind(("localhost",8888))
s.listen(2)
print("SSP is ready to accept any request of CSP")
while(True):
csobj,caddr=s.accept()
csdata=csobj.recv(1024).decode() print("\
nClient Data at Server=",csdata)

#This program reads values from KBD and send to Server Side Program for
obtaining its square
#ClientSquare.py
import socket
while(True):
s=socket.socket()
s.connect(("localhost",8558))
print("CSP got connection from SSP")
n=input("Enter Value:")
s.send(n.encode())
res=s.recv(1024).decode()
print("Server Data at Client=",res)
ch=input("Do u want to Continue(yes/no):")
if(ch=="no"):
break

#Server Side Program for accepting client side value and square it send
result to client
#ServerSquare.py
import socket
s=socket.socket()
s.bind(("localhost",8558))
s.listen(2)
print("SSP is ready to accept any request of CSP")
while(True):
csobj,caddr=s.accept()
csdata=float(csobj.recv(1024).decode())
print("\nClient Data at Server=",csdata)
res=csdata**2 # Process client Data
csobj.send(str(res).encode())

#This Program considered as Client Side Program, It Sends the Messages


Server Side Program and gets Answer as Response by client side Program
from server side program
#ChatClient.py-----Program-(B)
import socket,sys
while(True):
s=socket.socket()
s.connect( ("localhost",9999) )
csdata=input("Student-->")

423
if(csdata.lower()=="bye") :
s.send("Bye KVR, I have some work!".encode())
sys.exit()
else:
s.send(csdata.encode())
ssdata=s.recv(1024).decode()
print("KVR-->{}".format(ssdata))

#This Program considered as Server Side Program, It receives the


Messages from Client Side Program and Gives Answer as Response to
client side Program
#ChatServer.py-----Program-(A)
import socket
s=socket.socket()
s.bind( ("localhost",9999) )
s.listen(1)
print("Sever Side Program is ready to accept any request of client:")
print("-"*40)
while(True):
cs,addr=s.accept()
csdata=cs.recv(1024).decode()
print("Student Msg-->{}".format(csdata))
sdata=input("KVR-->")
cs.send(sdata.encode())

#write a client side program which will accept employee no.from


keyboard,send to the server and get employee name,salary and
disignation from server side program.
#ClientEmpData.py
import socket
s=socket.socket()
s.connect(("127.0.0.1",3600))
print("CSP got Connection From SSP:")
empno=input("Enter Employee Number:")
s.send(empno.encode())
sdata=s.recv(1024).decode()
print(" ")
print("Result from Server about Employee:")
print(" ")
print(sdata)
print("

# Write a server side program which will accept employee number from
client, retrieve empname, salary and designation from emp table.
#ServerEmpData.py-----------Program-(A)
import socket
import cx_Oracle
s=socket.socket()
s.bind(("127.0.0.1",3600))
s.listen(2)
print("SSP is Ready to accept CSP request:")
while(True):
try:
cs,ca=s.accept()
eno=int(cs.recv(1024).decode())

424
#PDBC CODE
oracon=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("SSP connectd to Oracle DB")
cur=oracon.cursor()
cur.execute("select ename,sal,cname from employee where
eno=%d" %eno)
record=cur.fetchone()
if(record==None):
cs.send("Employee Record Does not
Exist".encode())
else:
cs.send(str(record).encode())
except ValueError:
cs.send("Don't enter strs,Symbols and alph-numerics for
empno".encode() )
except cx_Oracle.DatabaseError as db:
cs.send("Prob in DB"+str(db).encode())
except :
cs.send("OOOOPs Some went wrong".encode())

#Server Side Program for accepting client side value and square it send
result to client
#ServerSquare.py
import socket
s=socket.socket()
s.bind(("localhost",8558))
s.listen(2)
print("SSP is ready to accept any request of CSP")
while(True):
try:
csobj,caddr=s.accept()
csdata=float(csobj.recv(1024).decode())
print("\nClient Data at Server=",csdata)
res=csdata**2 # Process client Data
csobj.send(str(res).encode())
except ValueError:
csobj.send("Don't Send Strs symbols and alpha-
numerics".encode())

< Thank you >

425

You might also like