Python New
Python New
1
<PYTHON>
===============================================
Real Time Applications of Python
===============================================
=>With Programming, we can develop 22+ Real Time Applications
===========================================
Getting started with Python
===========================================
=>History of Python
=>Versions of Python
=>Downloading Process of Python
=============================================================
=>History of Python
=>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
============================================
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
=======================================
2. Freeware and Open Source
=======================================
Freeware:-
Open Source:
4
=>Some of Python Distributions are
=======================================
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
Examples: PYTHON
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.
=>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.
Example : Python
=================================x==================================
============================================
7. Robust (Strong )
============================================
=>Python is one of the Robust Programming language bcoz of Python
provides
" Exception Handling " Facility.
NOTE:
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:
===================================
9. Extensible
===================================
===================================
10. Embedded
===================================
=>Python Programming can call other languages coding segments for
fastest execution
=========================================================
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:
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.
Def. of Variable:
================================================================
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.
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.
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:
>>> 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.
>>> a=0b1111
13
>>> print(a) 15
>>> a=0B1101
>>> print(a, type(a))------------13 <class 'int'>
>>> a=0b100
>>> print(a, type(a))------------4 <class 'int'>
Examples:
>>> a=0o22
>>> print(a, type(a))----------------18 <class 'int'>
>>> a=0o34
>>> print(a, type(a))-------------- 28 <class 'int'>
>>> a=0o123
>>> print(a) 83
>>> 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
=============================================
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:
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
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
>>> 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:
=>Single Line String Data must enclosed with Single or Double Quotes.
=>Syntax:-
strobj =" Single Line String Data "
(OR)
strobj = ' Single Line String Data '
Examples:
=>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:
18
String data-n " " "
(OR)
Examples:
>>> print(s3,type(s3))----
GUIDO VAN ROSSUM
HNO:3-4 red sea side
Python software Foundation
Nether Lands-51
<class 'str'>
>>> print(s4,type(s4))
Dennis Ritche
34-56 Hill Side
Bell Labs
United States-67
<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
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:
=>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 : ]
strobj[ : End ]
strobj[ : ]
strobj[ Begin : End : Step ]-----5 rules
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
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
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."
>>> 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'>
>>> 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'>
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:
=====================================
2) float()
=====================================
=>float() is used for converting "One Type of Possible Value into
float Value."
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'>
>>> 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:
==============================================
3) bool()
==============================================
=>bool() is used for converting "One Type of Possible Value into bool
Value."
Examples:
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:
Examples:
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."
28
>>> a=123
>>> print(a,type(a))----------------123 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))--------------(123+0j) <class 'complex'>
>>> a=10.5
>>> print(a,type(a))--------------10.5 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))----------(10.5+0j) <class 'complex'>
>>> 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."
>>> 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:
==============================================
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.
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)
Syntax-2 range(start,stop)
>>> 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)
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
35
4
5
6
7
8
9
36
Q5)Generate 1000 1005 1010 1015 1020-------------
range(1000,1021,5)
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
Q3) 10 9 8 7 6 5 4 3 2 1
Q4) -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
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()
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():
>>> 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
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
=>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]
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
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():
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():
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:
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:
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
>>> 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 ]
Examples:
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]
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():
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:
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()
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)
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
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()
dictobj[Key1]=Value1
dictobj[Key2]=Value2
dictobj[Key-n]=Value-n
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:
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:
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:
4) popitem()
59
=>Syntax:- dictobj.popitem()
=>This function is used for removing last (key,value) entry from dict
obj.
=>Examples:
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:
>>> 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:
61
8)items():
=>Syntax:- dictobj.items()
=>This Function gives set of (Key,Value)
Examples:
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
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)
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:
b) Batch Mode:
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
=======================================================
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:
>>> 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
>>> 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
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:
(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:
(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)
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)
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)
===========================================
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 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 *
==================================================
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
=>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
Var1,Var2.....Var-n= Expr1,Expr2...Expr-n
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
3. == Equality
===================================================
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:
=================================================
Rel Expr1 Rel Expr2 RelExpr1 and RelExpr2
=================================================
True False False
False True False
False False False
True True True
=================================================
Examples:-
2) 'or' Operator:
=================================================
Rel Expr1 Rel Expr2 RelExpr1 or RelExpr2
=================================================
75
True False True
False True True
False False False
True True True
=================================================
Examples:
=================================================
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.
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
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 ( | ):
=============================
Var1 Var2 Var1 | Var2
=============================
0 1 1
1 0 1
0 0 0
1 1 1
=============================
Example:-
>>> print(4|3) 7
>>> print(15|3)--------------15
>>>print(10|15)------------15
>>> 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 ( & ):
Examples:
>>>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 ( ^ ):
Examples:
>>>a=4 >0100
>>>b=5 > 0101
-
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:
b) not in:
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)
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
-
2) is not
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():
Examples:
2) title():
3) find():
Examples:
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():
=>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() :
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() :
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:
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:
12) join():
>>> 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:
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
============================================
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
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:
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
Explanation:
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:
case label-n:
block of statements-n
case _ : # default case block
default block of statements
100
Explanation:
=======================================================================
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
104
==========================================
for loop or for else concept
==========================================
Syntax1:
statement-1
statement-2
statement-n
======================================================
Syntax2:
statement-1
statement-2
statement-n
else:
else block of statements
Explanation:
===============================================================
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)
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
"""
109
cs=cs+i**3
i=i+1
else:
print("="*50) print("\t{}\t\t{}\t\
t{}".format(s,ss,cs)) print("="*50)
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(" ")
111
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*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
=>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:-
if ( Test Cond):
continue
statement-1 # written after continue
stateemnt
statement-2
statement-n
=>Syntax:-
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(" ")
#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:
else:
else:
--
***********************************************************************
*************************************
Syntax2:
else:
else:
***********************************************************************
*************************************
Syntax3:
else:
else:
117
***********************************************************************
**************************************
Syntax4:
for varnam1 in IterableObj1: # outer for 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")
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")
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
===============================================
Types of Languages in the context of Functions
===============================================
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
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:
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.
#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
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]))
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:
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.
=======================================================================
127
print("-"*50)
print("Type of obj=",type(obj))
for val in obj:
print("\t{}".format(val))
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)))
#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:
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)
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)
====================================----------------------------------------------------------------
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]
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)))
#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))
#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.
def functionname(parm1,param2.....param-n):
functionname(arg1,arg2....arg-n)
======================================
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)
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
#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)
#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.
def functionname(param1,param2...param-n):
functionname(param-n=val-n,param1=val1,param-n-1=val-n-1,......)
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)
#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'>.
=>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'>
#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)
#purevarargsex1.py
#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
#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()
==============================================
#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(" ")
#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
=======================================================
#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'>.
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'>
Final Syntax:
--
==============================X=======================================
#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)
#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)
#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
#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
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
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
================================================
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'>.
Final Syntax:
--
==============================X=======================================
#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)
#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--
#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
#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
#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
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
147
#purekwdvarlegargsex5.py
==================================================
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
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:
#main program
operation()
====================================X==================================
==
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.
Explanation:
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
#AnonymousFunex2.py
#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
#main program
res=findbig(100,20)
print("Result=",res)
print(" ")
res=big(1000,2000)
print("Result=",res)
#AnonymousFunex4.py
#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
#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():
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.
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
#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
=============================================================
#FilterEx4.py
def uppercase(s):
return s.isupper()
def lowercase(s):
return s.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
lowercase=lambda s: s.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)
#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)
=======================================================================
#main program
lst=[2,3,5,-4,-6,4,8]
sqlist=tuple(map(square,lst))
print("Original List=",lst)
print("Square list=",sqlist)
164
=======================================================================
=======================================================================
#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))
=======================================================================
=======================================================================
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)
=======================================================================
=======================================================================
#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".
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 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)
=====================================================================
=====================================================================
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:
=>Types of Modules:
168
2) Programmer or user or custom-defined modules.
=================================================
Development of Programmer-Defined Module
=================================================
=>To develop Programmer-Defined Modules, we must use the following
steps
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
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.
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.
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
=======================================================================
#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")
==================================================================
174
print("sum({},{})={}".format(a,b,c))
=======================================================================
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)
=======================================================================
=======================================================================
=======================================================================
#m1m2.py----main program
import m2 ,m1
print("Subject=",m1.subject)
print("Subject=",m2.subject)
print(" ")
m1.hello("Rossum")
m2.hello("Travis")
=======================================================================
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:
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)
====================================================================
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)
=======================================================================
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.
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:
Example:
bank <-----Package Name
=>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
Syntax:
----------- sys.path.append("Absolute Path of Package")
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")
-
=>PYTHONPATH is one of the Enviromental Variable
=>Search for Enviromental Variable
Steps for setting :
180
Var Value : E:\KVR-PYTHON-7AM\PACKAGES\BANK
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()
Syntax-2: random.rangerange(start,stop)
This syntax generates any random value between start to
stop-1
Examples:
#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:
#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:
#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():
Syntax:- random.shuffle(list)
=>We can shuffle the data of list but not other objects of Data Types
Examples:
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:
#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
187
===================================================
Exception Handling
===================================================
=>The purpose of Exception Handling is that "To Build Robust
(Strong) Applications".
2. Logical Errors
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.
===============================================
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.
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.
===============================================
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
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.
a=int(s1) #
b=int(s2)
c=a/b
print("Val of a=",a)
print("Val of
b=",b)
print("Div=",c)
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
=====================================================
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.,
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.
try:
Block of
statements
generating
exceptions
except <exception-class-name-1> as alias
name: print(alias name)
try:
Block of
statements
generating
exceptions
except : # default except block and written at
last block of stmts
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")
=======================================================================
=======================================================================
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")
=======================================================================
=======================================================================
==============================================================
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.
203
1) Development of programmer-defined exception class
204
#vspark.py----File Name and acts as Module Name (3)
# (1) (2)
class vsparkDivisionError(Exception):pass
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
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
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)
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.
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
=>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.
=================================================
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:
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:
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
219
3. a:
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+
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()
Explanation:
Syntax:-
with open("FileName","File Mode") as VarName:
Explanation:
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.
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():
2) writelines():
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)
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")
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")
#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
228
save or write entire object data of main memory into the file of
secondary memory.
=>Definition of Pickling:
Un-Pickling
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()
=======================================================================
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
Example:
2) create a folder :
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:
Examples:
4) remove a folder :
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")
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 :
Examples:
#renamedirex.py
import os
try:
os.rename("c:\\mango","c:\\india")
print("Folder renamed successfully--verify")
except FileNotFoundError:
print("Folders does not exists")
Examples:
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")
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")
================================================
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
=>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()
235
csvwriterobj.writerows(data rows)
here data rows can be list tuple set,frozenset only
1) writeheader():
writeheader() method simply writes the first row of your csv file
using the pre-specified fieldnames.
Syntax: DictWriterObj.writeheader()
2) writerows():
=>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():
2) csv.DictReader():
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()
237
# data record of csv file
row = ['KVR', 'CSE', '2', '9.0']
# field names
csvfields = ['name', 'branch', 'year', 'cgpa']
#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.
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.
================================================================
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
Explanation:
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
Explanation:
=>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")
241
ORCL <---------------Service id
=>When we use / write Invalid Connection URL then we get
cx_Oracle.DatabaseError as an exception and must handle.
4. Python program must Prepare the Query and Execute the Query in
Oracle DB
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
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)
#main program
tablecreate()
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()
#main program
alteroperation()
==============================================
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:
2. alter :
=>This Query is used for alter the table structure such as modifying
(modify) the column sizes and adding (add) new columns.
Syntax2:- SQL> alter table <table-name> add ( new col name1 database
data type....
new col name-n database data type )
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:
#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")
#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.
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)
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")
#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)
#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
==========================================================
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.
=>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:
====================================================
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):
@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.
=>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
=>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
#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(" ")
#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(" ")
=======================================================================
#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(" ")
#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(" ")
#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
objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()
=>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):
=>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"
#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
#main program
s1=Student() # Object creation
s2=Student() # Object creation
print("First Student Details")
s1.readstuddata() # Method Call
print("Second Student Details")
s2.readstuddata()
264
self.marks=float(input("Enter Student Marks:"))
print(" ")
#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
265
cls.addr="IBM-HYD"
#main program
Student.getcourse() # Calling Class Level Method
Student.getcompaddress() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"
#main program
Student.getcourse() # Calling Class Level Method
266
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"
#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"
267
self.marks=float(input("Enter Student Marks:"))
print(" ")
#main program
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"
#main program
268
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
=================================================
Types of Methods in class of Python
=================================================
1) Instance Methods
269
objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()
=>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):
=>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"
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):
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)
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:
varname=classname()
so=Student()
Example:- create an object Employee
eo=Employee()
273
Differences Betwwen Classes and Objects
Class:
Objects:
#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 :
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
Definition:
=>Syntax:
====================================================================
2. Parameterized Constructor
Definition:
=>Syntax:
======================================================================
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))
=====================================================
#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
=====================================================
=====================================================
#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.
281
=>Syntax:
=======================================================================
Garbage Collector
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)
#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)
#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)
#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)
#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)
#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)
#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
==========================================================
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.
=>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:
288
====================================================
Syntax for defining a class in Python
====================================================
class <clsname>:
Class Level Data Members
def instancemethodname(self,list of formal params if
any):
@classmethod
def classlevelmethod(cls,,list of formal params if any):
@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.
=>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
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
#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(" ")
=======================================================================
#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(" ")
#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(" ")
#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
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()
=>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):
=>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"
295
3) Static Method-----Tomorrow class
#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
296
self.dispstuddata() # calling Instance Method
#main program
s1=Student() # Object creation
s2=Student() # Object creation
print("First Student Details")
s1.readstuddata() # Method Call
print("Second Student Details")
s2.readstuddata()
#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
297
self.stno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
print(" ")
#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
#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"
#main program
Student.getcourse() # Calling Class Level Method
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"
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()
@classmethod
def getcompaddress(cls):
cls.addr="IBM-HYD"
#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"
#main program
s1=Student() # Object creation
s1.readstuddata()
s1.dispstuddata()
301
=================================================
Types of Methods in class of Python
=================================================
1) Instance Methods
objectname.InstanceMethodName()
(OR)
self.InstanceMethodName()
=>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"
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):
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:
varname=classname()
so=Student()
Example:- create an object Employee
eo=Employee()
Class:
Objects:
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 :
===================================================
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
Definition:
=>Syntax:
309
def init (self):
====================================================================
2. Parameterized Constructor
Definition:
=>Syntax:
======================================================================
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))
=====================================================
#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
=====================================================
=====================================================
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.
=>Syntax:
=======================================================================
Garbage Collector
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)
#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)
#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)
#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)
#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)
#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)
#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:
(OR)
Syntax1:- class
<ClassName>:
def init (self):
319
self. Data
MemberName1=Value1
self. Data
MemberName2=Value2
self.Data MemberName-
n=Value-n
Example1:
Example2:
==============================================================
Data Abstraction:
Example1:
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:
==========================================================
#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"
==========================================================
===========================================================
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:
Advatnages of Inheritance:
====================================
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
==============================================================
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}
=============================================================
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()
=============================================================
=============================================================
326
self.dispunivdet()
print("-"*50)
print("College Details:")
print("-"*50)
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-"*50)
=============================================================
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:
===========================================
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()
#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():
=>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.
=>By using ClassName approach, we can call any base class method /
constructor name from the context of derived class method / constructor
names.
#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".
=================================================
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():
2) group():
3) start():
4) end():
5) search():
=>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'>
#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:")
"""
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
==================================================
"""
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
================================================== """
"""\
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
=================================================="""
"""
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
==================================================
"""
"""
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:!
==================================================
"""
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
==================================================
"""
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
==================================================
"""
"””
==================================================
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:!
==================================================
"""
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"
"""
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
==================================================
"""
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:!
==================================================
"""
"""
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
==================================================
"""
"""
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
==================================================
"""
"""
E:\KVR-PYTHON-7AM\REGEX>py RegExpr25.py
==================================================
Start Index:5 End Index:6 Value:
Start Index:10 End Index:11 Value:
==================================================
"""
"""
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
=================================================="""
==============================================================
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 ]"
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
=========================================
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.
Note:
==>\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.
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
==================================================
"""
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:")
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
==========================================
Introduction to Numpy
==========================================
Introduction to 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:
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:
=================================================
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:
>>> 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)
[[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>
Examples:
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)
Examples:
[[0, 0],
[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]]])
[[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:
[[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()
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()
Examples:
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():
Examples:
a) add():
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()
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]])
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]])
d) dot()
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.]])
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]])
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]],
===========================================
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():
=>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():
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()
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():
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:
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.
Examples:
>>> a=np.array([10,20,30,40,50,60])
>>> a
array([10, 20, 30, 40, 50, 60])
>>> a[0]
10
>>> a[3]
40
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.
=>Syntax:- ndarrayname [ x ]
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]
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]]
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)
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
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]
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:
[[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.
380
Example
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]
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])
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,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:
=>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.
Approach-2:
382
=>In this approach, we directly pass Boolean array values to the
ndarray for getting required elements based on condition.
Examples:
>>> 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:
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:
---
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
385
Explanation:-
>>> 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'>
>>> 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'>
Examples:
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:
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
Examples:
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
>>> 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
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
=======================================================
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"]
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]
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,
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.
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.
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.
DataFrame.groupby() method
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.
394
# Iterate over all the groups
for grpName, rows in df.groupby('City'):
print("Group Name: ", grpName)
print('Group Content: ')
print(rows)
Output:
=>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.
For example
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.
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.
Output:
396
19 Samir 42 Mumbai 15
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.
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.
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,
Output:
Delhi 4
Mumbai 3
Sydney 3
dtype: int64
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.
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.
400
=>Thread Based Applications are treated as Light Weight Applications.
=========================================
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:
=>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)
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():
2) active_count():
=>This Function is used for counting number threads which are running
Syntax: varname=threading.active_count()
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"
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()
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
404
2. By Using Object Oriented Approach
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
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)
#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
#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():
2) active_count():
=>This Function is used for counting number threads which are running
Syntax: varname=threading.active_count()
2) setName(str) or name
409
(OR)
Syntax: childthreadobj . name=str
Examples: t1.setName("Rossum")
or
t1.name="Rossum"
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()
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()
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.
lockobj.release()
#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:-
#non-dec.py
def getval(): # Normal Function
return (float(input("Enter Value of n:")))
#main program
res=sqrtvalue()
print("Square Root=",res)
#dec1.py
def getval(): # Normal Function
return (float(input("Enter Value of n:")))
#main program
hyd=sqrtvalue( getval)
result=hyd()
print("Result=",result)
#dec2.py
def getval(): # Normal Function
416
return (float(input("Enter Value of n:")))
#main program
hyd=sqrtvalue( getval)
print("Result=",hyd())
#dec3.py
@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
========================
=>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.
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
=>Server Side Program is one, which receives the request the from
Client Side Program, Process and gives Response Back 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
================================================================
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 .
NOTE:
===================================================
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()
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()
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()
=>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())
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))
# 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())
425