PYTHON Programming 1
PYTHON Programming 1
By KVR sir
EDIT BY NAVEEN.E
HYDERABAD
1
====================================================================
PYTHON Programming
with NUMPY and PANDAS ---->Data Science /AI / ML / DL
====================================================================
Real time Applications of Python Programming
====================================================================
1. Web Application Development
2. Gaming Application Development
3. Artificial Intelligence and Machine Learning , Deep Learning , Data Science
4. Desktop GUI Applications
5. Image Processing
6. Text Processing
7. Business Applications
8. Education Programs and Training Programs.
9. Audio and Video Based Application
10.Web Scrapping / Web Harvesting Application.
11. Data Visualization in Data Science
12. Scientific and Numerical Operation
13. Software Development
14. Operating Development
15. CAD Based Application
16. Embedded Application
17. Console based Applications.
18. Computer Vision
19. Language Development
20. Automation of Testing
21. Animation applications
22. Data Analysis and Data Analytics
23. Development of IOT
=====================================================================
Python Programming Inspired From
=====================================================
=>The Python Programming Inspired From 4 languages.
1) Python Programming Inspired From C Language<-----Functional Programming
2) Python Programming Inspired From CPP Language<---Object Oriented Principles
3) Python Programming Inspired From PERL Language<---Scripting Principles4)
Python Programming Inspired From MODULO3 Language<--Modular Programming
Principles
2
=========================================
Features of Python
=========================================
=>Features of any language are nothing but services (or) facilities by Lang
developers and those features used by Language programmers for developing Real
Time Applications.
=>Python Programming The following features.
1. Simple
2. Freeware and Open Source
3. Dynamically Typed Programming
4. Platform Independent and Portable
5. Interpreted
6.High Level
7.Both Procedural (Functional) and Object oriented Prog lang.
8. Robust(Strong)
9. Extensible
10.Embedded
11. Supports Extensive Third Party APIs( Numpy,Pandas,
matplotlib,scipy,scikit....)
---------------------------------------------------------------------------------------------------------------
1) Simple:
----------------
=>Python is one of the simple programming bcoz of 3 important tech factors.
a) Python Programming Provides Rich set Of APIs. So that Python Programmer can
re-use the pre-defined code without writing our code
=>Definition of API (Application Programming Interface):-
--------------------------------------------------------------------------
=>An API is a collection MODULES.
=>A MODULE is a collection Variables, Functions and Classes
b) Python programming Provides In-Built Garbage Collection facility to collect
un-Used memory space to it improves the performance of Python Based Application.
=>Def. Of Garbage Collector:
-----------------------------------------
=>A Garbage Collector is one of In-Built python background Program running behind
of every python program whose purpose is to collect Un-used memory space and
improves performance of Python based Applications.
=>Open Source:
-----------------------
=>Some Companies came forward and customized CPYTHON and they are using
as inhouse tools and Customized versions of CPYTHON are called "Distributions of
PYTHON"
=>Some of the "Distributions of PYTHON" are
1) Jpython (or) Jython------>Used to execute Java Based Applications
2) Micro Python ---------->used to develop Micro Controller Applications
3) Iron Python--------->Used To run C#.net Applications
4) Ankonda Python--->Used to run Hadoop / Big data Applications
5) Stackless python --->used for developing Concurrency Applications
6) Pypy---Provides JIT compiler
7) Ruby Python----Used to run Ruby based Applications....etc
=============================================================
4. Platform Independent and Portable:
------------------------------------------------------
=>In Python programming all value are treated as "objects" and objects can store
un-limited number of values and they can run and same on all types of OSes. and
hence Python language is considered as " Platform Independent "
Examples:
----------------
Platform dependent Lang:---> C,CPP,...etc, bcoz data type of C,CPP are
containing specific memory space can change from OS to another OS.
Platform Independent:→ Java data types takes same memory space on all OSes
but can store only smaller values and Fixed number of values
--------------
portable:
--------------
Portable applications / projects are those which are running on every OS with
considering Their vendors.
Example: Python and Java projects are portable
=> Dynamically Typed Programming , It is not necessary to specify the data type and
data type of the variable is decided by python environment and data type is
assigned.
Example: Python
4
=>In Python Programming all the values are stored in the form of objects and behind
the objects we have classes.
>>>a=10 # here 'a' is an object <class, 'int'>
>>b=12.34 # here 'a' is an object <class, 'float'>
>>>print(a, type(a))---------> 10 <class, 'int'>
>>>print(b, type(b))---------> 12.34 <class, 'float'>
================================================================
5. Interpreted :
-----------------------
In python Programming, when we RUN the python program, Internally Python
Compiler reads line by line of Source Code and Converted into Byte Code
(Intermediate Code Python Lang) and PVM execute the python program by reading
line of byte code and converted into Machine Understandable Code (Binary Format
or executable code ) and It read by OS and Processor and Gives Result.
=>Hence During compilation and execution and line by Line operation has performed
and Python is one of the Interpreted Programming lang.
================================================================
6.High Level
-------------------------
=>Writing the program in python is nothing but writing like English statements.
================================================================
8. Robust(Strong)
-----------------------------
=>Since Python Programming Provides a Programming Feature called "Exceptional
Handling" and python based Applications are called "Robust"
Exception Handling:
-------------------------------
The Process of converting technical error messages into user-friendly error
messages is called Exception Handling.
========================================================
9. Extensible 10.Embedded:
---------------------------------------------------
=>Python programming services can be used in other languages and it is called
extensible programming Language.
=>Python programming can also other languge serivices and Python is one of the
embedded programming lang.
===============================================================
11. Supports Extensive Third Party APIs( Numpy,Pandas,
matplotlib,scipy,scikit....)
=>Python use Third pary APIs for cal complex math calculations , analysis and
analystics and generating graphs.
5
===================================================
Introduction to Python Programming
===================================================
History Of Python:
---------------------------
=>The Python Programming Language foundation done in the late 1980
=>The implementation of Python Programming Language was started in December 1989
=>The Python(0.9) Programming Language officially released in the year 1991 Feb 20.
=>The Python Programming Language Developed by " GUIDO VAN ROSSUM ".
=>The ABC Programming Language is the predecessor of Python Programming Language.
=>There is fact behind choosing the name python is that there is a popular BBC comedy
series "Monty python's Flying Circus---late 1970"
---------------------------------
Python Versions:
---------------------------------
=> Python Programming Language contains Two Types of Versions. They are
1) Python 2.x here x ---> 0, 1,2,3............
=>The Python3.x does not support Python 2.x. Hence Python 3.x does not contain
backward compatibility.
==================================================
Importance of Literals and Variables (OR ) identifiers
==================================================
Literals:
-------------
=>All the values , which we are giving to the program as an input are called Literals.
=>In any programming lang, we have 4 types of literals (values). They are
a) Integer Literals
b) float Literals
c) String / Character Literals
d) Boolean Literals
----------------------------------------------------------------------------------------------------------------
Variables (OR ) identifiers
-----------------------------------------
=>All Literals (inputs) stored in main memory by allocating sufficient memory space.
=>To Process the inputs of our program, as programmer , we must distinct names to
the created memory space for identifying the values. Hence distinct names are
called "Identifiers".
=>During the program execution, identifier values can be changed and
hence Identifiers are also called "Variables"
6
Def of Variables:
--------------------------
=>A variable is one of the identifier, whose value can be changed during
execution of the program.
=>Without variables , we can't store the data.
------------------------------------------------------------------------------------------------
--------------------------------
Rules for using Variables in Python program
----------------------------------------------------------------------
Example:-
sal=12.34------valid
_sal=23.45-----valid
1sal=1.2----invalid
$sal=2.3----invalid
3) Within the variable Name, special symbols are not allowed except
under score.
Example:- emp_sal=2.3----valid
emp#sal=3.4---invalid
_$=3.4---------invalid
_s=2.3--------valid
emp sal=2.3------invalid
>>> age=18--------------valid
>>> AGE=20------------valid
>>> Age=22------------valid
>>> aGe=24--------------valid
>>> agE=26------------valid
7
>>>Ag_e=12---------valid
>>>ag@e=34--------invalid
Example:
>>>salaryofanibmemployeeofhyd=23.45--> not recommended, bcoz it is length and
not user-friendly
(or)
===============================================
Data Types
===============================================
=>The purpose of Data Types is that to allocate memory space for input data .
=>Python Programming provides 14 data types and classified into 6 types .
They are
===========================================
I. Fundamental Data Types
===========================================
=>The purpose of Fundamental Data Types is that to store Single Value.
=>we have 4 data types in Fundamental Data Types. They are
1. int
2. float
3. bool
4. complex
============================================
1. int
============================================
=>'int' is one of the pre-defined class and it is treated as data type.
=>The purpose of int data type is to store Integral values / whole numbers (numbers
without decimal places) and we can also store All Number System data.
Example:
-------------
>>>a=100
>>>print(a)--------------------------100
>>>type(a)-------------------------<class,'int'>
>>>a=123
>>>print(a, type(a))---------------- 123 <class, 'int'>
-------------------------------------------------------------------------------------------------------
------
=>With int data type, we store all number system data.
>We have 4 types of number Systems.They are
a) Decimal Number System(default):
Digits:- 0,1,2,3,4,5,6,7,8,9-------- 10 digits
Base: - 10
b) Binary Number System :
Digits: 0 1----------- 2 digits
Base: 2
c) Octal Number System:
digits:- 0,1,2,3,4,5,6,7-------- 8 digits
Base: 8
d) Hexa Decimial Number System:
Digits: 0,1,2,3,4,5,6,7,8,9, A,B,C,D,E,F---- 16 digits
base: 16
-------------------------------------------------------------------------------------------
Storing Binary Number System data in Python Programming:
--------------------------------------------------------------------------------------------
=>To Store Binary Number System data in Python Programming, the binary data
must be proceeded with 0b (or) 0B
Examples:
---------------
>>>a=0b1010
>>>print(a, type(a))------------ 10 <class, 'int'>
>>>b=0B1111
>>>print(b, type(b))------------ 15 <class, 'int'>
>>>b=0B10000
>>>print(b, type(b))------------ 1b <class, 'int'>
Examples:
-----------------
>>>a=0xAB
>>>print(a, type(a))------------->171 <class, 'int'>
>>>a=0xBEE
>>>print(a, type(a))------------->3054 <class, 'int'>
10
11
=>Syntax:-
varname=oct( Decimal / Binary / Hexa Decimal Value)
=>here varname is of type <class 'str'>
Examples:
---------------
>>> a=18
>>> b=oct(a)
>>> print(b)---------------0o22
>>> print(type(b))----------<class 'str'>
>>> a=0b1111
>>> b=oct(a)
>>> print(b)--------------0o17
>>> a=0xAB
>>> b=oct(a)
>>> print(b)-------------0o253
>>> print(type(b))-------------<class 'str'>
-----------------------------------------------------------------------------------------
12
c) hex():
---------
=>This function is used for converting any number System value into Hexa
Decimal format.
=>Syntax:- varname=hex( Decimal / Binary / Octal Value)
=>here varname is of type <class 'str'>
Examples:
-----------------
>>> a=15
>>> b=hex(a)
>>> print(b)--------------0xf
>>> a=171
>>> b=hex(a)
>>> print(b)------------0xab
>>> a=0o253
>>> b=hex(a)
>>> print(b)-----------0xab
>>> a=0b1010
>>> b=hex(a)
>>> print(b)--------------0xa
>>> print(type(b))-------------<class 'str'>
============================================
2. float data type
============================================
=>'float' is one the pre-defined class and treated as Fundamental data type
=>This data type is used for storing Real Constant values (or) floating point values.
Math Example:- 23.45
here 23 is called Integer part
0.45 is called Decimal part
=>float data never allows us store Binary , Octal and Hexa Decimal Number System
values.
=>this data type can also be used for storing scientific data (mantissa e exponent)
Examples:
-----------------
>>> a=12.34
>>> print(a)-------------12.34
>>> print(type(a))--------<class 'float'>
>>> a=0.9999
>>> print(a)----------------0.9999
>>> print(type(a))-------------<class 'float'>
-------------------------------------------------------------
Special Examples:
--------------------------
>>> a=0b1010.0b1010-------->SyntaxError: invalid syntax
>>> a=0b1010.0o22----------SyntaxError: invalid syntax
>>> a=0xA.0xF---------------SyntaxError: invalid syntax
13
----------------------------------------------------------------------------
Scientific Notation Examples:
-----------------------------------------
>>> a=3e2
>>> print(type(a))-------------<class 'float'>
>>> print(a)----------300.0
>>> a=4e-2
>>> print(a,type(a))----------0.04 <class 'float'>
>>> a=34e-4
>>> print(a, type(a))------------0.0034 <class 'float'>
========================================================
=============================================
Complex data type
=============================================
=>'complex' is one of the pre-defined class and treated as fundamental data type.
=>The purpose of complex data type is to store complex data.
=>The general format of Complex Data Type is shown Bellow
Syntax1: a + bj
Syntax2: a - bj
=>here 'a' is called real part and b is called imaginary part and 'j' represents sqrt(-1)
=>By default , the values of real and imaginary are belongs to 'float'
=>To extract the real and imaginary values from complex object, we use two pre-
defined attributes / variables. They are
a) real
b) imag
Syntax: complexobj.real---->Gives real part of complex objectSyntax:
complexobj.imag---->Gives imaginary part of complex object
============
Examples:
============
>>> a=2+3j
>>> b=2-3j
>>> print(a, type(a))---------(2+3j) <class 'complex'>
>>> print(b, type(b))--------(2-3j) <class 'complex'>
>>> c=2.5+3.6j
>>> d=-3.4-6.7j
>>> print(c, type(c))-------------(2.5+3.6j) <class 'complex'>
>>> print(d, type(d))----------(-3.4-6.7j) <class 'complex'>
---------------------------------------------------------------------------
14
Examples:
--------------------
>>> a=2+3j
>>> print(a.real)-----------2.0
>>>
>>> print(a.imag)----------3.0
>>> a=-3.5+4j
>>> print(a.real, a.imag)------- -3.5 4.0
>>> a=-2.3-4.5j
>>> print(a.real, a.imag)-------- -2.3 -4.5
===============================================
Sequence Type Data Types
===============================================
=>The purpose of Sequence Type Data Types is that "To store Sequence of Values"
in single object.
=>In python , we have 4 data types in Sequence Type. They are
a) str
b) bytes
c) bytearray
d) range
================================================================
======================
str
======================
=>'str' is one of the pre-defined class and treated as sequence data type
=>The purpose of str is that to store String data
=>The string can be organized in two ways. They are
a) Single line string data
b) multi line string data
a) Single line string data:
-----------------------------------
Syntax: " single line string data"
(or)
Syntax: ' single line string data '
Examples::
>>> s1="PYTHON"
>>> print(s1)-------------PYTHON
>>> print(type(s1))--------------<class 'str'>
>>> s2='PYTHON'
>>> print(s2, type(s2))------------PYTHON <class 'str'>
>>> s3='K'
>>> print(s3, type(s3))---- K <class 'str'>
15
Note:- With double and single quotes we can organize single line string data but not
multiple string data.
>>> s4="Rossum -------------------SyntaxError: EOL while scanning string literal
----------------------------------------------------------------------------------------------------
b) multi line string data:
-----------------------------------
=>To organize multi line string data , we use tripple double quotes or tripple
single quotes.
Syntax:- " " " String data1
String data 2
-----------------
String data -n " " "
(OR)
=========================================
Operations on str data
=========================================
=>On str data, we can two types of operations. They are
a) Indexing
b) Slicing
---------------------------------------------------------------------------------
a) Indexing:
------------------
=>The process of obtaining particular character from given str object by passing
valid existing Index / Position ( +ve / -ve) is called Indexing
=>If we enter Invalid Index then we get IndexError
Syntax: strobj[index]
here Index can be either +ve or -ve
Examples:
----------------
>>> s="PYTHON"
>>> print(s)--------------------------PYTHON
>>> print(s[0])------------------P
>>> print(s[-6])---------------P
>>> print(s[5])---------------N
>>> print(s[-1])---------------N
>>> print(s[3])---------------H
>>> print(s[-3])--------------H
>>> print(s[10])----------IndexError: string index out of range
==============================================================
b) Slicing:
----------------
=>The process obtaining range of characters (or) sequence of characters (or) sub
string from Given String is called Slicing.
=>Syntax1:- strobj[start:stop]----------->start<stop
=>This syntax gives range of character from start Index to stop-1 index provided
start<stop otherwise we never get any output
------------------------
Examples:
------------------------
>>> s="PYTHON"
>>> print(s[0:4])--------------PYTH
>>> print(s[2:6])--------------THON
>>> print(s[3:6])---------------HON
>>> print(s[6:2])---------------no output bcoz 6 < 2 is false
17
=>Syntax2:- strobj[start:stop:step]----------->start<stop
-----------------------------
Basic Examples:
----------------------------
>>> s="PYTHON"
>>> print(s)
PYTHON
>>> print(s[1:5])
YTHO
>>> print(s[0:4])
PYTH
>>> s[0:6]
'PYTHON'
>>> s[0:6:2]
'PTO'
>>> s[0:6:3]
'PH'
>>> s[0:6:4]
'PO'
--------------------------------------------------------------------------------------
=>Syntax2:- strobj[start:stop:step]
Rules:
---------
1) here start and stop can be either +ve or -ve
2) if step Value is Positive then we must consider the elements from start to stop-1
in forward direction provided start<stop
3) if step Value is -negative then we must consider the elements from start to
stop+1 in backward direction provided start > stop
4) If we don't specify start value then PVM takes Init Index Value
5) If we don't specify stop value then PVM takes end Index Value( len(obj)-1 )
6) If we don't specify start value and stop value then PVM takes Init Index Value as
start and end Index Value( len(obj)-1 ) as stop value
18
Examples:
----------------
>>> s="PYTHON"
>>> s[0:6]---------------------------'PYTHON'
>>> s[:6]------------------'PYTHON'
>>> s[0:]------------------'PYTHON'
>>> s[:]------------------'PYTHON'
>>> s[::-1]---------------'NOHTYP'
>>> s="PYTHON PROGRAMMING LANG"
>>> s[::-1]------------------'GNAL GNIMMARGORP NOHTYP'
>>> s="PYTHON"
>>> len(s)---------------------6
>>> s="PYTHON"----------------
>>> s[:]------------------'PYTHON'
>>> s[::-1]--------------'NOHTYP'
>>> s[::2]--------------'PTO'
>>> s[::-2]--------------'NHY'
==========================X=============================
………………………………………………………………………………………………
19
=========================================
Type Casting Techniques in Python
=========================================
=>The process of converting one type of value into another type value is called Type
Casting.
=>In Python programming , we have 5 Type casting Functions. They are
a) int()
b) float()
c) bool()
d) complex()
e) str()
-------------------------------------------------------------------------------------------------
a) int()
-------
=>This function is used for converting any type of Possible value into int type value.
=>Syntax:- varname=int(float / bool / complex / str)
Examples: (float----->int--->Possible)
----------------------------------------------------
>>> a=12.34
>>> print(a, type(a))----------12.34 <class 'float'>
>>> b=int(a)
>>> print(b, type(b))----------12 <class 'int'>
-------------------------------------------------------------------
Examples: (bool----->int--->Possible)
-------------------------------------------------------------------
>>> a=True
>>> print(a, type(a))--------------True <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------1 <class 'int'>
>>> a=False
>>> print(a, type(a))------------False <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))----------0 <class 'int'>
----------------------------------------------------------------------------
Examples: (complex----->int--->Not Possible )
-------------------------------------------------------------------
>>> a=2+3j
>>> print(a, type(a))-------------(2+3j) <class 'complex'>
>>> b=int(a)---------TypeError: can't convert complex to int
>>> print(a.real)
2.0
>>> b=int(a.real)
20
========================================
b) float()
========================================
=>This function is used for converting any type of Possible value into float type
value.
Examples(int---->float-->Possible:
------------------------------------------------
>>> a=100
>>> print(a,type(a))--------100 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))--------100.0 <class 'float'>
--------------------------------------------------------------------
Examples(bool---->float-->Possible)
--------------------------------------------------
>>> a=True
>>> print(a,type(a))-----------------True <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))-------------1.0 <class 'float'>
>>> a=False
>>> print(a,type(a))-------------False <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))----------0.0 <class 'float'>
----------------------------------------------------------------------
Examples(complex---->float-->Not Possible)
-----------------------------------------------------------------------
>>> a=2+4.5j
>>> print(a,type(a))-------------(2+4.5j) <class 'complex'>
>>> b=float(a)----------TypeError: can't convert complex to float
------------------------------------------------------------------------------------------
Examples(int str---->float-->Possible)
-----------------------------------------------------------------------
>>> a="12"
>>> print(a,type(a))---------12 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))-------12.0 <class 'float'>
------------------------------------------------------------------------
Examples(float str---->float-->Possible)
-----------------------------------------------------------------------
>>> a="12.34"
>>> print(a,type(a))-----------12.34 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))-----------12.34 <class 'float'>
------------------------------------------------------------------------
Examples(bool str---->float-->Not Possible )
-----------------------------------------------------------------------
>>> a="True"
22
====================================
c) bool()
====================================
=>This function is used for converting any type of Possible value into bool type
value.
>>> a=0.0
>>> print(a,type(a))----------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))---------False <class 'bool'>
>>> a=0.0000000000000000000000000000000000001
>>> print(a,type(a))------- 1e-37 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
-------------------------------------------------------------------------------
Examples(complex---->bool-->Possible)
------------------------------------------------
>>> a=2+3j
>>> print(a,type(a))--------------(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))-------0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))--------False <class 'bool'>
---------------------------------------------------------------------------
Examples(str---->bool-->Possible )
--------------------------------------------------------------
>>> a="PYTHON"
>>> print(a,type(a))----------------PYTHON <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a="$%#12kvr"
>>> print(a,type(a))-----------$%#12kvr <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'>
>>> a=""
>>> print(a,type(a))---------- <class 'str'>
>>>b=bool(a)
>>> len(a)----------0
>>> print(b,type(b))---------False <class 'bool'>
>>> bool(str())----------False
>>> len(str())------------0
===============================================================
24
==========================================
d) complex()
==========================================
=>This function is used for converting any type of Possible value into complex type
value.
>>> a="2+3j"
>>> print(a, type(a))------------2+3j <class 'str'>
>>> b=complex(a)
>>> print(b, type(b))--------------(2+3j) <class 'complex'>
===================================
e) str( )
===================================
=>This function is used for converting any type of Possible value into str type value.
==========================================
bytes
==========================================
=>'bytes' is one of the pre-defined class and treated as sequence data type
=>The purpose of bytes data type is that to store Numerical Possitive Integer
Values ranges from 0 to 256 i.e it store the values from 0 to 255 (256-1)
=>bytes data type does not contain any symbolic notation to represent bytes
values. But we can convert other type values into bytes type values by using
bytes().
====================================================
bytearray
====================================================
=>'bytearray' is one of the pre-defined class and treated as sequence data type
=>The purpose of bytearray data type is that to store Numerical Positive Integer
Values ranges from 0 to 256… i.e it store the values from 0 to 255 (256-1)
=>bytearray data type does not contain any symbolic notation to represent bytearray
values. But we can convert other type values into bytearray type values by using
bytearray().
=>On the object bytearray data type, we can perform Indexing and slicing
Operations.
=>An object of bytearray maintains Insertion Order (or) Preserves insertion Order (
In whichever order, we insert the data, in the same order data will be displayed)
=>An object of bytearray is mutable.
Note:- The Functionality of bytearray is exactly similar to bytes data type but an
object bytearray belongs to mutable and bytes object belongs immutable.
------------------------------------------------------------------------------------------------------------
Examples:
-----------------
>>> l=[10,23,45,255]
>>> ba=bytearray(l)
>>> print(ba)-------------------bytearray(b'\n\x17-\xff')
>>> print(type(ba))----------<class 'bytearray'>
>>> for x in ba:
... print(x)
...
10
23
45
255
>>> print(id(ba))---------------2433089030064
>>> print(ba[0])--------------10
>>> print(ba[1])-------------23
>>> ba[0]=123
>>> for x in ba:
... print(x)
...
123
23
45
255
>>> print(id(ba))---------------2433089030064
28
=========================================
range
========================================
=>'range' is on the pre-defined class and treated as sequence data type.
=>The purpose of range data type that to store sequence of values with equal
interval
=>On the range object we can perform indexing and slicing operations
=>An object of range belongs to immutable.
=>range data type provides the following syntaxes:
-------------------------------------------------------------------------
Syntax1:- varname=range(value):
=>here varname is an object <class,'range'>
=>This syntax generates range object from 0 to value-1
Examples:-
>>> r=range(11)
>>> print(r)
range(0, 11)
>>> print(type(r))
<class 'range'>
>>> for x in r:
... print(x)
...
0
1
2
3
4
5
6
7
8
9
10
>>> for x in range(5):
... print(x)
...
0
1
2
3
4
--------------------------------------------------------------------------
Syntax2:- varname= range(start,stop)
=>This syntax generates range object from start to stop-1 values
Examples:
---------------
>>> r=range(1,11)
>>> print(r)----------range(1, 11)
29
=>This syntax generates range object from start to stop-1 values with spoecified
interval value called step.
Examples:
--------------
>>> r=range(10,101,10)
>>> print(r, type(r))
range(10, 101, 10) <class 'range'>
>>> for x in r:
... print(x)
...
10
20
30
40
50
60
70
80
90
100
>>> for x in range(1000,1101,20):
... print(x)
...
30
1000
1020
1040
1060
1080
1100
>>> for k in range(100,9,-30):
... print(k)
...
100
70
40
10
>>> for x in range(-1,-11,-1):
... print(x)
...
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
---------------------------------
>>> for x in range(-10,0):
... print(x)
...
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
>>> for x in range(-10,0,1):
... print(x)
...
-10
-9
-8
-7
-6
-5
-4
31
-3
-2
-1
-----------------------------------------------------
>>> for k in range(-5,6):
... print(k)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
>>> for k in range(-5,6,1):
... print(k)
...
-5
-4
-3
-2
-1
0
1
2
3
============================================
>>> r=range(10,21)
>>> print(r[0])
10
>>> print(r[-11])
10
>>> print(r[-10])
11
>>> print(r[-1])
20
>>> print(r[-111])----------IndexError: range object index out of range
>>> print( r[2:7] )---------range(12, 17)
>>> for x in r[2:7]:
... print(x)
...
12
13
14
15
16
32
…………………………………………………………………………………………………
33
===============================================
III) List type data types (Collections Data Types )
===============================================
=>The purpose of List type data types is that to store multiple values either of same
type or different type or both types with unique and duplicates values.
=>We have two types of List type data types. They are
a) list (mutable)
b) tuple (immutable)
==================================================
a) list
===================================================
=>'list' is one of the pre-defined class and treated as list type data type
=>The purpose of List type is that to store multiple values either of same type or
different type or both types with unique and duplicates values.
=>The elements of list must be written within square brackets [ ] and elements must
seprated by comma .
=>An object of list maintains insertion order.
=>On the object of list , we can perform indexing and slicing operations.
=>An object of list belongs to mutable.
=>We have two types of list objects.
=>To convert ont type elements into list type elements, we use list()
a) empty list
b) non-empty list
a) empty list:
-------------------
=>An empty list is one, which does not contain any elements and wose length =0
Syntax:- listobj=[]
(or)
listobj=list()
================================================================
Examples:
-----------------
>>> l1=[10,20,30,10,34]
>>> print(l1, type(l1))----------------[10, 20, 30, 10, 34] <class 'list'>
>>> l2=[10,"KVR","OUCET",94.25,"HYD"]
>>> print(l2, type(l2))---------------[10, 'KVR', 'OUCET', 94.25, 'HYD'] <class 'list'>
>>> print(l2[0])--------------10
>>> print(l2[2])--------------OUCET
>>> print(l2[4])----------------HYD
>>> print(l2[14])------------IndexError: list index out of range
>>> print(l2[0:4])------------[10, 'KVR', 'OUCET', 94.25]
>>> print(id(l2))------------2908432554304
>>> l2[0]=123
34
==========================================================
=========================================
Functions in list object
=========================================
=>To perform additional operations on list object along with slicing and indexing, we
use the following pre-defined functions.
1) append():
-------------
=>This function is used for adding any element to list object at end (knows
appending).
Syntax:- listobj.append(element)
Examples:
--------------
>>> l1=[]
>>> print(l1, len(l1), type(l1))----------[] 0 <class 'list'>
>>> l1.append(10)
>>> print(l1, len(l1), type(l1))-----------[10] 1 <class 'list'>
>>> l1.append("Rossum")
>>> print(l1, len(l1))---------------[10, 'Rossum'] 2
>>> l1.append(12.34)
>>> print(l1, len(l1))----------[10, 'Rossum', 12.34] 3
>>> l2=[10,"Bharat"]
>>> print(l2)-----------------[10, 'Bharat']
>>> l2.append(23.45)
>>> print(l2)---------------[10, 'Bharat', 23.45]
>>> l2.append("Hyd")-----------
>>> print(l2)-------------[10, 'Bharat', 23.45, 'Hyd']
--------------------------------------------------------------------------------
35
2) insert();
=>This function is used for inserting the specified element in list object by specifying
valid existing index.
Syntax:- listobj.insert(index, element)
Examples:
--------------
>> l2=[10,"Bharat",23.45,"HYD"]
>>> print(l2)-------------[10, 'Bharat', 23.45, 'HYD']
>>> l2.insert(2,"python")
>>> print(l2)-------------[10, 'Bharat', 'python', 23.45, 'HYD']
>>> l2.insert(2,"ampt")
>>> print(l2)-----------[10, 'Bharat', 'ampt', 'python', 23.45, 'HYD']
>>> l2[4]=43.45
>>> print(l2)------------[10, 'Bharat', 'ampt', 'python', 43.45, 'HYD']
-----------------------------------------------------------------------
3) remove():
----------------------
=>This function is used for removing the first occurrence of specified element.
if the specified element then we get ValueError: list.remove(x): x not in list
=> syntax: listobj.remove(element)
Examples:
------------------
>>> l3=[10,"Raju",23.45,10,"Raju","HYD"]
>>> print(l3)--------------[10, 'Raju', 23.45, 10, 'Raju', 'HYD']
>>> l3.remove(10)
>>> print(l3)-------------['Raju', 23.45, 10, 'Raju', 'HYD']
>>> l3.remove(10)
>>> print(l3)----------------['Raju', 23.45, 'Raju', 'HYD']
>>> l3.remove(10)-----------ValueError: list.remove(x): x not in list
-------------------------------------------------------------------------------
4) pop(index):
---------------------------
=>This function is used for removing the element of list based on valid index.
=>if the index is invalid then we get IndexError
=>Syntax:- listobj.pop(index)
Examples:
-----------------------
>>>l3=[10, 23.45, 10, 'Raju', 'HYD']
>>> l3.pop(0)------------10
>>> print(l3)---------[23.45, 10, 'Raju', 'HYD']
36
Examples:
------------------
>>> l3=[10,"Raju",23.45,10,"Raju","HYD"]
>>> l3.pop()-----------'HYD'
>>> print(l3)------[10, 'Raju', 23.45, 10, 'Raju']
>>> l3.pop()-----------'Raju'
>>> print(l3)-------------[10, 'Raju', 23.45, 10]
>>> l3.pop()----------10
>>> print(l3)------------[10, 'Raju', 23.45]
>>> l3.pop()------------23.45
>>> print(l3)-------------[10, 'Raju']
>>> l3.pop()----------------'Raju'
>>> print(l3)--------------[10]
>>> l3.pop()------------10
>>> print(l3)--------------[]
>>> l3.pop()-------------IndexError: pop from empty list
Special Case
---------------------------
>>> print([].pop())----------IndexError: pop from empty list
>>> print(list().pop())----------IndexError: pop from empty list
-----------------------------------------------------------------------------------------
6) count():
---------------
=>This function is used for finding number of occurrences of a specified element.
=>The specified element does not exists then whose count 0.
=>Syntax: listobj.count(element)
Examples:
>>> l1=[10,20,30,40,10,20,10,20]
>>> print(l1)------------------[10, 20, 30, 40, 10, 20, 10, 20]
>>> l1.count(10)--------------3
>>> l1.count(20)--------------3
>>> l1.count(40)---------------1
>>> l1.count(50)-----------------0
>>> l1.count("KVR")-------------0
37
7) reverse():
--------------------
=>This function is used for obtaining reverse order original elements of list.
=>Syntax:- listobj.reverse()
-----------------
Examples:
-----------------
>>> l1=[10,20,30,40,40-50,0,12]
>>> print(l1)------------[10, 20, 30, 40, -10, 0, 12]
>>> l1.reverse()
>>> print(l1)-----------[12, 0, -10, 40, 30, 20, 10]
------------------------------------------------------------------
8) sort()
--------------
=>This function is used for sorting similar type data of list object in Ascending order
by default.
=>Syntax: listobj.sort() (or) listobj.sort(reverse=False)
=>Syntax: listobj.sort(reverse=True)------DESC order
Examples:
-----------------
>>> l1=[10,20,30,40,40-50,0,12]
>>> print(l1)----------[10, 20, 30, 40, -10, 0, 12]
>>> l1.sort()
>>> print(l1)-----------[-10, 0, 10, 12, 20, 30, 40]----ASC
>>> l1.reverse()
>>> print(l1)----------[40, 30, 20, 12, 10, 0, -10]---DESC
-------------------------------------------------------------------
Special Case:
----------------------
>>> l1=[10,20,30,40,40-50,0,12]
>>> print(l1)---------------[10, 20, 30, 40, -10, 0, 12]
>>> l1.sort(reverse=True)
>>> print(l1)---------------[40, 30, 20, 12, 10, 0, -10]
>>> l1.reverse()
>>> print(l1)-----------------[-10, 0, 10, 12, 20, 30, 40]
>>> l1=[10,20,30,40,40-50,0,12]
>>> print(l1)--------------[10, 20, 30, 40, -10, 0, 12]
>>> l1.sort(reverse=False)
>>> print(l1)--------------[-10, 0, 10, 12, 20, 30, 40]
38
9) copy():
----------------
=>This function is used for copying the content of one list object into another list
object(shallow copy).
a) Shallow Copy
------------------------
=>In this Copy process,
a) Initially, Both the objects content is same
b) Both objects memory address are different.
c) Modification on both the objects are Independent (or) modifications
are not reflected to each other.
=>To implement shallow copy, we use copy()
b) Deep Copy
---------------------
=>In this Copy process,
a) Initially, Both the objects content is same
b) Both objects memory address are Same.
c) Modification on both the objects are dependent (or) modifications
are reflected to each other.
=>=>To implement deep copy, we use assignment operator ( = )
=>Syntax:- listobj2=listobj1
-----------------------------------------------------------------------------
Examples of shallow copy:-
---------------------------------------
>>> l1=[10,"KVR","Hyd","Python"]
>>> l2=l1.copy()
>>> print(l1)------------------[10, 'KVR', 'Hyd', 'Python']
>>> print(l2)----------------[10, 'KVR', 'Hyd', 'Python']
>>> print(id(l1))-------------2868252301184
>>> print(id(l2))-------------2868252275008
>>> l1.append(11.11)
>>> l2.insert(2,"India")
>>> print(l1, id(l1))---------[10, 'KVR', 'Hyd', 'Python', 11.11] 2868252301184
>>> print(l2, id(l2))--------[10, 'KVR', 'India', 'Hyd', 'Python'] 2868252275008
-------------------------------------------
Examples of deep copy:-
>>> l1=[10,"KVR","Hyd","Python"]
>>> l2=l1 # DEEP COPY
>>> print(l1, id(l1))-------------[10, 'KVR', 'Hyd', 'Python'] 2868252591232
>>> print(l2, id(l2))------------------[10, 'KVR', 'Hyd', 'Python'] 2868252591232
>>> l1.append(22.22)
>>> print(l1, id(l1))----------[10, 'KVR', 'Hyd', 'Python', 22.22] 2868252591232
39
Note:- By using operator +, we can add two or more list objects into another list
object.
Examples:
---------------
>>> l1=[10,"Anurag","Hyd"]
>>> print(l1, id(l1))---------[10, 'Anurag', 'Hyd'] 2868252275008
>>> l2=["PYTHON","JAVA","DS with AI"]
>>> print(l2, id(l2))------['PYTHON', 'JAVA', 'DS with AI'] 2868252301184
>>> l1.extend(l2)
>>> print(l1)-------[10, 'Anurag', 'Hyd', 'PYTHON', 'JAVA', 'DS with AI']
>>> l1=[10,"Anurag","Hyd"]
>>> l2=["PYTHON","JAVA","DS with AI"]
>>> l3=["Oracle","MySql","SQLITE3"]
>>> l1.extend(l2,l3)---------TypeError: list.extend() takes exactly one argument (2
given)
>>> l1=l1+l2+l3 # using + we can extend the functionality two or more list objects.
>>> print(l1)--[10, 'Anurag', 'Hyd', 'PYTHON', 'JAVA', 'DS with AI', 'Oracle', 'MySql',
'SQLITE3']
>>> print(l2)------['PYTHON', 'JAVA', 'DS with AI']
>>> print(l3)-------['Oracle', 'MySql', 'SQLITE3']
-------------------------------------------------------------------------------
==========================================
inner (or ) nested list
==========================================
=>The process of defining one list in another list is called inner or nested list.
=>Syntax:
---------------
listobj=[ elements of list, [ inner list elements]......[inner list elements].. ]
Example:
requirement:- i want to store student details like stdno,name, Internal marks of 4
subjects and external marks of 4 subs and college name
--------------------------------------------------------------------------------------------------------
>>> sl=[10,"Mukul",[20,15,16,19],[66,77,80,78],"OUCET"]
>>> print(sl)------------------------[10, 'Mukul', [20, 15, 16, 19], [66, 77, 80, 78], 'OUCET']
>>> print(sl[0])-------------10
>>> print(sl[1])------------Mukul
>>> print(sl[2])------------[20, 15, 16, 19]
>>> print(sl[-2])-------------[66, 77, 80, 78]
>>> print(sl[-1])-------------OUCET
>>> print(sl[2][-1])------------19
>>> print(sl[-3][-4])-----------20
>>> sl[2][-3]=17
>>> print(sl)----[10, 'Mukul', [20, 17, 16, 19], [66, 77, 80, 78], 'OUCET']
>>> sl[2].append(20)
>>> print(sl)-----[10, 'Mukul', [20, 17, 16, 19, 20], [66, 77, 80, 78], 'OUCET']
>>> sl[-2].insert(1,80)
>>> print(sl)--------[10, 'Mukul', [20, 17, 16, 19, 20], [66, 80, 77, 80, 78], 'OUCET']
>>> sl[-2].count(80)--------2
41
========================================
tuple
========================================
=>'tuple' is one of the pre-defined class and treated as list type data type
=>The purpose of tuple type is that to store multiple values either of same type or
different type or both types with unique and duplicates values.
=>The elements of tuple must be written within braces ( ) and elements must
separated by comma .
=>An object of tuple maintains insertion order.
=>On the object of tuple , we can perform indexing and slicing operations.
=>An object of tuple belongs to immutable.
=>To convert one type value into tuple type, we use tuple()
=>We have two types of tuple objects.
a) empty tuple
b) non-empty tuple
a) empty tuple:
--------------------
=>It does not contain any elements and whose size is 0
Syntax:- varname= ()
(or)
varname= tuple()
b) non-empty tuple:
--------------------
=>It contain elements and whose size is > 0
Syntax:- varname= (list elements)
Note:- The functionality of tuple is exactly similar to the functionality of list but an
object tuple belongs to immutable and list object belongs to mutable.
--------------------------------------------------------------------------------------------------
Examples:
-----------------
>>> t1=()
>>> print(t1, type(t1))------------() <class 'tuple'>
>>> t2=tuple()
>>> print(t2, type(t2))-------------() <class 'tuple'>
>>> len(t1)-----------0
>>> len(t2)-----------0
>>> t3=(10,30,20,10,30,45)
>>> print(t3, type(t3))------------(10, 30, 20, 10, 30, 45) <class 'tuple'>
>>> t3=(10,"Rossum","hyd",34.56)
>>> print(t3, type(t3))---------(10, 'Rossum', 'hyd', 34.56) <class 'tuple'>
>>> t4=110,"JG","SUN",45.67
>>> print(t4, type(t4))-----------(110, 'JG', 'SUN', 45.67) <class 'tuple'>
>>> a=10
>>> print(a, type(a))-------------10 <class 'int'>
>>> b=10,
>>> print(b, type(b))--------(10,) <class 'tuple'>
42
>>> b=(100,200,)
>>> print(b, type(b))-----------(100, 200) <class 'tuple'>
------------------------------------------------------------------------------
>>> t3=(10,30,20,10,30,45)
>>> print(t3[0])----------10
>>> print(t3[1])----------30
>>> len(t3)-------6
>>> print(t3[5])---------45
>>> print(t3[len(t3)-1])------45
>>> print(t3[len(t3)])-------IndexError: tuple index out of range
>>> print(t3[1:4])--------(30, 20, 10)
>>> print(t3,id(t3))------(10, 30, 20, 10, 30, 45) 2868252533280
>>> t3[0]=100------TypeError: 'tuple' object does not support item assignment
-------------------------------------------------------------------------------------------------------
===============================================
IV) set type data types (Collections Data Types )
===============================================
=>The purpose of set type data types is that to store multiple values either of same
type or different type or both types with unique values.
=>we have two types set data types
a) set (Mutable and Immutable)
b) frozenset (Immutable )
==========================================
a) set (Mutable and Immutable)
==========================================
=>'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 either of same type or
different type or both types with unique values.
=>The elements of set must be written within curly braces { } and elements must
separated by comma.
=>An object of set never maintains insertion order bcoz it can display any
its possibility among multiple possibilities.
=>On the object of set, we can't perform indexing and slicing operations bcoz it
never maintains insertion order.
=>To convert one type value into set type value, we use set().
=>An object of set belongs to both mutable(in the case of add() ) and immutable (in
the case of item assignment )
=>We have two types of sets. They are
a) empty set
b) non-empty set
a) empty set:
------------------
=>empty set does not contain elements and whose size is 0
Syntax: - varname=set()
43
b) non-empty set:
------------------
=>non-empty set contains elements and whose size is >0
Syntax: - varname={set of elements }
----------------------------------------------------------------------------------------------------
Examples-:
------------------
>>> s1=()
>>> s2=set()
>>> s3={10,20,30,-4,50,10}
>>> s4={10,"Rossum",23.45,True}
>>> print(s1, type(s1))---------() <class 'tuple'>
>>> print(s2, type(s2))-----------set() <class 'set'>
>>> print(s3, type(s3))--------{50, 20, 10, -4, 30} <class 'set'>
>>> print(s4, type(s4))---------{True, 10, 'Rossum', 23.45} <class 'set'>
>>> print(s3[0])----TypeError: 'set' object is not subscriptable
>>> print(s3[0:3])--------TypeError: 'set' object is not subscriptable
--------------------------------------------------------------------------------------------------------
==========================================
Functions in set
==========================================
a) add():
------------
=>This function is used for adding any type element to the set object
=>Syntax:- setobj.add(element)
Examples:
-----------------
>>> s1=set()
>>> print(s1, type(s1), len(s1))-------set() <class 'set'> 0
>>> s1.add(100)
>>> s1.add("Rossum")
>>> s1.add(23.45)
>>> s1.add(True)
>>> print(s1, type(s1), len(s1))-----{True, 'Rossum', 100, 23.45} <class 'set'> 4
-----------------------------------------------------------------------------------
b)remove()
=>This function is used for removing a particular element from set object.
=>If the specified element does not exists then we get KeyError
=>Syntax:- setobj.remove(element)
----------------
44
Examples:
----------------
>>> s1={True, 'Rossum', 100, 23.45}
>>> print(s1)
{True, 'Rossum', 100, 23.45}
>>> s1.remove(100)
>>> print(s1)
{True, 'Rossum', 23.45}
>>> s1.remove(100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 100
------------------------------------------------------------------------------------------
c)discard()
---------------
=>This function is used for removing / discarding a particular element from set
object otherwise never removed.
=>If the specified element does not exists then we never get any error
Syntax:- setobj.discard(element)
Examples:-
----------------
>>> s1={True, 'Rossum', 100, 23.45}
>>> print(s1)-----------{True, 'Rossum', 100, 23.45}
>>> s1.discard(23.45)
>>> print(s1)------------{True, 'Rossum', 100}
>>> s1.discard(123.45)
>>> print(s1)-------------{True, 'Rossum', 100}
----------------------------------------------------------------------------
d)pop():
---------------
=>This function is used for removing any arbitrary element from set object.
Syntax:- setobj.pop()
Examples:
----------------
>>> s1={True, 'Rossum', 100, 23.45}
>>> print(s1)-----------{True, 'Rossum', 100, 23.45}
>>> s1.pop()---------True
>>> print(s1)-------{'Rossum', 100, 23.45}
>>> s1.pop()----------'Rossum'
>>> print(s1)----------{100, 23.45}
>>> s1.pop()----------100
>>> print(s1)----------{23.45}
>>> s1.pop()---------23.45
>>> print(s1)---------set()
45
f) issubset():
-------------------
=>This function returns True provided all the elements of setobj1 present setobj2
otherwise it returns False
Sytntax:- setobj1.issubset(setobj2)
Examples:
-----------------
>>> s1={10,20,30}
>>> s4={10,20}
>>> s2={40,50,60}
>>> s2.issubset(s1)---------False
>>> s4.issubset(s1)-------True
>>> set().issubset(s1)--------True
>>> set().issubset(set())----------True
>>> s2={10,50,60}
>>> s2.issubset(s1)------------False
g) union():
---------------
=>This function is used for combining all specified sets by considering duplicate
elements as single element.
Syntax:- setobj3=setobj1.union(setobj2)
>>> s1={10,20,30,40}
>>> s2={20,30,50,60}
>>> s3=s1.union(s2)
>>> print(s3)------------{40, 10, 50, 20, 60, 30}
-----------------------------------------------------------------------------
h)intersection():
-----------------------
=>This function is used for extracting common elements from specified sets.
=>Syntax:- setobj3=setobj1.intersection(setobj2)
>>> s1={10,20,30,40}
>>> s2={20,30,50,60}
>>> s4=s1.intersection(s2)
>>> print(s4)----------{20, 30}
------------------------------------------------------------------------------------------------
i) difference()
--------------------
Syntax:- setobj3=setobj1.difference(setobj2)
=>This function is used for removing common elements from setobj1 and setobj2
and extract remaining from setobj1 and place them setobj3.
Example:
-------------
>>> s1={10,20,30,40}
>>> s2={20,30,50,60}
>>> s5=s1.difference(s2)
>>> print(s5)---------{40, 10}
>>> s6=s2.difference(s1)
>>> print(s6)-----------{50, 60}
47
j) symmetric difference():
-------------------------------------
=>This function is used for obtaining exclusive elements of specified sets by element
Ing common elements from all the sets.
Syntax:- setobj3=setobj1.symmetric_difference(setobj2)
Example:
>>> s1={10,20,30,40}
>>> s2={20,30,50,60}
>>> s7=s1.symmetric_difference(s2)
>>> print(s7)----------{40, 10, 50, 60}
>>> s8=s2.symmetric_difference(s1)
>>> print(s8)----------{40, 10, 50, 60}
-------------------------------------------------------------------------------------
Special case:-
---------------------
>>> s1={10,20,30,40}
>>> s2={20,30,50,60}
>>> s3={10,70,80,20}
>>> s4=s1.union(s2,s3)
>>> print(s4)------------{70, 40, 10, 80, 50, 20, 60, 30}
>>> s4=s1.union(s2).union(s3)
>>> print(s4)---------------{70, 40, 10, 80, 50, 20, 60, 30}
>>> s5=s1.intersection(s2,s3)
>>> print(s5)------------{20}
>>> s5=s1.intersection(s2).intersection(s3)
>>> print(s5)-----------{20}
>>> s6=s1.difference(s2,s3)
>>> print(s6)---------{40}
>>> s6=s1.difference(s2).difference(s3)
>>> print(s6)-----------{40}
>>> s7=s1.symmetric_difference(s2,s3)------TypeError: set.symmetric_difference()
takes exactly one argument (2 given)
>>> s7=s1.symmetric_difference(s2).symmetric_difference(s3)
>>> print(s7)----------{70, 40, 80, 50, 20, 60}
---------------------------------------------------------------------------------------------------------
Most Special Cases:
------------------------------
>>> s1={10,20,30,40}
>>> s2={20,30,50,60}
>>> s3=s1|s2 #bitwise OR
>>> print(s3)------------{40, 10, 50, 20, 60, 30}
>>> s3=s1.union(s2)
>>> print(s3)------------{40, 10, 50, 20, 60, 30}
>>> s4=s1&s2 # bitwise AND
>>> print(s4)--------------{20, 30}
>>> s4=s1.intersection(s2)
>>> print(s4)------------{20, 30}
>>> s3=s1-s2 # Arithmetic operator minus(-)
>>> print(s3)------------{40, 10}
48
>>> s3=s2-s1
>>> print(s3)-------------{50, 60}
>>> s4=s1^s2-------------Bitwise XOR
>>> print(s4)-----------------{40, 10, 50, 60}
------------------------------------------------------------------------------------------------
…………………………………………………………………………………………………
=======================================
frozenset (immutable)
========================================
=>'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 either of same
type or different type or both types with unique values.
=>we don't have any symbolic notation to represent the elements in frozenset. But
we can convert list type elements and set type elements into frozenset by using
frozenset()
Syntax:- varname=frozenset(list / tuple / set)
=>An object of frozenset never maintains insertion order bcoz it can display any
its possibility among multiple possibilities.
=>On the object of frozenset, we can't perform indexing and slicing operations bcoz
it never maintains insertion order.
=>An object of frozenset belongs to immutable (in the case of item assignment )
Examples:
----------------
>>> s1={10,20,30,"Hyd"}
>>> print(s1, type(s1))-------------{10, 'Hyd', 20, 30} <class 'set'>
>>> fs=frozenset(s1)
>>> print(fs, type(fs))-----------frozenset({10, 'Hyd', 20, 30}) <class 'frozenset'>
>>> lst=[10,20,10,"python","java"]
>>> print(lst, type(lst))---------[10, 20, 10, 'python', 'java'] <class 'list'>
>>> fs1=frozenset(lst)
>>> print(fs1, type(fs1))-----------frozenset({10, 20, 'python', 'java'}) <class 'frozenset'>
>>> tpl=(10,20,10,20,"python","PYTHON")
>>> fs2=frozenset(tpl)
>>> print(fs2, type(fs2))------frozenset({10, 'PYTHON', 20, 'python'}) <class
'frozenset'>
Examples:
-----------------
>>> lst=[10,20,10,"python","java"]
>>> print(lst, type(lst))-----------[10, 20, 10, 'python', 'java'] <class 'list'>
>>> fs1=frozenset(lst)
>>> print(fs1, type(fs1))-------frozenset({10, 20, 'python', 'java'}) <class 'frozenset'>
>>> tpl=(10,20,10,20,"python","PYTHON")
>>> fs2=frozenset(tpl)
>>> print(fs2, type(fs2))---frozenset({10, 'PYTHON', 20, 'python'}) <class 'frozenset'>
>>> a=10
>>> fs=frozenset(a)-------TypeError: 'int' object is not iterable
>>> fs=frozenset(a,)-------TypeError: 'int' object is not iterable
>>> fs=list(a)-----------TypeError: 'int' object is not iterable
>>> x=a,
>>> fs=frozenset(x)
>>> print(fs)-------------frozenset({10})
>>> a=10
>>> fs=frozenset((a,))---------
>>> print(fs)-------frozenset({10})
>>> fs=frozenset([a,])
>>> print(fs)--------frozenset({10})
>>> fs=frozenset({a,})
>>> print(fs)----------frozenset({10})
------------------------------------------------------------------------------------------------
Examples:;
-------------------
>>> tpl=(10,20,10,20,"python","PYTHON")
>>> fs=frozenset(tpl)
>>> print(fs)----------frozenset({10, 'PYTHON', 20, 'python'})
50
>>> d4={"sub1":"python",10:20,40:"Java","DS":50}
>>> print(d4,type(d4))--------{'sub1': 'python', 10: 20, 40: 'Java', 'DS': 50} <class 'dict'>
>>> print(d4[0])-----KeyError: 0
>>> print(d4["sub1"])------------python
>>> print(d4["DS"])-------------50
>>> print(id(d4))---------2041082686784
>>> d4["sub1"]="JAVA"
>>> print(d4)-----------{'sub1': 'JAVA', 10: 20, 40: 'Java', 'DS': 50}
>>> print(id(d4))----------2041082686784
========================================================
Syntax for empty dict:
--------------------------------------
varname={}
Syntax for adding (Key,Value) to the empty object
dictobj[key1]=val1
dictobj[key2]=val2
-------------------------
dictobj[keyn]=valn
Examples:
-----------------------
>>> d1={}
>>> print(d1, type(d1))---------{} <class 'dict'>
>>> len(d1)--------0
>>> d1["stno"]=12
>>> d1["name"]="Rossum"
>>> d1["marks"]=23.45
>>> print(d1, type(d1))----{'stno': 12, 'name': 'Rossum', 'marks': 23.45} <class 'dict'>
>>> d1["marks"]=45.67
>>> print(d1, type(d1))--{'stno': 12, 'name': 'Rossum', 'marks': 45.67} <class 'dict'>
>>> d1["city"]="NL"
>>> print(d1)---{'stno': 12, 'name': 'Rossum', 'marks': 45.67, 'city': 'NL'}
===============================
Functions in dict
===============================
=>On the object of dict , we can perform the following operation by using
functions present in dict
1) clear():
------------
=>This function is used for removing all the entities of dict object
Syntax:- dictobj.clear()
52
Examples:
----------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)-----------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> print(len(d2))----------3
>>> d2.clear()
>>> print(d2)----------{}
>>> print(len(d2))---------0
---------------------------------------
2) copy():
--------------
=>This function is used for copying the content of one dict into another dict object.
(Implementing Shallow copy)
=>Syntax: dictobj2=dictobj1.copy()
Examples:
---------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> d3=d2.copy()
>>> print(d2, id(d2))---------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'} 2041082686080
>>> print(d3, id(d3))---{10: 'Apple', 20: 'Mango', 30: 'Kiwi'} 2041082686400
>>> d2[40]="Sberry"
>>> d3[50]="Guava"
>>> print(d3, id(d3))---{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 50: 'Guava'}
2041082686400
>>> print(d2, id(d2))---{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'}
2041082686080
-----------------------------------------------------------------------------------------------------------
3)popitem():
----------------
=>This function always removes last element from non-empty dict.
=>we call popitem() on empty dict object we get KeyError: 'popitem(): dictionary is
empty'
Syntax:- dictobj.popitem()
---------------
Examples:
---------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)----------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> d2.popitem()-------(30, 'Kiwi')
>>> print(d2)-------{10: 'Apple', 20: 'Mango'}
>>> d2.popitem()-----(20, 'Mango')
>>> print(d2)--------{10: 'Apple'}
>>> d2.popitem()-------(10, 'Apple')
>>> print(d2)--------{}
>>> d2.popitem()--------KeyError: 'popitem(): dictionary is empty'
--------------------------------------------------------------------------------------------
53
4) pop():
-----------
=>This function is used for removing (Key,Value) from dict object by passing Value
of Key . if the value of Key does not exists then we get KeyError
Syntax:- dictobj.pop(key)
Example:
------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> d2.pop(10)-----------'Apple'
>>> print(d2)----------{20: 'Mango', 30: 'Kiwi'}
>>> d2.pop(30)---------'Kiwi'
>>> print(d2)----------{20: 'Mango'}
>>> d2.pop(100)---------KeyError: 100
----------------------------------------------------------------------------------------
5) get() :
-----------
=>This function is used for finding the value of Value by passing value of Key.
=>If the Value of Key does noy exist then we get None ( It indicates no value found
on the that key)
Syntax:- varname=dictobj.get(key)
Examples:
--------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)--------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> print(d2.keys())------dict_keys([10, 20, 30])
>>> d3={}
>>> print(d3.keys())----dict_keys([])
54
>>> k=d2.keys()
>>> print(k)-------dict_keys([10, 20, 30])
>>> for x in k:
... print(x)
...
10
20
30
>>> for x in d2.keys():
... print(x)
...
10
20
30
------------------------------------------------------------------------
7) values() :
----------------
=>This function gives list of Values from dict object.
Syntax:- dictobj.values()
(or)
varname=dictobj.values()
Examples:
-------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)
{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> v=d2.values()
>>> print(v)-----------dict_values(['Apple', 'Mango', 'Kiwi'])
>>> for value in v:
... print(value)
...
Apple
Mango
Kiwi
>>> for value in d2.values():
... print(value)
...
Apple
Mango
Kiwi
------------------------------------------------------------------------------
8)items():
--------------
=>This function gives (Key,value) entries of dict object
=>Syntax:- dictobj.items()
(or)
varname=dictobj.items()
Examples:
----------------
55
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)-------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> kv=d2.items()
>>> print(kv)-------dict_items([(10, 'Apple'), (20, 'Mango'), (30, 'Kiwi')])
>>> for entry in kv:
... print(entry)
...
(10, 'Apple')
(20, 'Mango')
(30, 'Kiwi')
>>> for entry in d2.items():
... print(entry)
...
(10, 'Apple')
(20, 'Mango')
(30, 'Kiwi')
>>> for k,v in d2.items():
... print(k,"--->",v)
...
10 ---> Apple
20 ---> Mango
30 ---> Kiwi
-----------------------------------------------------------------------------------------
9)update()
=>This function is used for updating source dict object with target dict object
Syntax:- sourcedictobj.update(targetdictobj)
----------------
Examples:
----------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)-----------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> d3={40:"Guava",50:"banana"}
>>> d2.update(d3)
>>> print(d2)-------{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Guava', 50: 'banana'}
>>> print(d3)---{40: 'Guava', 50: 'banana'}
Examples:
--------------
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d2)----------{10: 'Apple', 20: 'Mango', 30: 'Kiwi'}
>>> d3={40:"Guava",50:"banana",30:"Sberry"}
>>> d2.update(d3)
>>> print(d2)-----------{10: 'Apple', 20: 'Mango', 30: 'Sberry', 40: 'Guava', 50: 'banana'}
----------------------------------------------------------------------------------------------------------------
None Data Type
=====================================
=>"NoneType" is one of the pre-defined class treated as None Type data type
=>None is the value of NoneType
=>The Value None is not space , false and zero
56
Examples:
----------------
>>> a=None
>>> print(type(a))---------<class 'NoneType'>
>>> d={10:"Rossum",20:"Ritche"}
>>> print(d)---------{10: 'Rossum', 20: 'Ritche'}
>>> print(d.get(10))--------Rossum
>>> print(d.get(100))--------None
=================================================
No. Of approaches to develop Python program
=================================================
=>We can develop the program in python in 2 ways. they are
a) Interactive Approach
b) Batch Mode Approach
------------------------------------------------------------------------------------------------
a) Interactive Approach:
---------------------------------
=>In This approach, As a programmer, we can give one statement at a time and
getting one result at a time.
Examples:
-------------- Python IDLE Shell (comes along with Python Software Installation)
Edit Plus (External Installation)
PyCharm (External Installation)
Spider (External Installation)
Jupiter Note Book (External Installation)----etc
============================================================
Steps to develop program in Python IDLE Shell :
-------------------------------------------------------------------
=>launch Python IDLE shell
=>Choose the File-->New File
=>Ensure that a new Window will be opened and Write the source Code and save it
on some file name with an extension .py Example: sum.py
=>Run the python Program
a) Through IDLE shell--->Run--->Run Module ( f5)
b) go to cmd prompt and locate the folder where we saved the program.
To run the python from command prompt, we use a tool called "python" or "py"
57
------------------------------
=>Formats of print():
------------------------------
Syntax1:- print(msg), here msg represents str
Examples:
---------------
>>> print("Hello")-------------Hello
>>> print("Python")----------Python
>>> print("Val of a")----------Val of a
---------------------------------------------------------------------
Syntax2:- print(var1,var2....var-n),
here var1,var2...var-n represents valid variable names of any data type.
Examples:
---------------
>>> a=10
>>> print(a)-----------10
>>> lst=[10,"abc",23.45]
>>> print(lst)----------[10, 'abc', 23.45]
>>> print(a,lst)-------10 [10, 'abc', 23.45]
-----------------------------------------------------------------------------------
Syntax3:- print(Message sum Variables list),
here var1,var2...var-n represents valid variable names of any data type.
Examples:
-----------------
>>>print("Val of a=",a)---------val of a=10
>>>print(a, "Val of a")------- 10 val of a
>>> a=10
>>> b=20
>>> c=a+b
>>>print("sum of ",a," and ",b,"=",c)-------sum of 10 and 20 = 30
---------------------------------------------------------------------------------------------
58
Examples:
-----------------
>>>print("Val of a={}".format(a))---------val of a=10
>>>print("{} Val of a".format(a) )------- 10 val of a
>>> a=10
>>> b=20
>>> c=a+b
>>>print("sum of {} and {} = {}".format(a,b,c))
---------------------------------------------------------------------------
Syntax5:- print(Message with format specifiers)
Examples:
-----------------
>>>print("Val of a=%" %a)
>>>print("%f Val of a" %a)
>>> a=10
>>> b=20
>>> c=a+b
>>>print("sum of %d and %f = %f" %(a,b,c))
#Program for calculating sum two numbers
a=float(input("Enter value of a:"))
b=float(input("Enter value of b:"))
c=a+b
print("-"*40) #for Underline between two lines of code
print("Val of a=",a)
print("Val of b=",b)
print("sum=",c)
print("-"*40)
…………………………………………………………………………………………………
===========================================
reading The input data to the python program
===========================================
=>To read the data from keyboard , we use a pre-defined function called input().
=>The input() is available in two forms.
1)input()
2) input(msg)
1)input():
-------------
=>This function is used for reading any type of value from key board in the form of
str.
Syntax:- varname=input()
=>here 'varname' represents an object of str and we can convert any type of str
value into another type Type Conversion Functions.
=>input() is predefined functions
-------------------------------------------------------------------------------------------------------------
59
2) input(msg):
------------------------
=>This function is used for reading any type of value from key board in the form of
str by giving user-prompting message.
Syntax:- varname=input(Msg)
=>here 'varname' represents an object of str and we can convert any type of str
value into another type Type Conversion Functions.
=>input() is predefined functions
=>Msg represents User-Prompting Message
#dataread1.py
#Program accepting two values from KBD and find their mul
print("Enter two values")
s1=input()
s2=input()
v1=float(s1)
v2=float(s2)
v3=v1*v2
print("mul( {}, {} )={}".format(v1,v2,v3))
…………………………………………………………………………………………………..
#dataread2.py
#Program accepting two values from KBD and find their mul
print("Enter two values")
v1=float(input())
v2=float( input() )
v3=v1*v2
print("mul( {}, {} )={}".format(v1,v2,v3))
………………………………………………………………………………………………….
#dataread3.py
#Program accepting two values from KBD and find their mul
print("Enter two values")
v1=float(input())
v2=float( input() )
print("mul( {}, {} )={}".format(v1,v2,v1*v2))
………………………………………………………………………………………………….
#dataread4.py
#Program accepting two values from KBD and find their mul
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
v1=float(s1)
v2=float(s2)
v3=v1*v2
print("Mul of {} and {}={}".format(v1,v2,v3))
………………………………………………………………………………………………….
#dataread5.py
#Program accepting two values from KBD and find their mul
v1=float(input("Enter First Value:"))
v2=float(input("Enter Second Value:"))
print("Mul of {} and {}={}".format(v1,v2,v1*v2))
60
#Program accepting two values from KBD and find their mul
#mul1.py
print("Enter First Value:")
s1=input()
print("Enter Second Value:")
s2=input()
print("Value of s1={} and whose type={}".format(s1 ,type(s1)))
print("Value of s2={} and whose type={}".format(s2,type(s2)))
#s3=s1-s2 error
#convert str values into int / float
v1=float(s1)
v2=float(s2)
print("Value of v1={} and whose type={}".format(v1 ,type(v1)))
print("Value of v2={} and whose type={}".format(v2,type(v2)))
v3=v1*v2
print("Value of v3={} and whose type={}".format(v3,type(v3)))
…………………………………………………………………………………………………
#program for calculating simple intrest and total amount to pay
#simplint.py
p=float(input("\tEnter principle Amount:"))
t=float(input("\tEnter Time:"))
r=float(input("\tEnter rate of interest:"))
si=(p*t*r)/100
totamt=p+si
print("-"*50)
print("\tResult of simple interest Formula")
print("-"*50)
print("\tPrinciple Amount:{}".format(p))
print("\tTime:{}".format(t))
print("\trate of interest:{}".format(r))
print("-"*50)
print("\tSimple Interest={}".format(si))
print("\tTotal amount to pay={}".format(totamt))
print("-"*50)
61
=========================================
Operators in Python
=========================================
=>An Operator is a symbol, which is used to perform some type of operations.
=>In Python Programming, we have 7 Operators. They are
1) Arithmetic Operators
2) Assignment Operator
3) Relational Operators
4) Logical Operators
5) Bitwise Operators.(Most Imp)
6) Membership Operators
7) Identity Operators
Note:- we don't have Pre / Post increment (++ -- ) and Ternary Operator(? :)
====================================
1) Arithmetic Operators
====================================
=>The purpose of Arithmetic Operators is to perform Arithmetic Operations such as
addition, subtraction, mul...etc.
=>We have 7 Arithmetic Operators and they are given in the following Table.
==============================================================
SlNo Symbol Meaning Example: a=10 b=3
==============================================================
1 + Addition print(a+b)-----13
2 - subtraction print(a-b)-----7
3. * multiplication print(a*b)-----30
4. / Division print(10/3)---3.33333333
(float quotient) print(10.0/3)-->3.333333
7. ** Exponentiation print(a**b)--1000
==============================================================
62
Examples:
------------------
>>> a=10
>>> b=20
>>> c=a+b # Arithgmetic Expression
>>> print(c)-------30
----------------------------------------------------------------------------------------------------
b) Multi line assignment:
Syntax:- var1,var2...var-n=val1,val2...val-n
(or)
var1,var2...var-n=expr1,expr2,....expr-n
=>With Multi line assignment, we can assign multiple RHS values to LHS variables.
63
Examples:-
>>>a,b=10,20
>>>c=a+b
>>>d=a-b
(or)
>>>a,b=10,20
>>>c,d,e=a+b,a-b,a*b
-----------------------------------------------------------------------------------------------
#assgnaop.py
a=float(input("Enter First value:"))
b=float(input("Enter Second value:"))
c,d,e,f,g,h,i=a+b,a-b,a*b,a/b,a//b,a%b,a**b
print("="*50)
print("Assignment Operator-Results")
print("="*50)
print("{} + {}={}".format(a,b,c))
print("{} - {}={}".format(a,b,d))
print("{} * {}={}".format(a,b,e))
print("{} / {}={}".format(a,b,f))
print("{} // {}={}".format(a,b,g))
print("{} % {}={}".format(a,b,h))
print("{} ** {}={}".format(a,b,i))
print("="*50)
=====================================
3) Relational Operators
=====================================
=>The purpose of Relational Operators is that "To Compare two Values "
=>If the relational operator is connected with two variables then it is called Relational
Expression (or) Test Condition
=>The Result of Relational Expression (or) Test Condition is either True or False
depends on the values of variables.
=>The following shows the list of Relational Operators.
64
=====================================================================
SlNo Symbol Meaning Example a=10,b=20,c=10
=====================================================================
1 > greater than a>b----False
b>c----True
3. == equality a==b-----False
(double equal to) a==c-----True
4 != not equal to a!=b-----True
a!=c-----False
2. or Physical ORing
3. not ------------------------
===========================================================
1) and operator:
------------------------
Truth Table
--------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 and RelExpr2
--------------------------------------------------------------------
False False False
True False False
False True False
True True True
--------------------------------------------------------------------
65
Example:
>>> a,b,c=10,20,10
>>> print(a,b,c)------------10 20 10
>>> (a>b) and (b>c)-----------False
>>> (a<b) and (b>c)-----------True
>>> (a<b) and (b<c)------------False
>>> (a!=b) and (a==c)----------True
>>> (a==b) and (a==c)--------False
=========================================================
2) or operator:
------------------------
Truth Table
--------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 or RelExpr2
--------------------------------------------------------------------
False False False
True False True
False True True
True True True
--------------------------------------------------------------------
Examples:
-----------------
>>> a,b,c=10,20,10
>>> print(a,b,c)--------10 20 10
>>> (a>b) or (b>c)----------True
>>> (a<b) or (b<c)--------True
>>> (a!=b) and (a==c)--------True
>>> (a!=b) or (a==c)--------True
>>> (a==b) or (a!=c)-------False
------------------------------------------------------------------------------------------------
3) not operator:
------------------------
Truth Table
--------------------------------------------------------------------
Rel Expr not RelExpr
--------------------------------------------------------------------
False True
True False
-----------------------------------------------------------------------
Examples:;
-------------------
>>> a=10
>>> b=20
>>> not (a!=b)---------False
>>> not (a==b)----------True
>>> a,b,c=10,20,10
>>> not ((a!=b) and (a==c))--------False
>>> not((a==b) or (a==c))----------False
>>> not((a!=b) or (a==c))-----------False
66
=========================================
Bitwise Left shift Operator ( << )
=========================================
=>The leftshift operator moves (or) filpped-off given number of bits toward left side.
=>Syntax: resultvar=Given number << no. of bits
=>Examples:
>>> a=10
>>> b=a<<3
>>> print(b)-----------80
>>> print(15<<2)----------60
>>> print(12<<3)-----------96
>>> print(120<<0)----------120
>>> print(120<<-3)----------ValueError: negative shift count
======================================================
Bitwise Right shift Operator ( >> )
======================================================
=>The Right shift operator moves (or) flipped-off given number of bits toward Right
side.
=>Syntax: resultvar=Given number >> no. of bits
Examples:
---------------
>>> a=10
>>> b=a>>3
>>> print(b)--------1
>>> print(15>>2)------3
>>> print(120>>4)-------7
===============================================================
Bitwise OR operator ( | )
===============================================================
truth table Bitwise OR operator ( | ):
------------------------------------------------------
Input1 Input2 Input1 | Input2
------------------------------------------------------
0 0 0
0 1 1
1 0 1
1 1 1
-----------------------------------------------------------
Examples:
----------------
>>>a=4------------------- 0 1 0 0
>>>b=3------------------- 0 0 1 1
--------------------------------------------
>>>c=a | b----------------- 0 1 1 1------result is 7
>>>print(c)-------------7
----------------------------------------------------------------
>>>a=15--------------------- 1 1 1 1
68
>>>b=14--------------------- 1 1 1 0
------------------------------------------------
>>>c=a|b-------------------- 1 1 1 1-----result is 15
>>>print(c)---------15
-----------------------------------------------------------------------
Special Examples:
-----------------------------
s1={10,20,30}
s2={30,40,50}
s3= s1 | s2 # s3=s1.union(s2)--10 20,30,40,50
>>>print(s3)-----{10,20,30,40,50}
>>> print({10,20,30}|{10,20,30,40})---------{20, 40, 10, 30}
0 1 0
1 0 0
1 1 1
-----------------------------------------------------------
Examples:
----------------
>>>a=4------------------- 0 1 0 0
>>>b=3------------------- 0 0 1 1
--------------------------------------------
>>>c=a & b----------------- 0 0 0 0---result 0
>>>print(c)------------- 0
>>>a=15--------------------- 1 1 1 1
>>>b=14--------------------- 1 1 1 0
------------------------------------------------
>>>c=a&b-------------------- 1 1 1 0-----result is 14
>>>print(c)---------14
>>> print(5&10)-----------0
--------------------------------------------------------------------
Special Examples:
-----------------------------
s1={10,20,30}
s2={30,40,50}
s3= s1 & s2 # s3=s1.intersection(s2)-- 30
print(s3)----{30}
-------------------------------------------------------------------------------------------------------
69
Example:
--------------
>>>a=10--------------- 1 0 1 0
NOTE:
----------------
Formula:-- ~n ===> - (n+1)
~ (-98)------> -(-98+1)
- (-97)==> 97
=============================================================
70
0 1 1
1 0 1
1 1 0
-----------------------------------------------------------
Examples:-
----------------
>>>a=4------------------ 0 1 0 0
>>>b=3------------------ 0 0 1 1
-------------------------------------------
>>>c=a^b--------------- 0 1 1 1 ------------Result is 7
>>>print(c)------7
71
Examples:-
---------------
>>>a=15--------------- 1 1 1 1
>>>b=14--------------- 1 1 1 0
-------------------------------------------------
>>>c=a^b------------- 0 0 0 1 --------------Result is 1
>>>print(c)------------ 1
-------------------------------------------------------------------------
Special Case:
--------------------
>>>s1={10,20,30,40}
>>>s2={30,40,50,60}
>>>s3=s1^s2----10 20 50 60 # or s3=s1.symmetric_difference(s2)
>>>print(s3)----{10,20,50,60}
-----------------------------------------------------------------------------------------------------
Special Case: Swapping Logic by using Bitwise XOR
---------------------
>>>a=4
>>>b=3
>>>print(a,b)------- 4 3
>>>a=a^b
>>>b=a^b
>>>a=a^b
>>>print(a,b)--------- 3 4
==========================================
Membership Operators
==========================================
=>Membership Operators are use for checking the existence of the specified value
in an object which contains multiple values like sequence type, list, set, dict
types etc.
=>We have two types of Membership Operators. they are
a) in
b) not in
a) in:
-------
Syntax:
value in sequence / list / set / dict
=>if the"value" present in sequence / list / set / dict objects then "in" operator returns
True otherwise it returns False.
b) not in:
---------------
Syntax:
value not in sequence / list / set / dict
=>if the"value" not present in sequence / list / set / dict objects then "not in"
operator returns True otherwise it returns False.
72
Examples:-
-----------------
>>> s="PYTHON"
>>> "HON" in s-----------True
>>> "HON" not in s----------False
>>> "hon" not in s--------True
>>> "hon" in s---------False
>>> "pon" in s----------False
>>> "PON" not in s--------True
>>> "ON" in s[::-1]--------False
>>> "NO" in s[::-1]---------True
>>> "NOP" in s[::-1]--------False
>>> "PON" in s[::-1]-------False
>>> tp=(10,"bipin",34.56,"MH")
>>> print(tp)----------(10, 'bipin', 34.56, 'MH')
>>> "bipin" not in tp---------False
>>> "bipin" in tp----------True
>>> "pin" in tp-----------False
>>> "pin" in tp[1]---------True
>>> "nip" in tp[::-1]----------False
>>> "nip" in tp[1][::-1]---------True
>>> "MH" in tp[2:4]--------True
>>> "HM" not in tp[2:4]--------True
=============================================================
=========================================
Identity Operators
=========================================
=>Identity operator are always used for comparing memory address (id()).
=>We have two types of Identity Operators .They are
1) is
2) is not
a) is:
---------
Syntax:- var1(or) val1 is var (or) val2
=>This "is" operator returns Ture provide both var1 and var2 contains Same Address
otherwise it returns False.
b) is not:
---------
Syntax:- var1(or) val1 is not var (or) val2
73
=>This "is not" operator returns Ture provide both var1 and var2 contains
Different Address otherwise it returns False.
>>> d1={10:"KVR",20:"Ramu"}
>>> d2={10:"KVR",20:"Ramu"}
>>> print(d1, id(d1))------------{10: 'KVR', 20: 'Ramu'} 1685664901888
>>> print(d2, id(d2))------------{10: 'KVR', 20: 'Ramu'} 1685664902080
>>> print(d1 is d2)---------False
>>> print(d1 is not d2)--------True
>>> fs1=frozenset([10,20,30])
>>> fs2=frozenset([10,20,30])
>>> print(fs1, id(fs1))---------frozenset({10, 20, 30}) 1685665249088
>>> print(fs2, id(fs2))---------frozenset({10, 20, 30}) 1685665249312
>>> print(fs1 is fs2)----------False
>>> print(fs1 is not fs2)---------True
>>> s1=set([10,20,30,40])
>>> s2=set([10,20,30,40])
>>> print(s1,id(s1))----------{40, 10, 20, 30} 1685665251104
>>> print(s2,id(s2))---------{40, 10, 20, 30} 1685665248640
>>> print(s1 is s2)-----------False
>>> print(s1 is not s2)-------True
>>> tp1=(10,"KVR","HYD")
>>> tp2=(10,"KVR","HYD")
>>> print(tp1,id(tp1))-----------(10, 'KVR', 'HYD') 1685665012160
>>> print(tp2,id(tp2))------------(10, 'KVR', 'HYD') 1685665236928
>>> print(tp1 is tp2)---------False
>>> print(tp1 is not tp2)-----------True
>>> l1=[10,"KVR"]
>>> l2=[10,"KVR"]
>>> print(l1,id(l1))--------[10, 'KVR'] 1685665011328
>>> print(l2,id(l2))----------[10, 'KVR'] 1685665011584
>>> print(l1 is l2)---------False
>>> print(l1 is not l2)---------True
>>> s1="KVR"
>>> s2="KVR"
>>> print(s1,id(s1))-----------KVR 1685665303344
>>> print(s2,id(s2))---------KVR 1685665303344
>>> print(s1 is s2)-------True
>>> print(s1 is not s2)-------False
>>> s3="KvR"
>>> print(s3,id(s3))---------KvR 1685665302768
>>> print(s1 is not s3)--------True
>>> print(s1 is s3)----------False
74
>>> r1=range(1,10)
>>> r2=range(1,10)
>>> print(r1,id(r1))-----------range(1, 10) 1685664407792
>>> print(r2,id(r2))---------range(1, 10) 1685665209824
>>> print(r1 is r2)----------False
>>> print(r1 is not r2)----------True
>>> ba=bytes([10,20,30])
>>> bb=bytes([10,20,30])
>>> print(ba, id(ba))--------b'\n\x14\x1e' 1685665207952
>>> print(bb, id(bb))-----b'\n\x14\x1e' 1685665209920
>>> print(ba is bb)-------False
>>> print(ba is not bb)---True
>>> ba=bytearray([10,20,30])
>>> bb=bytearray([10,20,30])
>>> print(ba, id(ba))---------bytearray(b'\n\x14\x1e') 1685665302640
>>> print(bb, id(bb))--------bytearray(b'\n\x14\x1e') 1685665302704
>>> print(ba is bb)-------False
>>> print(ba is not bb)-------True
>>> a=True
>>> b=True
>>> print(a, id(a))------True 140721665988712
>>> print(b, id(b))-------True 140721665988712
>>> print(a is b)----------True
>>> print(a is not b)--------False
>>> a=2+3j
>>> b=2+3j
>>> print(a, id(a))--------(2+3j) 1685665061360
>>> print(b, id(b))-------(2+3j) 1685665061296
>>> print(a is b)---------False
>>> print(a is not b)------True
>>> a=12.34
>>> b=12.34
>>> print(a, id(a))-------12.34 1685664581008
>>> print(b, id(b))------12.34 1685665060944
>>> print(a is b)------False
>>> print(a is not b)--------True
>>> a=10
>>> b=10
>>> print(a, id(a))-------10 1685663935056
>>> print(b, id(b))-------10 1685663935056
>>> print(a is b)-------True
>>> print(a is not b)-----False
>>> a=300
>>> b=300
75
===========================================
Flow Control (or) Control Structures in Python
===========================================
=>The purpose of Control Structures in Python is that "To perform certain operation
only once (X-Operation in the case of True or Y-Operation in the case of False )
only once (OR)
Perform certain operation repeatedly for finite number of times until condition is
False".
=>In Python programming, we have Three type Flow Control (or) Control Structures.
They are
a) Conditional (or) Selection (or) Branching Statements
b) Looping / Iterative / Repetitive Statements
c) MiSc flow control statements.
====================================================
a) Conditional (or) Selection (or) Branching Statements
====================================================
=>The purpose Conditional (or) Selection (or) Branching Statements "To perform
certain operation only once (X-Operation in the case of True or Y-Operation in the
case of False ) only once.
=>We have 3 Conditional (or) Selection (or) Branching Statements. They are
a) Simple if statement
b) if...else statement
c) if..elif..else statement
77
EXAMPLES:
==============================================
78
IF ELSE STATEMENT:
===========================================================
79
EXAMPLES :
#big1.py
a=int(input("Enter the first value:"))
b=int(input("Enter the second value:"))
c=int(input("Enter the third value:"))
if ( (a==b) and (b==c) ):
print("ALL VALUES ARE EQUAL:")
else:
big=a
if(b>big):
big=b
if(c>big):
big=c
print("biggest({},{},{})={}".format(a,b,c,big))
========================================================
#digitex1.py---with simple if statement
d=int(input("Enter a digit:"))
if (d==0):
print("ZERO")
if (d==1):
print("ONE")
if (d==2):
print("TWO")
if (d==3):
print("THREE")
if (d==5):
print("FIVE")
if (d==4):
print("FOUR")
if (d==6):
print("SIX")
if (d==9):
print("NINE")
if (d==8):
print("EIGHT")
if (d==7):
print("SEVEN")
if d not in range(0,10):
print("Its a number:")
80
81
IF ..ELIF…ELSE STATEMENT:
83
EXAMPLE :
#digitex3.py
d=int(input("Enter any digit:"))
if(d==0):
print("ZERO")
elif(d==1):
print("ONE")
elif(d==2):
print("TWO")
elif(d==3):
print("THREE")
elif(d==4):
print("FOUR")
elif(d==5):
print("FIVE")
elif(d==6):
print("SIX")
elif(d==7):
print("SEVEN")
elif(d==8):
print("EIGHT")
elif(d==9):
print("NINE")
else:
print("Its a number:")
print("Program finished its execution")
d=int(input("Enter any digit:"))
if(d==0):
print("ZERO")
elif(d==1):
print("ONE")
elif(d==2):
print("TWO")
elif(d==3):
print("THREE")
elif(d==4):
print("FOUR")
elif(d==5):
print("FIVE")
elif(d==6):
print("SIX")
elif(d==7):
print("SEVEN")
elif(d==8):
print("EIGHT")
elif(d==9):
print("NINE")
elif d not in range(1,10):
print("Its a number / -ve digit :")
print("Program finished its execution")
84
………………………………………………………………………………………………………………..
………………………………………………………………………………………………………………………..
85
EXAMPLE :
#disp.py
line=input("Enter a line of text:")
i=0
lst=['a','e','i','o','u']
while(i<len(line)):
if(line[i]==" "):
print(" is a space")
else:
if(line[i] in lst):
print("Vowel:{}".format(line[i]))
if(line[i] not in lst):
print("Consonant:{}".format(line[i]))
i=i+1
……………………………………………………………………………………………………………………………………
#numgen1.py
n=int(input("Enter a number:"))
if (n<=0):
print("{} is invalid input:".format(n))
else:
i=1
print("-"*50)
print("Numbers within:{}".format(n))
print("-"*50)
while(i<=n):
print("\t{}".format(i))
i=i+1
else:
print("*"*50)
………………………………………………………………………………………………………………………………………
#program for generating mul table
#multab.py
n=int(input("Enter a number:"))
if (n<=0):
print("{} is invalid input:".format(n))
else:
print("="*50)
print("Mul table for : {}".format(n))
print("="*50)
i=1
while(i<=10):
print("\t{} x {}={}".format(n,i,n*i))
i=i+1
else:
print("="*50)
86
#digsum.py
n=int(input("Enter a number:"))
if(n<0):
print("{} is invalid input:".format(n))
else:
s=0;
while(n>0):
r=n%10
s=s+r
n=n//10
else:
print("Digits sum={}".format(s))
……………………………………………………………………………………………………………………………
#chargen.py
line=input("Enter a line of text:")
for val in line:
print(val, end=" ") # p y t h o n
else:
print()
print("=================(OR========")
#with while loop
i=0
while(i<len(line)):
print(line[i],end=" ")
i=i+1
else:
print()
print("====================")
87
#sumavg.py
n=int(input("Enter How Many Numbers u Have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
l=()
print("Enter {} values:".format(n))
for i in range(1,n+1):
val=float(input())
l.append(val)
else:
print("-"*40)
print("Given List Elements:{}".format(l))
print("-"*40)
s=0
for val in l:
s=s+val
else:
print("="*50)
print("Sum={}".format(s))
print("Avg={}".format(s/len(l)))
print("="*50)
……………………………………………………………………………………………………………………………………………….
#sortnames.py
nn=int(input("Enter How many names u want to sort:"))
if(nn<=0):
print("{} is invalid input:".format(nn))
else:
lst=list()
for i in range(1,nn+1):
name=input("Enter {} Name:".format( i ))
lst.append(name)
else:
print("="*50)
print("Given Names in Original Order:")
print("="*50)
for name in lst:
print(name)
else:
print("="*50)
#sorting logic---in ASC Order
lst.sort()
print("Given Names in ASC Order:")
print("="*50)
for name in lst:
print(name)
print("="*50)
#sorting logic---in DESC Order
lst.sort(reverse=True)
print("Given Names in DESC Order:")
print("="*50)
for name in lst:
print(name)
print("="*50)
88
===================================
break statement
===================================
=>break is one the keyword
=>break statement is used for terminating the execution of
loop and comes out of loop and PVM exeutes other statements
which are written after looping statement.
=>Syntax1:-
------------
while (test cond1):
------------------
if (test cond-2):
break
--------------------
-----------------------------------
other statements in Program
------------------------------------------
=>Syntax2:-
------------
for varname in iterable-object
------------------
if (test cond-2):
break
--------------------
-----------------------------------
other statements in Program
------------------------------------------
Examples:
----------------
s="PYTHON"
for val in s:
if(val=='O'):
break
else:
print("\t{}".format(val))
print("Program finished")
…………………………………………………………………………………………………………………………………
#breakex.py
s="PYTHON"
for val in s:
if(val=='O'):
break
else:
print("\t{}".format(val))
print("Program finished")
89
#breakex1.py
lst=[10,20,30,40,50,60,70]
for val in lst:
if(val==50):
break
print(val)
print("Other statements in program")
………………………………………………………………………………………………………………………………………………………
#studmarksreport.py
#validation of student number
while(True):
sno=int(input("Enter Ur Roll Number(100-200):"))
if((sno>=100) and (sno<=200)):
break
#validation of name
sname=input("Enter Student Name:")
#Validation of Marks in C
while(True):
cm=int(input("Enter Marks in C(0-100):"))
if((cm>=0) and (cm<=100)):
break
#Validation of Marks in CPP
while(True):
cppm=int(input("Enter Marks in CPP(0-100):"))
if((cppm>=0) and (cppm<=100)):
break
#Validation of Marks in PYTHON
while(True):
pym=int(input("Enter Marks in Python(0-100):"))
if((pym>=0) and (pym<=100)):
break
#calulate total marks and percantage of marks
totmarks=cm+cppm+pym
percentmarks=(totmarks/300)*100
#decide the grade
if ((cm<40) or (cppm<40) or(pym<40)):
grade="FAIL"
else:
if( (totmarks>=250) and (totmarks<=300) ):
grade="DISTINCTION"
if( (totmarks>=200) and (totmarks<=249) ):
grade="FIRST"
if( (totmarks>=150) and (totmarks<=199) ):
grade="SECOND"
else:
if( (totmarks>=120) and (totmarks<=149) ):
grade="THIRD"
print("\tS t u d e n t M a r k s R e p o r t:")
print("*"*50)
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Mrks in C:{}".format(cm))
print("\tStudent Marks in CPP:{}".format(cppm))
print("\tStudent Marks in Python:{}".format(pym))
print("-"*50)
print("\tStudent Total Marks:{}".format(totmarks))
print("\tStudent Percentage of Marks:{}".format(percentmarks))
print("\tStudent Grade:{}".format(grade))
print("*"*50)
………………………………………………………………………………………………………………………………………………………
#studmarksreport1.py
#validation of student number
while(True):
while(True):
sno=int(input("Enter Ur Roll Number(100-200):"))
if((sno>=100) and (sno<=200)):
break
#validation of name
sname=input("Enter Student Name:")
#Validation of Marks in C
while(True):
cm=int(input("Enter Marks in C(0-100):"))
if((cm>=0) and (cm<=100)):
break
#Validation of Marks in CPP
while(True):
cppm=int(input("Enter Marks in CPP(0-100):"))
if((cppm>=0) and (cppm<=100)):
break
#Validation of Marks in PYTHON
while(True):
pym=int(input("Enter Marks in Python(0-100):"))
if((pym>=0) and (pym<=100)):
break
#calulate total marks and percantage of marks
totmarks=cm+cppm+pym
percentmarks=(totmarks/300)*100
#decide the grade
if ((cm<40) or (cppm<40) or(pym<40)):
grade="FAIL"
else:
if( (totmarks>=250) and (totmarks<=300) ):
grade="DISTINCTION"
if( (totmarks>=200) and (totmarks<=249) ):
grade="FIRST"
if( (totmarks>=150) and (totmarks<=199) ):
91
grade="SECOND"
else:
if( (totmarks>=120) and (totmarks<=149) ):
grade="THIRD"
===================================================
Continue statement
===================================================
=>continue is one of the keyword
=>The purpose of continue statement is that to make control to top of
the loop for that current iteration without executing the following
statement writtng after continue statement
Syntax1:-
--------------
while(Test cond1):
--------------------
--------------------
if(Test cond2):
---------------
continue
---------------
statements written - after continue statement
--------------------------------------------------------
--------------------------------------------------------
Syntax2:-
--------------
for varname in iterable-object
--------------------
--------------------
if(Test cond):
---------------
continue
---------------
statements written - after continue statement
--------------------------------------------------------
--------------------------------------------------------
92
EXAMPLES:
#continuestex1.py
s="PYTHON"
for val in s:
if(val=="O"):
continue
print("\t{}".format(val))
print("-"*50)
for val in s:
if(val=="Y") or (val=="O"):
continue
print("\t{}".format(val))
……………………………………………………………………………………………………………………………………………………..
#continuestex2.py
lst=[10,-25,-31,40,-53,61,-76,-83,90,100]
for element in lst:
if(element==30) or (element==60) or(element==90) :
continue
print("\t{}".format(element))
…………………………………………………………………………………………………………………………………………………………
93
===================================================
Nested Loops (or) Inner Loops in Python
===================================================
=>The process of defining one loop inside of another loop is called
Inner Loops or nested loops.
=>For Every value of Outer loop , Inner loop will execute multiple
time until inner loop condition False.
Syntax1:-
for var1 jn Iterbale-obj1: # outer for loop
-----------------------------
for var2 in Iterable-obj2: # inner for loop
--------------------------
----------------------------------
-------------------------------------------
Syntax2:
while (Test Cond1): # outer while loop
---------------------
while(test cond2): # inner while loop
--------------------
--------------------------
---------------------------------
Syntax3:-
for var1 jn Iterbale-obj1: # outer for loop
-----------------------------
while(test cond2): # inner while loop
--------------------
--------------------------
-------------------------------------------
Syntax4:
while (Test Cond1): # outer while loop
---------------------
for var2 in Iterable-obj2: # inner for loop
--------------------------
--------------------------------
EXAMPLES:
#innerloopex1.py
for i in range(1,4):
print("-"*50)
print("Val of i={}".format(i))
print("-"*50)
for j in range(1,6):
print("\tj={}".format(j))
print("coming out of inner for loop")
print("coming out of outer for loop")
94
#innerloopex2.py
for n in range(1,6):
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)
print("\nAll Tables Completed")
………………………………………………………………………………………………………………………………………………….
#innerloopex3.py
nn=int(input("Enter How many Mul tables u want:"))
if(nn<=0):
print("{} is invalid input:".format(nn))
else:
for n in range(1,nn+1):
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)
print("\nAll Tables Completed")
………………………………………………………………………………………………………………………………..
#innerloopex4.py
lst=[6,-4,19,0,25,-34,8,3]
for n in lst:
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)
print("\nAll Tables Completed")
95
#innerloopex5.py
lst=[6,-4,19,0,25,-34,8,3]
i=0
while(i<len(lst)):
if (lst[i]<=0):
print("{} is invalid input:".format(lst[i]))
else:
print("-"*50)
print("Mul table for:{}".format(lst[i]))
print("-"*50)
for j in range(1,11):
print("\t{} x {} = {}".format(lst[i],j, lst[i]*j))
else:
print("-"*50)
i=i+1
print("\nAll Tables Completed")
………………………………………………………………………………………………………………………………………………………………
#perfect.py
n=int(input("Enter any number:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*50)
print("Factors of {}".format(n))
print("-"*50)
s=0
for i in range(1,n//2+1):
if(n%i==0):
print("\t{}".format(i))
s=s+i
else:
print("-"*50)
if(s==n):
print("{} is Perfect:".format(n))
else:
print("{} is Not Perfect:".format(n))
print("-"*50)
96
#primex.py
n=int(input("Enter any number:"))
if(n<=1):
print("{} is invalid input:".format(n))
else:
result=True
for i in range(2,n):
if(n%i==0):
result=False
break
if( result ):
print("{} is prime:".format(n))
else:
print("{} is not prime:".format(n))
………………………………………………………………………………………………………………………………………………………………
#voterex1.py
age=int(input("Enter age of citizen:"))
if ((age>=18) and (age<=100)):
print("Citizen is eligible to Vote:")
else:
print("Citizen is not eligible to Vote:")
………………………………………………………………………………………………………………………………………………………………
#voterex2.py
while(True):
age=int(input("Enter Ur Correct Age:"))
if((age>=18) and (age<=100)):
break
#roman.py
n=int(input("Enter any number:")) #n= 2500
if(n<=0):
print("{} is invalid input:".format(n))
else:
while(n>=1000):
print("M",end="")
n=n-1000
if(n>=900):
print("CM",end="")
n=n-900
if(n>=500):
print("D",end="")
n=n-500
if(n>=400):
print("CD",end="")
n=n-400
while(n>=100):
print("C",end="")
n=n-100
if(n>=90):
print("XC",end="")
n=n-90
if(n>=50):
print("L",end="")
n=n-50
if(n>=40):
print("XL",end="")
n=n-40
while(n>=10):
print("X",end="")
n=n-10
if(n>=9):
print("IX",end="")
n=n-9
if(n>=5):
print("V",end="")
n=n-5
if(n>=4):
print("IV",end="")
n=n-4
while(n>=1):
print("I",end="")
n=n-
1………………………………………………………………………………………………………………………………………………………………
98
FUNCTIONS IN PYTHON
Index:
---------
=>Purpose of Functions
=>Definition of Functions
=>Parts of Functions
=>Phases in Functions
=>Advantages of Functions
=>Syntax for Defining a function
=>Approaches to Defined Functions
=>Arguments and parameters
=>Types of Arguments and parameters
a) Positional Parameters (or) Arguments
b) Default Parameters (or) Arguments
c)Variable Length Parameters(or) Arguments
d) Key word Parameters (or) Arguments
e) Key word Variable Length Parameters (or) Arguments
=>Programming Examples
=>Global Variables and Local Variables
=>global key word and global()
=>Anonymous Functions (or) Lambda Functions
=>Application of Anonymous Functions (or) Lambda
Functions
=>Special Functions in Python
(a) filter() with Normal Function and Anonymous
Functions
(b) map() with Normal Function and Anonymous
Functions
(c) reduce() with Normal Function and Anonymous
Functions
=>Programming Examples
99
============================================
Importance of Functions in Python
============================================
=>In Most of the Programming Languages , we use the concept of
FUNCTION.
=>The Purpose of Functions concept is that "To perform Certain
Operation and Provides Code Re-Usability"
===================================
Part of Functions
===================================
=>At time dealing with Functions development, we must ensure
there must exists Two parts. They are
a) Function Definition
b) Function Call(s)
=>For Every Function Call, There Must exists a Function
Definition otherwise we get "NameError"
=>For a Function Definition , there can exists one or more
Function Calls.
=>Function Definition will execute , when we call that
Function Definition otherwise Function Definition will not
execute.
Phases in Function
=>As we know that, Functions are meant for "Performing
Operations and code Re-usability", There must exists three
Phases. They are
1) Function Taking INPUT
2) Function PROCESS the Input
3) Function Gives OUTPUT / RESULT
102
===========================================================
Syntax for Defining the Function in Python
====================================================
Examples:-
-----------------
#approach1.py
#This program calculates a number and find its square using Functions
concept
def square( n ): # here 'n' is called formal Parameter
res=n*n
return res
#main program
x1=float(input("Enter a number:"))
res1=square(x1)
103
print("Square({})={}".format(x1,res1))
=====================================X=================================
Approach2:
-----------------
In This approach
=>We take INPUT in Function Definition
=>We do PROCESS in Function Definition
=>We Give OUTPUT to Function Definition
Examples:
---------------
#approach2.py
#This program calculates a number and find its square using
Functions concept
def square():
n=float(input("Enter a number:")) # input
res=n**2 # processing
print("Square({})={}".format(n,res)) # result
#main program
square()
=====================================X=================================
Approach3
-----------------
In This approach
=>We take INPUT from Function Call
=>We do PROCESS in Function Definition
=>We Give OUTPUT in Function Definition.
Examples:
----------------
#approach3.py
#This program calculates a number and find its square using
Functions concept
def square( n ):
res= n**2 # processing
print("Square({})={}".format(n,res)) # result
#main program
x=float(input("Enter a number:"))
square(x)
===================================X================================
Approach4
------------------
In This approach
=>We take INPUT in Function Definition
=>We do PROCESS in Function Definition
=>We Give OUTPUT to Function Call
104
Examples:
----------------
#approach4.py
#This program calculates a number and find its square using
Functions concept
def square():
x=float(input("Enter a number:")) #input
res=x**2
return x, res # In python , by using return
statement, we can return one or more values
#main program
n,res=square()
print("Square({})={}".format(n,res)) # result
print("===========OR===================")
kvr=square()
print("Square({})={}".format(kvr[0], kvr[1])) # result
……………………………………………………………………………………………………………………………
#big1.py
def findbig1():
a=float(input("Enter First value:"))
b=float(input("Enter Second Value"))
if(a==b):
return "All Values are equal"
else:
if (a>b):
return a
else:
return b
#main program
res=findbig1()
print("big={}".format(res))
………………………………………………………………………………………………………………………………………………………….
#big2.py
def findbig1():
a=float(input("Enter First value:"))
b=float(input("Enter Second Value"))
big=a if a>b else b
return a,b,big
#main program
res=findbig1()
if(res[0]==res[1]):
print("All Values are Equal")
else:
print("big({},{})={}".format(res[0],res[1],res[2]))
105
#main program
v1=int(input("Enter First Value:"))
v2=int(input("Enter Second Value:"))
r1,r2=swap(v1,v2)
print("Original Value1={}".format(v1))
print("Original Value2={}".format(v2))
print("Swapped Value1={}".format(r1))
print("Swapped Value2={}".format(r2))
………………………………………………………………………………………………………………………………………………….
#program for swapping two integers by using
functions with Bitwise Operator XOR ( ^ )
#swap2.py
def swap():
#input
v1=int(input("Enter First Value:"))
v2=int(input("Enter Second Value:"))
print("-"*50)
print("Original Value1={}".format(v1))
print("Original Value2={}".format(v2))
#processing
v1=v1^v2
v2=v1^v2
v1=v1^v2
print("Swapped Value1={}".format(v1))
print("Swapped Value2={}".format(v2))
print("-"*50)
#main program
swap()
106
============================================
Arguments and Parameters concept
============================================
Arguments:-
-------------------
=>Arguments are variables used in Function Calls and they are
also Global Variables
--------------------
Parameters:-
--------------------
=>Parameters are the variables used in Function Heading and
also called as "Formal Parameters"
=>Parameters are variables used in Function Body and They are
called Local Parameters (or) Local Variables.
==================================================
Argument (or) Parameter Passing Mechanisms
=================================================
=>Based on Arguments values are passing to Parameters from
Function call to Function Definition, the arguments (or)
Parameters are classified into 5 types.
==============================================
1) Positional Parameters (or) Arguments
==============================================
=>The concept of Positional Parameters (or) Arguments says
that The number of arguments values must be equal to the
number of formal parameters by ensuring Order and Meaning.
=>By default Function concept following Positional Parameters
(or) Arguments as Parameter passing mechanism.
--------------------------------------------------------------
-------------------------------------------
Examples:
-----------------
#posparamex1.py
def dispstuddet(stno,sname,marks,cname):
print("{}\t{}\t{}\t{}".format(stno,sname,marks,cname))
#main program
print("Number\tName\tMarks\tColl name")
dispstuddet(10,"Rossum",34.56,"NLU")
dispstuddet(12,"Ritche",44.56,"BLU")
dispstuddet(14,"Gosling",34.56,"SUN")
Result:
-------------
E:\KVR-PYTHON-11AM\FUNCTIONS>py posparamex1.py
Number Name Marks Coll name
10 Rossum 34.56 NLU
12 Ritche 44.56 BLU
14 Gosling 34.56 SUN
108
#posparamex1.py
def dispstuddet(stno,sname,marks,cname):
print("{}\t{}\t{}\t{}".format(stno,sname,marks,cname))
#main program
print("Number\tName\tMarks\tColl name")
dispstuddet(10,"Rossum",34.56,"NLU")
dispstuddet(12,"Ritche",44.56,"BLU")
dispstuddet(14,"Gosling",34.56,"SUN")
……………………………………………………………………………………………………………………………………………………………….
============================================
2) Default Parameters (or) Arguments
============================================
=>If we come across the common value for many function calls
and if we use Positional parameter mechanism then Program
takes more execution time bcoz the common values are
transfered from function calls to function definition every
time.
=>To overcome this problem, It is recommended to use default
Parameter mechanism. The advantage of Default Parameters is
that to represent common values for all Function calls.
#defaulparamex1.py
def dispstuddet(stno,sname,marks,crs="PYTHON",city="HYD"):
print("{}\t{}\t{}\t{}\t\t{}".format(stno,sname,marks,crs,city))
#main program
print("Number\tName\tMarks\tCourse name\tCity")
dispstuddet(10,"Ramu",34.56)
109
dispstuddet(11,"Rakesh",56.78)
dispstuddet(14,"Raju",33.33)
dispstuddet(13,"Atulya",83.33,"Java","MUMBAI")
#defaulparamex2.py
def show(a=1,b=2,c=3):
print(a,b,c)
#main program
show() # 1 2 3
show(10) # 10 2 3
show(10,20) # 10 20 3
show(10,20,30) # 10 20 30
show(c=100,a=200,b=300)
…………………………………………………………………………………………………………………………………………………………………
#argparamex.py
def mul(k,v,r):
d=k*v*r
print("Mul=",d)
#main program
a,b,c=10,20,30
addop(a,b,c) # here a,b,c are called arguments
………………………………………………………………………………………………………………………………………………………………
#listfunex1.py
def disp(obj):
print("-"*50)
for val in obj:
print("\t{}".format(val))
else:
print("-"*50)
def show(obj):
print("-"*50)
for k,v in obj.items():
print("\t{}--->{}".format(k,v))
else:
print("-"*50)
110
#main program
print("Elements of List:")
lst=[10,"Rossum","Python",45.67,True]
disp(lst)
print("Elements of Tuple:")
tpl=(12,"Ritche","C",88.88,False)
disp(tpl)
print("Elements of Set:")
s={13,"Gosling",45.67,True }
disp(s)
print("Elements of dict:")
d={"stno":10,"name":"Jim", "Marks":66.66,"cname":"NLU"}
show(d)
………………………………………………………………………………………………………………………………………………………………….
================================================
3) Key word Parameters (or) Arguments
===============================================
=>When we know the formal parameter names of any function and
if we don't know the order of parameters and if we pass the
data then we get In consistent Result. To overcome this
process , we must use the concept of Keyword arguments.
=>In other words, we know the formal parameter names of any
function and if we don't know the order of parameters and if
we pass the data accurately then we must use Keyword
arguments.
=>To implement Keyword arguments concept, we must take Formal
Parameter names as keys in function Call as arguments.
#kwdparamex1.py
def display(a,b,c):
print("{}\t{}\t{}".format(a,b,c))
#main program
print("a\tb\tc")
display(10,20,30)
display(b=20,c=30,a=10)
display(c=30,a=10,b=20)
display(b=20,a=10,c=30)
display(10,c=30,b=20)
#display(c=30,b=20,10) error
display(10,20,c=30)
……………………………………………………………………………………………………………………………………………………..
#kwdparamex1.py
def display(a,b,c):
print("{}\t{}\t{}".format(a,b,c))
#main program
print("a\tb\tc")
display(10,20,30)
display(b=20,c=30,a=10)
display(c=30,a=10,b=20)
display(b=20,a=10,c=30)
display(10,c=30,b=20)
#display(c=30,b=20,10) error
display(10,20,c=30)
…………………………………………………………………………………………………………………
#keywordparaex2.py
def dispempinfo(eno,ename,sal,dsg,cname="TCS"):
print("{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,cname))
#main program
print("Empno\tname\tsal\tdsg\tcname")
print("-"*50)
dispempinfo(10,"Rossum",3.4,"author","PSF")
dispempinfo(11,"Ritch",4.5,"author","BELL")
dispempinfo(12,"Ravi",2.3,"SE" )
dispempinfo(14,"NANI",4.3,"SE")
dispempinfo(15,"OMKAR",7.3,"Sr.SE")
dispempinfo(16,sal=3.4,dsg="TL",ename="Rasmi")
112
dispempinfo(cname="Wipro",eno=17,sal=3.4,ename="Prasad",dsg="H
R")
print("-"*50)
#main program
disp(10) # Function Call---(1)
disp(10,20) # Function call--(2)
disp(10,20,30) # Function call--(3)
113
#varlenparamex2.py
def disp(*param):# here *param is called Var len param and
whose type is tuple
print("-"*50)
for val in param:
print("\t{}".format(val), end=" ")
else:
print()
print("-"*50)
#main program
disp(10) # Function Call---(1)
disp(10,20) # Function call--(2)
disp(10,20,30) # Function call--(3)
disp(10,20,30,40) # Function call--(4)
disp("python","java","django","C") #---(5)
disp() #----(6)
………………………………………………………………………………………………………………….
#varlenparamex3.py
def addition (sname, *n, city="HYD",):
print("-"*50)
s=0
print("Name of the Student :{} and living in {}".format(sname,city))
for val in n:
print("\t{}".format(val))
s=s+val
else:
print("\tSum={}".format(s))
print("-"*50)
#main program
addition("Ravi",10)
addition("Omkar",10,12.34)
addition("Rs",10,12.34,23)
addition("DR",10,12.34,23,-12)
addition("JG",10,12.34,23,34.56,67.89)
addition("kvr")
#addition("Glfun",City="Bang",56,78,34,56) error
addition("Glfun",56,78,34,56, city="Bang")
114
================================================
5) Key word Variable length Parameters (or) Arguments
================================================
=>When we have family of similar Function calls with Key word
Variable number of values with normal python programming , we
must define Multiple Function Definitions and leads to more
development time.
=>To overcome this problem, we use the conept of Key word
Variable length Parameters (or) Arguments.
=>To Implement Key word Variable length Parameters (or)
Arguments, we must define single function definition
irrespective of family of Function calls by taking single
formal parameter preceded with a symbol double astrek (**) and
the formal parameter is called Key word Variable length
Parameter and whose type is dict.
……………………………………………………………………….
#kwdvarlenparamex1.py
def showinfo(**kwd):# here **kwd is of type <class, 'dict'>
print("-"*50)
for key,val in kwd.items():
print("\t{}-->{}".format(key,val))
else:
print("-"*50)
#main program
showinfo(frname="Mango")
showinfo(stno=10,sname="Rossum")
showinfo(eno=90,ename="Ritche",dsg="Author")
showinfo(fno=1,fname="KVR",sub1="PYTHON", sub2="JAVA")
115
#kwdvarlenparamex2.py
def findtotalmarks(sname,cls, **submarks):
print("-"*50)
print("Student Name:{}".format(sname))
print("Student Stuying in {}".format(cls))
print("-"*50)
print("\tSub Name\tSub Marks")
print("-"*50)
totmarks=0
for sn,sm in submarks.items():
print("\t{}\t\t{}".format(sn,sm))
totmarks=totmarks+sm
else:
print("-"*50)
print("\tTotal Marks:{}".format(totmarks))
print("-"*50)
#main program
findtotalmarks("rajesh","X",Eng=50,
Hindi=60,Maths=60,Sci=80,soc=89)
findtotalmarks("raju","XII",maths=50,phy=60,che=45)
findtotalmarks("bipin","B.Tech",C=50,Cpp=70,Python=60,Os=50)
findtotalmarks("Roosum","Research")
………………………………………………………………………………………………………
==========================================
Global Variables and Local Variables
==========================================
=>The purpose of Global Variables is that to Store Common
Values, which are used in all the function Definition.
=>Global Variables are those which are used before all the
function definitions.
=>Global Variable values can be accessed in all the functions
of same program.
#globallocalvarex1.py
city="HYD" # here city is global variable
def learnAI():
crs1="AI" # crs1 is called Local Variable
print("To Learn {} , we need {} Programming in {}
city".format(crs1,cl,city))
#print(crs2,crs3)----can't access
def learnML():
crs2="ML" # crs1 is called Local Variable
print("To Learn {} , we need {} Programming in {}
city".format(crs2,cl,city))
#print(crs1,crs3)----can't access
def learnDL():
crs3="DL" # crs1 is called Local Variable
print("To Learn {} , we need {} Programming in {}
city".format(crs3,cl,city))
#print(crs1,crs2)----can't access
#main program
cl="PYTHON" # here cl is global variable
learnAI()
learnML()
learnDL()
=====================================================================
Accessing the Global Variables inside of Function Definition
====================================================================
=>When we want to modify the global variables values inside of
function definition then the global variable values must be
referred (or) accessed w.r.t global keyword otherwise those
global variables are treated by PVM as Local Variables and
Gives UnboundLocalError
=>Syntax:-
----------------------------
var1=val1
var2=val2
--------------
var-n=val-n # here var1, var2...var-n are
called Global Variables
Examples:
-----------------
#GlobalVarModEx1.py
a=10 # global variable
def update1():
global a
print("Val of a(Global Variable) in side of
update1()={}".format(a)) #10
a=a+10
print("Val of a(Global Variable) in side of update1()
after Modi={}".format(a))# 20
def update2():
global a
a=a*10
print("Val of a(Global Variable) in side of update2()
after Modi={}".format(a))#200
#main program
print("Val of a in main program={}".format(a))#10
update1()
print("Val of a in main program after
update1()={}".format(a))#20
update2()
print("Val of a in main program after
update2()={}".format(a))#200
--------------------------------------------------------------
--------------------------------
Example:
--------------------------
#GlobalVarModEx2.py
a=10
b=20
def modify1():
#global a,b
print("val of a--global var={}".format(a)) # 10
print("val of b--global var={}".format(b)) # 20
a=a+10
b=b+10
print("val of a--global var after
modification={}".format(a)) # 20
print("val of b--global var after
modification={}".format(b)) # 30
#main program
modify1()
print("val of a--global var after modification in
main={}".format(a)) # 20
print("val of b--global var after modification in
main={}".format(b)) # 30
--------------------------------------------------------------
---------------------------------------------
118
=============================================
global Variables VS Local Variables with global()
=============================================
=>When we have global variable names and local variables on the same
name with different values in a python program with functions and if we
want to do any retrieving / accessing of global variables then we
must use global() otherwise PVM gives accessibility to local variables.
=>global() returns an object 'dict' and in which global variable names
are called Keys and Global Values are called Values.
Syntax:-
----------------------------
var1=val1
var2=val2
--------------
var-n=val-n # here var1, var2...var-n are called
Global Variables
def functionname():
---------------------------
var1=val11
var2=val22
--------------
var-n=val-nn # here var1, var2...var-n are
called local Variables
# retrieve the Global variables
globalval1=globals()['var1'] (or)
globals().get('var2')
globalval2=globals()['var2'] (or)
globals().get('var2')
-------------------------------------------------
---------------------------------
globalval-n=globals()['var-n'] (or)
globals().get('var-n')
………………………………………………………………………………………………………………………………………………………………..
Examples:
#localglobalVarsameEx1.py
a=11
b=20
c=30
d=40 # here 'a', 'b' , 'c' and 'd' are called Global
Variables
def calculate():
global c,d
c=c+10
d=d+10
a=100
b=200 # here 'a' and 'b' are called local Variables
print("Val of a(Local Var)={}".format(a))
print("Val of b(Local Var)={}".format(b))
print("Val of a(Global Var)={}".format(globals()['a']))
119
#main program
calculate()
==========================================================
#localglobalVarsameEx2.py
a=10
b=20
c=30
d=40 # here 'a', 'b' , 'c' and 'd' are called Global
Variables
def calculate():
hyd=globals()
for k,v in hyd.items():
print("{}----{}".format(k,v))
print("-------------------------------------------------
--")
print("Val of a=", hyd['a'])
print("Val of b=", hyd.get('b'))
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("sym={}".format(globals()['a']+globals()['b']+glob
als()['c']+globals()['d']))
#main program
calculate()
#localglobalVarsameEx3.py
a="Python"
b="Java"
def strconcat():
a=" is Functional and OOP Programming"
b=" is Only OOP Programming"
print("val of a--global={}".format(globals()['a']))
print("val of b--global={}".format(globals().get('b')))
print("val of a--local={}".format(a))
print("val of b--local={}".format(b))
print("-"*40)
print("result1={}".format(globals()['a']+a))
print("result2={}".format(globals()['b']+b))
#main program
strconcat()
120
===============================================
Anonymous Functions (or) Lambda Functions
===============================================
=>Anonymous Functions is one of the new Facility in Python
Programming
=>Anonymous Functions are those, which does not contains name
explicitly.
=>Anonymous Functions are used for Performing "Instant
Operations".
=>Instant Operations are those which are no longer to use but
used at that point time.
=>To develop Anonymous Functions, we use a key word called
lambda and Hence Anonymous Functions are called Lambda
Functions.
=>Anonymous Functions contains only one statement and it
returns the result automatically. (No need to use return
statement )
-------------------------------------------------------------
Syntax for defining Anonymous Functions:
--------------------------------------------------------------
varname= lambda params-list : expression
------------------
Explanation:
------------------
=>'varname' is one of the valid python variable name and it
acts as function name
=>lambda is key word used for developing or defining Anonymous
Functions
=>params-list represent set variable names used for holding
the input coming from function call.
=>expression represents an executable statement aqnd it
returns the value automatically
===============================X=============================
Example:
-------------------------------------------------------------
#anonyfunex1.py
def addop(a,b): # normal Function Def
c=a+b
return c
#main program
a=float(input("Enter First value:"))
b=float(input("Enter Second value:"))
res=addop(a,b)
print("sum={}".format(res))
print("=================OR============")
121
res=kvrop(a,b)
print("sum by using lambda={}".format(res))
res=kvrop("Python","Rossum")
print("sum by using lambda={}".format(res))
res=kvrop(True,False)
print("sum by using lambda={}".format(res))
res=kvrop(2+3j,3+9.5j) #
print("sum by using lambda={}".format(res))
#anonyfunex2.py
#main program
a=float(input("Enter First value:"))
b=float(input("Enter Second value:"))
res=big(a,b)
print("big({},{})={}".format(a,b,res))
==============================================================
#anonyfunex3.py
addop=lambda x,y:x+y
subop= lambda a,b:a-b
mulop= lambda a,b:a*b
#main program
a=float(input("Enter First value:"))
b=float(input("Enter Second value:"))
print("sum({},{})={}".format(a,b,addop(a,b)))
print("sub({},{})={}".format(a,b,subop(a,b)))
print("mul({},{})={}".format(a,b,mulop(a,b)))
==========================================================
#anonyfunex4.py
import sys
addop=lambda x,y:x+y
subop= lambda a,b:a-b
mulop= lambda a,b:a*b
divop=lambda x,y:x/y
modop= lambda a,b:a%b
expoop= lambda a,b:a**b
def readvalues(op):
x1=float(input("Enter First value for {}:".format(op)))
x2=float(input("Enter Second value for {}:".format(op)))
return x1,x2
#main program
while(True):
print("-"*50)
print("\tArithmetic Operations")
print("-"*50)
print("\t\t1.Addition")
122
print("\t\t2.Substraction")
print("\t\t3.Multiplication")
print("\t\t4.Division")
print("\t\t5.Modulas")
print("\t\t6.Exponent")
print("\t\t7.Exit")
print("-"*50)
ch=int(input("Enter Ur Choice:"))
if (ch==1):
a,b=readvalues("Additon")
print("sum({},{})={}".format(a,b,addop(a,b)))
elif (ch==2):
a,b=readvalues("Substraction")
print("sum({},{})={}".format(a,b, subop(a,b)))
elif (ch==3):
a,b=readvalues("Multipliucation")
print("mul({},{})={}".format(a,b, mulop(a,b)))
elif (ch==4):
a,b=readvalues("division")
print("div({},{})={}".format(a,b, divop(a,b)))
elif (ch==5):
a,b=readvalues("Modulas")
print("mod({},{})={}".format(a,b, modop(a,b)))
elif (ch==6):
a,b=readvalues("Exponent")
print("pow({},{})={}".format(a,b, expoop(a,b)))
elif (ch==7):
print("Thanks for using Cal App!")
sys.exit()
else:
print("Ur Choice of Operation is wrong, try
again")
a) filter()
b) map()
c) reduce()
123
=============================
filter()
=============================
=>This function is used for filtering the required elements
from given Iterable object by passing a function.
=>Explanation:
----------------------
=>varname is one object of <class,'filter'>, which containing
filtered elements and varname can be converted into any
collections data types(list,tuple,set,frozenset..etc)
=>Function-name can be either Normal Function definition or
anonymous Function def.
=>Iterable object an be any object contains multiple values.
=>The Execution behaviour of filter() is that Each element of
Iterbale-object sending to Specified Function-name. If the
Function-name returns True then that element will filtered .
if the Function returns False the that element will be
neglected.
=============================X================================
EXAMPLES:
=========
#filterex1.py----with normal functions--filter()
#This program filtering out the positive elements from given
list of elements
lst=[10,-23,45,0,56,-34,-45,12,56,90,-34,-6,-2,2]
resobj=filter(positive, lst)
print("Type of resobj:",type(resobj))
pslst=list(resobj)
print("Possitive Elements=",pslst)
print("--------------------------------------------------")
resobj=filter(negative,lst)
nslst=tuple(resobj)
print("Negative Elements=",nslst)
124
lst=[10,-23,45,0,56,-34,-45,12,56,90,-34,-6,-2,2]
pslst=list( filter(positiveop, lst) )
print("Possitive Elements=",pslst)
print("--------------------------------------------------")
nstpl=tuple(filter(negativeop,lst))
print("Negative Elements=",nstpl)
===========================================================
#filterex3.py----with anonymous functions--filter()
#This program filtering out the possitive elements from given
list of elements
lst=[10,-23,45,0,56,-34,-45,12,56,90,-34,-6,-2,2]
pslst=list( filter(lambda n: n>0, lst) )
print("Possitive Elements=",pslst)
print("--------------------------------------------------")
nstpl=tuple(filter(lambda n: n<0,lst))
print("Negative Elements=",nstpl)
#Filterex4.py
#program for reading the values dynamically by using list
comprehension and filter even and odd elements
print("Enter List of elements separated by comma")
lst = [int(x) for x in input().split(",") ]
evenlst=list(filter(evenop,lst))
oddlst=list(filter(oddop,lst))
print("Original Elements={}".format(lst))
print("Even Elements={}".format(evenlst))
print("Odd Elements={}".format(oddlst))
=========================================================
#listcomprehension.py
print("Enter Number of elements")
lst = [int(x) for x in input().split(",") }
print(lst)
125
======================================
map()
======================================
=>map() is used obtaining new Iterable object from existing
iterable object by passing a function with some logic
=>Syntax:-
objname=map(function-name, iterable-object)
Explnation:
-----------------
=>varname is one object of <class,'map'>, which containing new
elements and varname can be converted into any collections
data types(list,tuple,set,frozenset..etc)
=>Function-name can be either Normal Function definition or
anonymous Function def.
=>The Execution behaviour of map() is that each element of
iterable-object is passing to specified function, processing
that element based condition and returned to new iterable
object.
EXAMPLES:
……………………
#mapex1.py
def square(n):
return n**2
#main program
lst1=[2,3,4,5,6]
obj=map(square, lst1)
sqlst=list(obj)
print("Original List:{}".format(lst1))
print("Square List={}".format(sqlst))
#mapex2.py
lst1=[2,3,4,5,6]
sqlst=list(map(lambda n : n**2, lst1))
print("Original List:{}".format(lst1))
print("Square List={}".format(sqlst))
#mapex3.py
def dispsal(obj):
for sal in obj:
print("\t{}".format(sal))
def show(on):
for old,nw in on:
print("{}\t\t{}".format(old,nw))
#main program
print("Enter Salaries of employees:")
oldsallist=[ float(x) for x in input().split() ]
newsallist=list(map(lambda sal:sal+sal*0.05, oldsallist))
print("Old sal list={}".format(oldsallist))
print("new sal list={}".format(newsallist))
126
print("-------------------OR----------------------------")
print("Old Salaries of employee")
dispsal(oldsallist)
print("New Salaries of employee")
dispsal(newsallist)
print("-------------------OR----------------------------")
oldnew=zip(oldsallist,newsallist)
print("Old Salary\tNew Salary")
show(oldnew)
#mapex4.py
lst1=[10,20,30,40]
lst2=[1,2,3,4]
lst3=[100,200,300,400]
lst4=list(map(lambda a,b,c:a+b+c, lst1,lst2,lst3))
print(lst1)
print(lst2)
print(lst3)
print(lst4)
#mapex5.py
lst1=[10,20,30,40,50,60,70]
lst2=[1,2,3,4]
lst3=[100,200]
lst4=list(map(lambda a,b,c:a+b+c, lst1,lst2,lst3))
print(lst1)
print(lst2)
print(lst3)
print(lst4
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
---------------------------------------
Internal Flow of reduce()
---------------------------------------
step-1:- reduce() selects two First values int place them First var
and Second var
step-2:- The function-name utilizes the values First var and Second
var applied to the specified logic and obtains the result
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
--------------------------------------------------------------------
--
=>The reduce() belongs to a pre-defined module called" functools".
127
#reduceex1.py
import functools
print("Enter List of values separated by Space")
lst=[ int (x) for x in input().split()]
big=functools.reduce(lambda a,b:a if a>b else b, lst)
small=functools.reduce(lambda k,v : k if k<v else v, lst)
print("\nOriginal values:{}".format(lst))
print("Biggest Value={}".format(big))
print("Smallest Value={}".format(small))
#reduceex2.py
import functools
print("Enter List of values separated by Space")
lst=[ int (x) for x in input().split()]
sumres=functools.reduce(lambda a,b:a+b, lst)
print("\nOriginal values:{}".format(lst))
print("Sum ={}".format(sumres))
print("Avg ={}".format(sumres/len(lst)))
#reduceex3.py
import functools
print("Enter List of Words separated by Space")
lst=[ str(x) for x in input().split()]
# Or lst=["python","java","Django","Oracle"]
line=functools.reduce(lambda a,b:a+" "+b, lst)
print("\nOriginal Words:{}".format(lst))
print("Line of Text={}".format(line))
128
===================================
Introduction and Types of Modules
===================================
=>We know that Functions concept makes us understand how to
perform the operations and How re-use the function code within
the same program. But Functions concept unable to provided re-
usability across the Programs.
=>To re-use the code across the program, In Python we have a
concept called MODULES.
=>The purpose of Modules is that "To Re-use the code across
the Programs ".
=>Definition of Module:
-------------------------------------
=>A Module is a collection of Variables, Functions and
Classes.
--------------------------------------------------------------
Types of Modules:
---------------------------
=>In Python, we have two types of Modules. They are
a) Pre-defined (or) Built-in Modules
b) Programmer (or) user (or) Custom-defined Modules
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#SE.py
import simpleint====➔#
from simpleint import simpleintformula===➔*
#main program
simpleint.simpleintformula()=====➔#
(or)
Simpleintformula()=====➔*
===========================================================
Creating a module in python
=====================================
Step-1:- Define the common variables, Functions and
classes in a Editor
Step-2:- Save the Above Editor Code on some file name with
an extension. py (FileName.py)
Example1:
-----------------
#simpleint.py----File Name and It it treated as Module
Name(simpleint.pyc)
#program for cal simple interest
def simpleintformula():
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
#calculate
si=(p*t*r)/100
totamt=p+si
print("Simple Interest: {}".format(si))
print("Total Amount to pay: {}".format(totamt))
----------------------------------------------------------------------
#mathsinfo.py----file name and treated as module---(mathsinfo.pyc)
PI=3.14
E=2.71
A=34
-----------------------------------------------------------------------
130
==============================================================
Re-Using the Modules
==============================================
=>Re-Using the Modules in python is nothing but accessing the
variables , Functions and classes across the program
=>We have two Techniques for Re-Using the Modules. They are
a) by using import statement
b) by using from....import statement.
--------------------------------------------------------------
a) by using import statement:
---------------------------------------------
=>import is one the keyword in python
=>import statement is used for re-using the variables,
functions and classes across the programs.
=>when we import with this approach, the current python can
access the variables, functions and classes w.r.t module name
otherwise we get SyntaxError.
modulename.variable name
modulename.function name
modulename.class name
--------------------------------------------------------------
Syntax1 for importing a single module:
--------------------------------------------------------------
import module name
------------------------------------------------------------
Syntax2 for importing multipleModules
------------------------------------------------------------
import module name1,module name-2,...module name-n
--------------------------------------------------------------
-----------------------
Syntax3 for importing a single module with alias name:
--------------------------------------------------------------
-------------------
import module name as alias name
131
--------------------------------------------------------------
Syntax1 for importing a single module:
--------------------------------------------------------------
from module name import Variable Name, Function name, class
name
--------------------------------------------------------------
Syntax2 for importing a single module with alias names
--------------------------------------------------------------
-
from module name import Variable Name as alias name, Function
name as lias name, class name as alias name
--------------------------------------------------------------
--------------------------
Syntax3 for importing a single module with all
--------------------------------------------------------------
from module name import *
===============================X=======================
EXAMPLES:
#java.py
fname="KVR"
def teach():
print("KVR Teaches JAVA")
=========================================================
#python.py
fname="KVR"
def teach():
print("KVR Teaches PYTHON")
#course.py
from python import teach as t , fname as f
from java import teach as s, fname as j
print("Python Faculty:{}".format(f))
t()
print("Java Faculty:{}".format(j))
s()
132
EXAMPLE 2:
----------
#aopmenu.py
def menu():
print("="*50)
print("A r i t h m e t i c O p e r a t i o n")
print("="*50)
print("\t1.Addition")
print("\t2.Substraction")
print("\t3.Multiplication")
print("\t4.Division")
print("\t5.Modulas")
print("\t6.Exponent")
print("\t7.Exit")
print("="*50)
-----------------------------------------------------
#aopoperations.py
def addop():
a=float(input("Enter First Value for Addition"))
b=float(input("Enter Second Value for Addition"))
print("sum({},{})={}".format(a,b,a+b))
def subop():
a=float(input("Enter First Value for Subtraction"))
b=float(input("Enter Second Value for Subtraction"))
print("sub({},{})={}".format(a,b,a-b))
def mulop():
a=float(input("Enter First Value for Multiplication"))
b=float(input("Enter Second Value for Multiplication"))
print("mul({},{})={}".format(a,b,a*b))
def divop():
a=float(input("Enter First Value for Division"))
b=float(input("Enter Second Value for Division"))
print("div({},{})={}".format(a,b,a/b))
print("floor div({},{})={}".format(a,b,a//b))
def modop():
a=float(input("Enter First Value for Modulas"))
b=float(input("Enter Second Value for Modulas"))
print("mod({},{})={}".format(a,b,a%b))
def expoop():
a=float(input("Enter Base"))
n=float(input("Enter Power"))
print("pow({},{})={}".format(a,n,a**n))
-------------------------------------------------------
133
#aopdemo.py
import sys
from aopmenu import menu
from aopoperations import addop,subop,mulop,divop,modop,expoop
while(True):
menu()
ch=int(input("Enter Ur Choice:"))
if(ch==1):
addop()
elif(ch==2):
subop()
elif(ch==3):
mulop()
elif(ch==4):
divop()
elif(ch==5):
modop()
elif(ch==6):
expoop()
elif(ch==7):
print("Thanks for this calculator Program!")
sys.exit()
else:
print("Ur Choice 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
a) create a package:
----------------------------
=>To create a package, we use the following steps.
i) create a Folder
ii) place / write an empty python file called __init__.py
iii) place / write the module(s) in the folder where is it IS
considered as Package Name
Example:
--------------
bank <-----Package Name
-----------
__init__.py <----Empty Python File
simpleint.py <--- Module Name
mathsinfo.py <--- Module Name
========================================================
b) re-use the package
---------------------------------
=>To the re-use the modules of the packages across the
folders / drives / environments, we have to two approaches.
They are
i) By using sys module
ii)by using PYTHONPATH external Variables
--------------------------------------------------------------
i)By using sys module:
-------------------------------------
Syntax:
----------- sys.path.append("Absolute Path of Package")
Example:
sys.path.append("E:\\KVR-PYTHON-11AM\\ACKAGES\\BANK")
--------------------------------------------------------------
ii)by using PYTHONPATH Enviromental Variables:
--------------------------------------------------------------
=>PYTHONPATH is one of the Enviromental Variable
Steps for setting PYTHONPATH=E:\KVR-PYTHON-11AM\PACKAGES\BANK
--------------------------------------------------------------
135
==============================================================
EXAMPLES:
=========
1)
divop()
elif(ch==5):
modop()
elif(ch==6):
expoop()
elif(ch==7):
print("Thanks for this calculator Program!")
sys.exit()
else:
print("Ur Choice of Operation is wrong--try
again")
#Programme.py
#main program
import sys
sys.path.append("E:\KVR-PYTHON-11AM\PACKAGES\AOP")
from casestudy import mycasestudy as m
m()
===========================================
2)
#Programmer1.py
import sys
#sys.path.append("E:\\KVR-PYTHON-11AM\\PACKAGES\\BANK")
import simpleint
simpleint.simpleintformula()
===============OR====================
#Programmer2.py
import simpleint
simpleint.simpleintformula()
137
===============================================
Introduction to exception handling
==============================================
=>The purpose of exception handling is that "To develop Robust
Applications".
=>In real time, when we develop any project , we need to use
certain programming and by using that programming language we
develop, compile and execute certain programs. During this
development, Compilation and execution, we get 3 types of
errors. They are
a) Compile time errors.
b) Logical Errors
c) Runtime Errors.
3) Definition of exception:-
-----------------------------------
=>Runtime error(s) of a program is called Exception(s)
(Invalid Input----->Runtime Error---->Exception)
=>Every Invalid Input is considered as Exception.
4) All exceptions by default generates Technical error
messages
================================X=============================
Handling the exception in python
========================================
=>Handling the exception in python are nothing but converting
Technical Error Messages into User-friendly error messages.
=>To convert Technical Error Messages into User-friendly error
messages, In python we have 5 keywords. They are
a) try
b) except
c) else
d) finally
e) raise.
-----------------------------------------------------
Syntax for handling the exceptions:
-----------------------------------------------------
try:
------------------------------
block of statements
generating exceptions
-------------------------------
except exception-class-name-1:
----------------------------------------
Block of stements-generates
User_Friendly error Messages
-----------------------------------------
except exception-class-name-2:
----------------------------------------
Block of stements-generates
User_Friendly error Messages
-----------------------------------------
except exception-class-name-n:
----------------------------------------
Block of stements-generates
User_Friendly error Messages
-----------------------------------------
else:
----------------------------------------
Block of statements--Recommended
to display Results
----------------------------------------
finally:
--------------------------------------
Block of statements--executes compulsorily
--------------------------------------
140
EXAMPLES:
---------
#Program for cal divsion of two number by accepting from KBD.
#Div1.py
print("Program Execution Started...")
a=input("Enter First Value:")
b=input("Enter Second Value:")
x1=int(a) # exception generated statement--ValueError
x2=int(b)# exception generated statement--ValueError
x3=x1/x2 # exception generated statement--ZeroDivsionError
print("First Val=",x1)
print("Second Val=",x2)
print("Div =",x3)
print("Program Execution Ended...")
=============================================
#Program for cal divsion of two number by accepting from KBD.
#Div2.py
try:
print("Program Execution Started...")
a=input("Enter First Value:")
b=input("Enter Second Value:")
x1=int(a) # exception generated statement--ValueError
x2=int(b)# exception generated statement--ValueError
x3=x1/x2#exception generated statement--ZeroDivsionError
except ZeroDivisionError:
print("\nDon't enter Zero for Den...")
except ValueError:
print("\nDon't enter strs / alpha-numerics / Special
Symbols")
else:
print("First Val=",x1)
print("Second Val=",x2)
print("Div =",x3)
finally:
print("Program execution completed!")
===============================================
#Program for cal divsion of two number by accepting from KBD.
#Div3.py
try:
print("Program Execution Started...")
a=input("Enter First Value:")
b=input("Enter Second Value:")
x1=int(a) # exception generated statement--ValueError
x2=int(b)# exception generated statement--ValueError
x3=x1/x2#exception generated statement--ZeroDivsionError
141
============================================================
Explanation for keywords of handling the exceptions
============================================================
1) try:
---------
=>It is the block, in which we write block of statements
generating exceptions. In other words, what are all the
statements generating exceptions, they must written inside of
try block and hence try block is called exception monitoring
block.
=>If any exception occurs in try block then PVM comes out of
try block and execute appropriate except block and gives user-
friendly error messages.
=>After executing appropriate except block, PVM control never
goes to try block to execute rest of the statements.
=>Every try block must be immediately followed by except block
( Intermediate statements are not allowed between try and
except blocks)
=>Every try block must contain at least one except block and
recommended to write multiple except blocks for generating
multiple user-friendly error messages.
--------------------------------------------------------------
---------------------------------------------------
2) except :
-------------------
=>It is this block, in which we write block of statements
generates User-friendly error messages. In other words, except
block supresses the technical error messages and generates
user friendly error messages and hence except block is called
exception processing block.
Note:- handling the exception= try block +except block
=>except block will execute provided when the exception occurs
in try block.
=>even though we write multiple except blocks, at any point
time, PVM will execute only appropriate except block depends
on type of exception occurs in try block.
=>The place of writing except block is after try block.
--------------------------------------------------------------
-----------------------------------
142
3) else:
---------------
=>This is the block, in which we write block of statements and
they always recommended to gives results and hence it is
called result generated block
=>else will block will execute when there is no exception
occurs in try block.
=>writing else block is optional
=>The place of writing else block is after except block.
--------------------------------------------------------------
----------------------------------
4) finally:
-------------
=>It is the block, in which we write block of statements,
which are relinquishing(close / release / clean-up ) the
resources ( files / databases ) which are obtained in try
block.
Form1:
----------
try:
--------------
--------------
except exception-class-name-1:
-----------------------------------------
User-friendly error messages
-----------------------------------------
==============================================================
Form2: (Multi except exception handling block)
----------
try:
--------------
--------------
except (exception-class-name-1,exception-class-name-
2...exception-class-name-n:
-----------------------------------------
User-friendly error messages
-----------------------------------------
==============================================================
143
--------------------------------------------------------------
----------------------------------------------
Steps for developing programmer-defined exceptional classes
--------------------------------------------------------------
----------------------------------
1) Choose the programmer-defined class name
2) The Programmer defined must inherit the properties of
Exception / BaseException . Hence The Programmer-defined
class becomes programmer-defined exception sub class
class PinError(Exception):pass
144
class KvrDivisionError(Exception):pass
=================================================
raise key word
=================================================
=>raise keyword is used for hitting / raising / generating the
exception provided some condition must be satisfied.
=>Syntax:- if (Test Cond):
raise <exception-class-name>
Examples:
-------------------
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError
else:
return (a,b,a/b)
145
SOME EXAMPLES(FORM-4):
#Program for cal divsion of two number by accepting from KBD.
#alias.py
try:
print("Program Execution Started...")
a=input("Enter First Value:")
b=input("Enter Second Value:")
x1=int(a) # exception generated statement--ValueError
x2=int(b)# exception generated statement--ValueError
x3=x1/x2#exception generated statement--ZeroDivsionError
except ZeroDivisionError as z:# here z contains "division by
zero"
print(z)
except ValueError as v:
print(v)
except :
print("exception occured")
else:
print("First Val=",x1)
print("Second Val=",x2)
print("Div =",x3)
finally:
print("Program execution completed!")
=========================================================
CASE-2(EXAMPLE):
#invalidinput.py----File name and Treated as Module name
# here we are developping programmer-defined exception
class InvalidInputError(BaseException):pass
class LoginError(Exception):pass
========================================================
#multable.py-----File Name and treated as Module name
from invalidinput import InvalidInputError
def table():
n=int(input("Enter a number for generating mul table:"))
if(n<=0):
raise InvalidInputError # hitting the exception
else:
print("-"*40)
print("Mul Table for {}".format(n))
for i in range(1,11):
print("{} x {}={}".format(n,i,n*i))
else:
print("-"*40)
=============================================
146
#muldemo.py
from invalidinput import InvalidInputError
from multable import table
try:
table()
except ValueError:
print("Don't enter strs, alpha-numerics and special
symbols")
except InvalidInputError:
print("Don't enter -ve / zero Value:")
======================================================
#login.py
from invalidinput import InvalidInputError,LoginError
from multable import table
def mullogin(un,pw):
if((un=="python") and ( pw=="hyd")):
try:
table()
except ValueError:
print("Don't enter strs, alpha-
numerics and special symbols")
except InvalidInputError:
print("Don't enter -ve / zero
Value:")
else:
raise LoginError
=================================
#authentication.py
from login import mullogin
from invalidinput import LoginError
un=input("Enter Ur User Name:")
pw=input("Enter Ur Password:")
try:
mullogin(un,pw)
except LoginError:
print("\nLogin Denied--user Name / pwd is wrong")
147
ATM APPLICATION:
#atmmenu.py---file name and treated as module name
def menu():
print("-"*40)
print("\tATM Operations")
print("-"*40)
print("\t1.Deposit:")
print("\t2.Withdraw")
print("\t3.Bal Enq..")
print("\t4.Exit")
print("-"*40)
===================================================
#bankexcep.py
class DepositError(Exception):pass
class WithdrawError(Exception):pass
class InSuffFundError(BaseException):pass
#bankoperations.py
from bankexcep import
DepositError,WithdrawError,InSuffFundError
bal=500.00 #global variable
def deposit():
global bal
damt=float(input("Enter How much amount u want to
deposit:"))#ValueError
if(damt<=0):
raise DepositError
else:
bal=bal+damt
print("\nur Account xxxxxx123 credited with
INR:{}".format(damt))
print("Ur Acoount Bal INR:{}".format(bal))
def withdraw():
global bal
wamt=float(input("Enter How much amount u want to
withdraw:")) #ValueError
if(wamt<=0):
raise WithdrawError
elif(wamt+500>bal):
raise InSuffFundError
elif(wamt<=bal):
bal=bal-wamt
print("\nur Account xxxxxx123 Debited with
INR:{}".format(wamt))
print("Ur Acoount Bal INR:{}".format(bal))
def balenq():
print("Ur Acoount Bal INR:{}".format(bal))
148
#atmdemo.py---main program
from atmmenu import menu
from bankexcep import DepositError,WithdrawError,InSuffFundError
from bankoperations import deposit,withdraw,balenq
import sys
while(True):
try:
menu()
ch=int(input("Enter Ur Choice:"))
if(ch==1):
try:
deposit()
except DepositError:
print("Don't Try to deposit -ve / zero
Values:")
except ValueError:
print("Don't enter strs / special
symbols and alpha-numerics for deposits")
elif(ch==2):
try:
withdraw()
except WithdrawError:
print("Don't Try to Withdraw -ve / zero
Values:")
except InSuffFundError:
print("U don't have sufficient Funds!")
except ValueError:
print("Don't enter strs / special
symbols and alpha-numerics for withdarw")
elif(ch==3):
balenq()
elif(ch==4):
print("Thanks for using this ATM:")
sys.exit()
else:
print("Ur Choice of Operation is wrong--try
again")
except ValueError:
print("Don't enter strs / special symbols and alpha-
numerics for choice of operation:")
=========================================
149
FILES IN PYTHON
Index:
------------
=>Purpose of Files
=>Types of applications in the context of files
a)Non-persistent applications
b) Persistent Applications
=>Definition of file
=>Operations on Files
a) Read Operation
b)Write Operation
=>File Opening Modes
1) r
2) w
3) a
4) r+
5) w+
6) a+
7) x
=>Syntaxes for Opening a file
a) by using open()
b) with .. open()...as
=>Programming Examples
=>Writing the data to the files
a) write()
b)writelines()
=>Reading the data from the files
a) read()
b) read(no.of char)
c) readline()
d) readlines()
=>Programming Examples
=>Advanced concepts of Files
pickle module
a) Object Serialization and De-serialization
i) pickling
ii)un-pickling
=>Programming Examples
==============================================
Introduction to files
==================================================
=>The main purpose of files is that "To achieve the Data
Persistency "
=>Data Persistency is nothing but storing the data
permanently.
=>In the context of files, we can develop two types of
applications. They are
a) Non-Persistant Applications
150
b) Persistant Applications.
a) Non-Persistent Applications:
-----------------------------------------------
=>In this application development, we accept the inputs from
KBD, stored in main memory(RAM), process the input in main
Memory and whose result displayed on Console.
=>Any Data stored in Main Memory (RAM) is temporary.
=>All our previous program are comes under Non-Persistent
Applications.
--------------------------------------------------------------
----------------------------------------------
b) Persistent Applications:
-----------------------------------------
=>In this application development, we accept the inputs from
KBD, stored in main memory(RAM), process the input in main
Memory and whose result displayed on Console and the results
are Stored Permanently.
=>In Industry, we have two approaches to store the data
permanently. They are
a) By using Files
b) By using Database Software’s.
==============================X==============================
Operations on files
===============================================
=>Definition of File:
-----------------------------
=>A file is a collection of Records.
=>A record is a collection of Field values.
NOTE:- Every object data becomes record in the file and the
record of file becomes an object.
Definition of Stream:
------------------------------
=>The flow of data between main memory and file of secondary
is called stream
--------------------------------------------------------------
--------------------------------------------------
Operations on Files
-----------------------------
=>On files, we can perform two types of Operations. They are
a) Write Operation
b) Read Operation
----------------------------
a) Write Operation:
----------------------------
=>The purpose of write operation is that to store the object
data of main memory into file of secondary memory.
151
=>Steps:
-------------
a). Choose the file name
b). Open the file name in write mode
c). Perform Cycle of write Operations.
=>During the write operations, we get the following
exceptions.
a)EOFError
b)IOError
c)FileExistError
--------------------------------------------------------------
------------------------------
b) Read Operation:
-----------------------------
=>The purpose of read operation is that to transfer the data
from file of secondary memory into the object of main memory
.
Steps:
------------
a) Choose the file name
b) Open the file name in read mode
c) Perform Cycle of Read Operations.
=>During the read operations, we get the following exceptions.
a) FileNotFoundError
==============================X============================
Types of Files in python
=========================================
=>In Python , we have two types of files. They are
a) Text Files
b) Binary Files
a) Text Files:
-------------------
=>This files contains alphabets, special symbols and digits.
=>Text Files are denoted by a letter 't'
Examples: .py .java .txt .c, .cpp...etc
-------------------------------------------------------------
b) Binary Files:
-----------------------
=>These files contains the information internally in the form
of binary (or) pixels
=>Binary Fils are denoted by a letter 'b'
===============================X========================
152
==========================================
File Opening Modes in Python
==========================================
=>In Python , we have 7 file opening modes. They are
-------------------------------
1) r
------------------------------
=>This mode is used opening the file in read mode.
=> This is one of the default file mode
------------------------------
2) w
------------------------------
=>This mode is used for opening the file in write mode by
creating newly always.
=>In other words, This mode opens the new file in write mode
and write the data newly. if the file already existing then it
will be opened by removing existing data and adds new data
from the beginning of the file.
------------------------------
3) a
------------------------------
=>This mode is used for Opening and Creating the new File in
write mode and writes the from the begining.
=>This mode can also be used for Opening the Existing File in
write mode and writes new data at the end of existing data of
file (appending)
------------------------------
4) r+
------------------------------
=>This mode is used for opening the file in read mode
=>This mode makes to perform First read Operation and later we
can perform write operation.
=>While we are opening the file in r+ and if the file does
not exists then we get FileNotFoundError and we can't perform
write operation at this time.
------------------------------
5) w+
------------------------------
=>This mode is used for opening the file(new and existing
file) in write mode by creating newly always.
=>=>This mode makes to perform First write operation and later
we can perform Read Operation .
=>While we are opening the new file in w+ and if we try to
read the data from the new file then we IOError and EOFError
------------------------------
6) a+
------------------------------
=>This mode is used for Opening and Creating the new File in
write mode and writes the from the beging.
153
=>This mode can also be used for Opening the Existing File in
write mode and writes new data at the end of existing data of
file (appending)
=>Additionally, we can perform read operation also after write
/ appending operation otherwise we get EOFError and IOError.
------------------------------
7) x
-------------------------------
=>This mode is used for opening the file in write mode
EXCLUSIVELY.
=>If we open the existing file in 'x' mode then we get
FileExistError
--------------------------------------------------------------
Syntaxes for opening the files
==========================================
=>In Python, we have 2 syntaxes for opening a file. They are
a) open()
b) with open() as
--------------------------------------------------------------
----------------------------
a) open():
---------------
Syntax:- varname=open("filename","file mode")
Explanation:
------------------
=>'varname' represents File Pointer pointing to the file
provided the file opened successfully.
=>open() is used for opening file in specified mode other we
get appropriate exception.
=>File mode represents r, w,a,r+,w+,a+,x .
Explanation:
-----------------------
=>"with" and 'as' as keywords
=>open() is pre-defined function used to open a file in the
specified mode.
=>As long as PVM is executing Indentation block of statements
of with..open() as .. syntax , File is actively Under Opening
and whose 'closed' property is False.
=>Once PVM comes out of Indentation block of statements of
with..open() as .. syntax, then the 'closed' property is True.
In other words this syntax closes the file automatically once
PVM comes of Indentation block of statements of with..open()
as .. syntax. This Property is called auto-closable
=========================================================
Functions for writing the data to the file
===========================================
=>To write the data to the file, we have two functions. They
are
a) write()
b)writelines()
a)write():-
-------------
=>This function is used for writing the data to the file in
the form of str always.
Examples:
------------------
#FileWriteEx1.py
with open("person.addr","a") as wp:
#accept the address from KBD
pname=input("Enter Ur Name:")
hno=input("Enter Ur House Number:")
streetno=int(input("Enter Ur Street Number:"))
city=input("Enter Ur City:")
#save the address of person in file
wp.write(pname+"\n")
wp.write(hno+"\n")
wp.write(str(streetno)+"\n")
wp.write(city+"\n")
print('\nAddress Saved In file--verify')
==============================================================
==
b)writelines():-
-------------
=>This function is used for writing the Iterbale object data
to file in the form str
155
---------------------
Examples:
---------------------
#FileWriteEx3.py
with open("person1.addr","w") as wp:
# take addr in list
lst=["Ramesh\n",str(10)+"\n","Hyd\n","India\n"]
#save the address of person in file
wp.writelines(lst)
print('\nAddress Saved In file--verify')
==================================X===========================
EXAMPLES:
#FileOpenEx1.py
try:
fp=open("stud.data","r+")
print("File Opened Successfully In read mode");
except FileNotFoundError:
print("File does not Exists")
else:
print("-"*50)
print("Information about file properties:")
print("-"*50)
print("Type of fp={}".format(type(fp)))#<class,
'_io.TextIOWrapper'>
print("File Mode :{}".format(fp.mode ))
print("Is it readable:{}".format(fp.readable()))
print("Is it writable:{}".format(fp.writable()))
print("Line-15:--is the file closed?:
{}".format(fp.closed))
print("-"*50)
finally:
if fp!=None:
fp.close()
print("Line-20 is the file closed?:
{}".format(fp.closed))
print("Flie closed safely:")
==============================================
#FileOpenEx2.py
fp=open("stud.data","w")
print("File created and Opened in write mode--verify")
156
#FileOpenEx3.py
try:
fp=open("stud1.data","x")
print("File Opened Successfully In X --write mode
newly");
except FileExistsError:
print("File already exists")
else:
print("-"*50)
print("Information about file properties:")
print("-"*50)
print("Type of fp={}".format(type(fp))) # <class,
'_io.TextIOWrapper'>
print("File Mode :{}".format(fp.mode ))
print("Is it readable:{}".format(fp.readable()))
print("Is it writable:{}".format(fp.writable()))
print("Line-15:--is the file closed?:
{}".format(fp.closed))
print("-"*50)
==============================================================
#FileOpenEx4.py
try:
with open("stud.data","r") as rp:
print("-"*50)
print("Information about file properties:")
print("-"*50)
print("Type of rp={}".format(type(rp))) # <class,
'_io.TextIOWrapper'>
print("File Mode :{}".format(rp.mode ))
print("Is it readable:{}".format(rp.readable()))
print("Is it writable:{}".format(rp.writable()))
print("Line-11:--is the file closed?:
{}".format(rp.closed)) # False
print("-"*50)
print("Line-13:--is the file closed?:
{}".format(rp.closed)) # False
except FileNotFoundError:
print("File does not exists:")
finally:
print("Line-17:--is the file closed?:
{}".format(rp.closed)) #True
157
#FileWriteEx1.py
with open("person.addr","a") as wp:
#accept the address from KBD
pname=input("Enter Ur Name:")
hno=input("Enter Ur House Number:")
streetno=int(input("Enter Ur Street Number:"))
city=input("Enter Ur City:")
#save the address of person in file
wp.write(pname+"\n")
wp.write(hno+"\n")
wp.write(str(streetno)+"\n")
wp.write(city+"\n")
print('\nAddress Saved In file--verify')
=====================================================
#FileWriteEx2.py
with open("person1.addr","a") as wp:
#accept the address from KBD
lst=list()
pname=input("Enter Ur Name:")
hno=input("Enter Ur House Number:")
streetno=int(input("Enter Ur Street Number:"))
city=input("Enter Ur City:")
lst.append(pname+"\n")
lst.append(hno+"\n")
lst.append(str(streetno)+"\n")
lst.append(city+"\n")
#save the address of person in file
wp.writelines(lst)
print('\nAddress Saved In file--verify')
============================================================
#FileWriteEx3.py
with open("person1.addr","w") as wp:
# take addr in list
lst=["Ramesh\n",str(10)+"\n","Hyd\n","India\n"]
#save the address of person in file
wp.writelines(lst)
print('\nAddress Saved In file--verify')
============================================================
=========================================
158
===============================X========================
Functions for Reading the data from the file
=======================================================
=>To read the data from the file, we have 4 pre-defined
functions. They are
a) read()
b) read(no. of chars)
c) readline()
d) readlines()
--------------------------------------------------------------
-----------------------------------------------------
a) read():
----------------
=>This function is used for reading the entire data from file
and returns in the form of str.
Syntax:- varname=filepointer.read()
=>here 'varname' is of type <class,'str'>
Examples:
----------------
#program for reading the content of the file and display
#FileReadEx1.py-------------read()---implementation of type
command of OS
fname=input("Enter the file name:")
try:
with open(fname) as fp:
filedata=fp.read()
print(filedata)
except FileNotFoundError:
print("Files does not exists:")
--------------------------------------------------------------
-----------------------------------------------------
159
b) read(no. of chars):
----------------------------------
=>This function is used for reading the specified number of
characters from file and returns in the form of str.
Syntax:- varname=filepointer.read(no. of
characters)
=>here 'varname' is of type <class,'str'>
---------------------
Examples:
---------------------
#This program reads some specific number of characters from
the file.
#FileReadEx2.py----read(no. of chars)-----tell()
#tell() gives current position of filepointer
#seek(Position) will makes the file pointer to point to the
perticular position.
with open("pyth.info","r") as rp:
print("-"*50)
print("Initial Position/Index of
rp={}".format(rp.tell())) # 0
print("-"*50)
#read 6 characters
filedata=rp.read(6)
print("Data=",filedata)
print("-"*50)
print("Current Position/Index of
rp={}".format(rp.tell())) # 6
print("-"*50)
#read 10 characters
filedata=rp.read(10)
print("Data=",filedata)
print("-"*50)
print("Current Position/Index of
rp={}".format(rp.tell())) # 16
print("-"*50)
#read the rest of the data
filedata=rp.read()
print("Data=",filedata)
print("-"*50)
print("Current Position/Index of
rp={}".format(rp.tell())) # 105
print("-"*50)
rp.seek(0)
print("Current Position/Index of rp after
seek(0)={}".format(rp.tell())) # 0
print("-"*50)
filedata=rp.read()
print("Data=",filedata)
print("-"*50)
================================X=============================
160
c) readline()
-------------------
=>This function is used for reading One line at a time from
file wherever file pointer and returns in the form of str.
Syntax:- varname=filepointer.readline()
=>here 'varname' is of type <class,'str'>
--------------------
Examples:
-------------------
#This program reads one line at a time from File
#FileReadEx3.py----readline()
with open("pyth.info") as rp:
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
print(filedata)
--------------------------------------------------------------
-------------------------------------
d) readlines():
-----------------------
=>This function is used for reading all the lines from file
and returns in the form of list.
Syntax:- varname=filepointer.readlines()
=>here 'varname' is of type <class,'list'>
Examples:
--------------------
#This program reads all lines at a time from File
#FileReadEx4.py----readlines()
with open("pyth.info") as rp:
filedata=rp.readlines()
for line in filedata:
print(line, end="")
--------------------------------------------------------------
EXAMPLES:
--------
#program for reading the content of the file and display
#FileReadEx1.py----------read()---implementation of type command of OS
fname=input("Enter the file name:")
try:
with open(fname) as fp:
filedata=fp.read()
print(filedata)
except FileNotFoundError:
print("Files does not exists:")
161
#This program reads some specific number of characters from the file.
#FileReadEx2.py----read(no. of chars)-----tell()
#tell() gives current position of filepointer
#seek(Position) will makes the file pointer to point to the perticular
position.
with open("pyth.info","r") as rp:
print("-"*50)
print("Initial Position/Index of rp={}".format(rp.tell())) # 0
print("-"*50)
#read 6 characters
filedata=rp.read(6)
print("Data=",filedata)
print("-"*50)
print("Current Position/Index of rp={}".format(rp.tell())) # 6
print("-"*50)
#read 10 characters
filedata=rp.read(10)
print("Data=",filedata)
print("-"*50)
print("Current Position/Index of rp={}".format(rp.tell())) # 16
print("-"*50)
#read the rest of the data
filedata=rp.read()
print("Data=",filedata)
print("-"*50)
print("Current Position/Index of rp={}".format(rp.tell())) # 105
print("-"*50)
rp.seek(0)
print("Current Position/Index of rp after
seek(0)={}".format(rp.tell())) # 0
print("-"*50)
filedata=rp.read()
print("Data=",filedata)
print("-"*50)
==============================================================
#This program reads one line at a time from File
#FileReadEx3.py----readline()
with open("pyth.info") as rp:
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
162
print(filedata)
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
print(filedata)
filedata=rp.readline()
print(filedata)
==============================================================
#This program reads all lines at a time from File
#FileReadEx4.py----readlines()
with open("pyth.info") as rp:
filedata=rp.readlines()
for line in filedata:
print(line, end="")
=============================================================
#this program copy the content of source file into destination
file
#FileCopy.py-------implementing Copy command of MS-OS
try:
sfile=input("Enter Source File Name:")
with open(sfile) as rp: # opening source file in 'r'
mode
dfile=input("Enter Destination File:")
with open(dfile,"a") as wp: # opening Destination
file in 'a' mode
sfiledata=rp.read() # reading entire data
from source file
wp.write(sfiledata) # writing the entire
data to destination file
except FileNotFoundError:
print("Source File does not exists:")
else:
print("Source File copied into Destination file-verify
")
==========================================================
#this program copy the Image content of source file into
destination file
#FileImagCopy.py
try:
sfile=input("Enter Source File Name:")
with open(sfile,"rb") as rp: # opening source file in
'r' mode
dfile=input("Enter Destination File:")
with open(dfile,"wb") as wp: # opening
Destination file in 'w' mode
sfiledata=rp.read() # reading entire data
from source file
wp.write(sfiledata) # writing the entire
data to destination file
163
except FileNotFoundError:
print("Source File does not exists:")
else:
print("Source File copied into Destination file--verify
")
===================================
#Reading the data dynamically from KBD and write that dynamic
data to file until we press "stop"
#dynamicwrite.py
with open("wed.info","a") as wp:
print("Enter the data from KBD dynamically and 'stop' to
complete write opration to the file")
print("-"*50)
while(True):
kbddata=input()
if(kbddata!='stop'):
wp.write(kbddata+"\n")
else:
break
print("-"*50)
print("\nData Written to the file--verify")
print("-"*50)
===============================
Pickling and Un-pickling
(or)
Object Serialization and Object De-serialization
====================================================
Pickling ( Object Serialization)
--------------
=>Let us assume there exists an object with mutiple values in
main memory. To save / write the object data with write() and
writelines() , internally these functions will transfer value
by value to the file of secondary memory and takes more
execution time. To overcome this problem, we must use
pickling.
=>The Advantage of pickling concept is that with single write
operation we can save (or) writes the object data to the file
instead of redundant write operations.
Definition of Pickling:
---------------------------------
The Process of Saving (or) writing the object data of main
memory into the file of secondary memory by performing single
write Operation is called "Pickling"
=>Pickling concept participates in write Operation.
-----------------------------------
164
Implementation of Pickling:
---------------------------------------------
a) import pickle
b) prepare an object with multiple values
c) Choose the file name and open it into write mode
d) use dump() of pickle module
Syntax: pickle.dump(object,filepointer)
here dump() is used for saving / writing the entire
object data into file of secondary memory.
---------------------------------------------------------
Un-pickling (Object De-serialization)
--------------------------------------------------------
=>Let us assume there exists a record with multiple values
in a file of secondary memory. To read the entire record
content from the file of secondary memory by using read(),
read(no.of chars), readline() and readlines() then they will
read the record values value by value and it is one of the
time consuming Process / takes More execution time.
=>To over come this problem, we use un-pickling.
=>The advantage of un-pickling is that with single read
operation, we can read entire record content from file of
secondary memory into the object of memory.
-------------------------------------------
=>Definition of un-pickling:
-------------------------------------------
=>The process of reading / transferring the entire record
content from file of secondary memory into the object of main
memory by performing single read operation is called Un-
Pickling.
-----------------------------------------------
Implementation of Un-Pickling:
----------------------------------------------
a) import pickle
b)Choose the file name and open it into read mode
c) use load() of pickle module
Syntax:-
objname=pickle.load(file pointer)
#studentpick.py----------Program-(A)
import pickle
with open("stud.data","ab") as fp:
nos=int(input("Enter How many students data u want enter:"))
for i in range(1,nos+1):
print("-"*50)
print("Enter {} Student Values".format(i))
print("-"*50)
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student Marks"));
cname=input("Enter Student College Name:")
#create an empty list
lst=list()
#append the student data
lst.append(sno)
lst.append(sname)
lst.append(marks)
lst.append(cname)
#save the student data in file
pickle.dump(lst,fp)
print("-"*50)
print("\nStudent Data Saved Successfully in File:")
================================================================
#studunpick.py
import pickle
try:
with open("stud.data","rb") as fp:
print('-'*50)
print("\t\tStudent Details")
print('-'*50)
print("\tStno\tName\tMarks\tCollege Name")
print('-'*50)
while(True):
try:
listobj=pickle.load(fp)
for val in listobj:
print("\t{}".format(val),
end=" ")
print()
except EOFError:
print('-'*50)
break
except FileNotFoundError:
print("File does not exists:")
166
=============================================
random module
=============================================
=>Python "random" module is an in-built module of python.
=>The purpose of random module is that to generate random
numbers.
=>random numbers are not truly random but they are selected
from the specified list, string..etc objects and they
displayed on the console
=>The random module contains, the following pre-defined
functions.
a) randrange()
b) randint()
c) random()
d) uniform()
e) choice()
f) shuffle()
g) sample()
--------------------------------------------------------------
a) randrange():
------------------------
=>Syntax:- random.randrange(start,stop)
=>This function is used for generating random integer value
from the specified start and stop-1 value(start included and
stop value excluded).
=>Here start and stop value must be int data but other types
are not allowed.
------------------
Examples:
-----------------
>>> import random as r
>>> r.randrange(10,20)--------10
>>> r.randrange(10,20)--------18
>>> r.randrange(10,20)-------16
>>> r.randrange(10,20)----17
>>> r.randrange(10,20)----19
>>> r.randrange(10,20)----16
>>> r.randrange(10,20)-----14
>>> r.randrange(10,20)-----18
>>> r.randrange(1000,1500)---1212
>>> r.randrange(1000,1500)---1457
>>> r.randrange(1000,1500)--1047
Examples:
----------------
#otp.py
from random import randrange
print("Ur
OTP=",randrange(0,10),randrange(0,10),randrange(0,10),randrang
e(0,10),randrange(0,10),randrange(0,10))
print("----------------")
print(randrange(100000,999999))
167
-----------------------------------------------------------
b) randint():
------------------
=>Syntax:- random.randint(start,stop)
=>This function is used for generating random integer value
from the specified start and stop value(start and stop values
are included).
=>Here start and stop value must be int data but other types
are not allowed.
-----------------
Examples:
-----------------
>>> r.randint(1000,9999)---------8127
>>> r.randint(1000,9999)-----8220
>>> r.randint(1000,9999)-----7985
>>> r.randint(1000,9999)-----3792
>>> r.randint(10000,99999)----19974
>>> r.randint(10000,99999)----97968
>>> r.randint(10000,99999)---97781
>>> r.randint(10000,99999)---26995
>>> r.randint(10000,99999)---80854
--------------------------------------------------------------
------------------------------------------------------
c) random()
--------------------
=>This function generates floting point random values between
0 to 1 (both excluded)
=>Syntax:- random.random()
Examples:
---------------
>>> r.random()------0.4373284144678242
>>> r.random()-----0.19401495196580687
>>> r.random()------0.01862452100170109
>>> r.random()-----0.20330848408922564
Examples:
#ranex1.py
from random import random
for i in range(5):
print("%.4f" %random())
(OR)
#ranex1.py
from random import random
for i in range(5):
print(random())
168
d) uniform() :
------------------------
=>This function generates floating point random values between
start and stop ( both of them are excluded)
=>Syntax:- random.uniform(start,stop)
=>The values of start and stop can be either int or float
--------------
Examples
--------------
>>> r.uniform(100.5,200.5)--------------157.11114697097324
>>> r.uniform(100.5,200.5)---------190.95457759732517
>>> r.uniform(100.5,200.5)---------123.1952434841989
>>> r.uniform(100.5,200.5)---------104.82161510942237
>>> r.uniform(1,2)------1.3789457148106403
>>> r.uniform(1,2)------1.5586482241482948
>>> r.uniform(1,2)------1.128575716628112
>>> r.uniform(1,2)-----1.4208894552256035
>>> r.uniform(1,2)----1.9393817696446607
>>> r.uniform(1,2)----1.8984870017660347
>>> r.uniform(-100.5,-200.5)---------136.32077473726284
>>> r.uniform(-100.5,-200.5)-------112.2432994001467
>>> rv=r.uniform(-100.5,-200.5)
>>> print(rv)-------122.58685384954742
------------------
Examples:
------------------
#ranex2.py
from random import uniform
for i in range(3):
print("%.3f" %uniform(10.5,20.5))
--------------------------------------------------------------
--------------------------------------------
e) choice():
------------------
=>This function is used for obtaining random element from the
given iterable object.
=>Syntax:-
---------------
random.choice(iterableobj)
Examples:
---------------
>>> lst=['a','e','i','o','u']
>>> print(lst)-------['a', 'e', 'i', 'o', 'u']
>>> print(r.choice(lst))
u
>>> print(r.choice(lst))
u
>>> print(r.choice(lst))
a
>>> print(r.choice(lst))
169
e
>>> print(r.choice(lst))
o
>>> print(r.choice(lst))
i
>>> print(r.choice(lst))
e
>>> print(r.choice(lst))
u
------------------------------------------------
>>> lst=["python","java","DS","ML","AI",34.56,34,True]
>>> print(lst)
['python', 'java', 'DS', 'ML', 'AI', 34.56, 34, True]
>>> print(r.choice(lst))
java
>>> print(r.choice(lst))
python
>>> print(r.choice(lst))
34
>>> print(r.choice(lst))
34.56
>>> print(r.choice(lst))
DS
>>> print(r.choice(lst))
java
>>> print(r.choice(lst))
ML
>>> print(r.choice(lst))
True
>>> print(r.choice(lst))
python
Examples:
------------------
#ranex3.py
from random import choice
givendata="456AZU24abrE#Q73^#@HUt90rpm*%HK573QPZ1234$"
for i in range(5):
print(choice(givendata),choice(givendata),choice(givenda
ta),choice(givendata),choice(givendata))
--------------------------------------------------------------
------------
f) shuffle():
-------------------
=>This function is used for re-oranizing the order of elements
of any mutable objects only.
=>Syntax:- random.shuffle(Mutable_Iterable_object)
170
Examples:
-----------------
>>> lst=["python","java","DS","ML","AI",34.56,34,True]
>>> print(lst)----------['python', 'java', 'DS', 'ML', 'AI',
34.56, 34, True]
>>> r.shuffle(lst)
>>> print(lst)----[34, 'java', 'python', 34.56, 'AI', 'DS',
'ML', True]
>>> r.shuffle(lst)
>>> print(lst)----[34, 'AI', True, 'ML', 34.56, 'java',
'python', 'DS']
>>> r.shuffle(lst)
>>> print(lst)---['ML', True, 'java', 'AI', 34, 'python',
'DS', 34.56]
>>> print(r.shuffle(lst))---None
Examples:
-----------------
#ranex4.py
from random import shuffle
lst=["python","java","DS","ML","AI",34.56,34,True]
for i in range(5):
shuffle(lst)
print(lst)
-------------------
Examples:
------------------
>>> s="python"
>>> r.shuffle(s)---------TypeError: 'str' object does not
support item assignment
>>> lst=['a','e','i','o','u']
>>> r.shuffle(lst)----
>>> print(lst)--------['a', 'u', 'e', 'o', 'i']
>>> r.shuffle(lst)
>>> print(lst)---['u', 'i', 'a', 'o', 'e']
>>> r.shuffle(lst)
>>> print(lst)----['a', 'e', 'i', 'u', 'o']
==============================================================
=====
g) sample():
-------------------
Syntax:- listobj=random.sample(iterable_object, k )
=>Here k represents no. of selections to be made randomly from
the specified iterable object.
Examples:
------------------
>>> lst=["python","java","DS","ML","AI",34.56,34,True]
>>> print(lst)----['python', 'java', 'DS', 'ML', 'AI', 34.56,
34, True]
171
>>> r.sample(lst,2)
[34.56, 'DS']
>>> r.sample(lst,2)
['AI', 'python']
>>> r.sample(lst,2)
['python', 'AI']
>>> r.sample(lst,2)
['java', 'ML']
>>> r.sample(lst,2)
['AI', 'DS']
>>> r.sample(lst,3)
[34, 'java', 'AI']
>>> r.sample(lst,4)
[True, 'AI', 34.56, 'python']
>>> r.sample(lst,4)
['python', 'DS', 34, 'ML']
>>> res=r.sample(lst,4)
>>> print(res)--------[True, 'python', 34.56, 'ML']
>>> res=r.sample(lst,4)
>>> print(res)--------------['java', 'ML', 34, 'AI']
=============================X=========================
Importance of Database software’s in data Persistency.
==================================================
=>The main purpose DataBase Software’s is that "To achieve the
Data Persistency"
=>Data Persistency is nothing but storing the data
Permanently.
=>In Database , the data always stored in the form of Tables.
=>A table is a collection of Rows and Columns.
=>Rows are called Records & Columns are called Fields
--------------------------------------------------------------
=>Advantages of database software’s:
--------------------------------------------------------------
--
1) All types of RDBMS products provides high security
Database
2) Querying the data from database software is easy.
3) Database software are possessing OS Independency
4) Database software’s stores large volume of data.
========================================================
=>As a Python, we are communicating with Oracle and MySQL
databases.
172
=================================================
Communication between Python and DataBase Software’s
=================================================
=>In Python Programming, to communicate with any database
software’s, First we must install corresponding database
module of python.
=>Suppose, If python programmer wants communicate with Oracle,
we must install a pre-defined module cx_Oracle by using pip
tool.(C:\Users\nareshit\AppData\Local\Programs\Python\Python39
\Scripts)
==============================================================
Steps for python program to communicate with Oracle Data base:
--------------------------------------------------------------
-----------------------------------------
Step1:- import cx_Oracle module
--------------------------------------------------------------
-------------------------------------------
step-2:- Python Program must obtain Connection from Oracle
Database. To get this connection, we use
connect() , which is present in cx_Oracle module.
Example: tiger
DNS(Domain naming Service):
------------------------------------------
=>DNS is nothing but Name of machine where Data base software
is installed.
=>default DNS of every computer is "localhost"
=>IPAddress is nothing but The four parts Numerical Address of
the machine , where the Data base software is available.
=>The default IPaddress of every computer is 127.0.0.1 (loop
back address)
173
import cx_Oracle
con=cx_Oracle.connect("scott/[email protected]/orcl")
print("Python obtains connection from
Oracle DB")
------------------------------------------------------
3) Create a an object Cursor. To get the ncursor object, we
use cursor() which is present in connection object.
Syntax:-
varname=connectionobj.cursor()
=>here varname is an object of <cx_Oracle.Cursor>
------------------------------------------------------------
4) Design the query and execute . To execute the query from
Python program , we use a pre-defined function called
execute(), which is present in cursor object
cursorobj.execute(query)
=>here query represents either DDL, DML and DRL
-----------------------------------------------------------
PROGRAMS:
#oracontest.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("type of con=",type(con)) #
print("Python obtains connection from Oracle DB")
except cx_Oracle.DatabaseError:
print("Connection Problems--verify Connection URL")
-----------------------------------------------------------
#cursortest.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("type of con=",type(con)) #
print("Python obtains connection from Oracle DB")
cur=con.cursor()
174
print("Type of cur=",type(cur))
print("Python Obtains cursor object and ready to execute
any Query")
except cx_Oracle.DatabaseError:
print("Connection Problems--verify Connection URL”)
==================================================================
Types of query Database software’s
======================================
=>A query is a statement and it is treated as a Request /
Question to data base from Python Program
=>We have the following queries.
1) DDL Queries (Data Definition Language):
--------------------------------
a) create b) alter c) drop
Syntax:
-------------
SQL> create table <table-name>(colname1 datatype1, colname2
datatype2.....colname-n datatype-n);
------------------------------------------------------------
c) drop:
--------------
=>It is used for removing the table permanently from Database
Syntax:- drop table <table-name>
where condition;
--------------
Syntax-2:
---------------
update <table> set colname1=val1,colname2=val2...colname-
n=val-n;
==============================================================
EXAMPLES:
--------
#tabcreate.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("Python obtains connection from Oracle DB")
cur=con.cursor()
print("Python Obtains cursor object and ready to execute
any Query")
q="create table student (stno number(3), name
varchar2(15), marks number(5,2))"
cur.execute(q)
print("\tTable Created and goto Oracle--verify")
except cx_Oracle.DatabaseError:
print("Connection Problems--verify Connection URL")
============================================================
177
#tablecreateex1.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
cur.execute("create table faculty (fno number(2),fname
varchar2(15), sub varchar2(10) ) ")
print("Table Created Successfully--verify")
except cx_Oracle.DatabaseError :
print("table already exists")
==============================================================
#altertableex1.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
cur.execute("alter table faculty add ( exp number(2))")
print("Table altred with new Column name Successfully--
verify")
except cx_Oracle.DatabaseError :
print("table already exists")
===============================================
#altertableex2.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
cur.execute("alter table faculty modify ( fname
varchar2(20))")
print("Table alterd Column size Successfully--verify")
except cx_Oracle.DatabaseError :
print("table already exists")
====================================================================
#tabledrop.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/[email protected]/orcl")
cur=con.cursor()
cur.execute("drop table faculty")
print("Table Dropped Successfully--verify")
except cx_Oracle.DatabaseError :
print("table does not exists")
=============================================================
#insertrecordex1.py
#This program inserts the student record values in student
table of Oracle
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
178
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor()
#accpt student number , name and marks for
updatation
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name for updation:")
smarks=float(input("Enter Student Marks for
updation:"))
#update the record
cur.execute("update student set name='%s',
marks=%f where stno=%d " %(sname,smarks,sno) )
con.commit()
if(cur.rowcount>0):
print("{} student record updated--
verify:".format(cur.rowcount))
else:
print("Student Record does not exists:")
except cx_Oracle.DatabaseError as db:
print("Data base rules not followed ", db)
except ValueError:
print("Don't enter strs/ alpha-numerics / special
symbols")
#updaterecordexp2.py
#MAIN PROGRAM
from updaterec import updatestudrec
updatestudrec()
Syntax:-
--------------
select colname1,colname2..colname-n from table name where
condition;
(OR)
select colname1,colname2..colname-n from table name ;
(OR)
select * from table name ;
Syntax:- curobj.fetchone()
Syntax:- curobj.fetchall()
================================X===========================
#This program select the records (or) read the records from
student table
#selectex1.py
import cx_Oracle
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor();
cur.execute("select * from student")
#apply fetchone()
print("-"*50)
print("\tStudent Details")
print("-"*50)
while (True):
rec=cur.fetchone()
if(rec==None):
break
183
else:
for recval in rec:
print("\t{}".format(recval), end=" ")
print()
print("-"*50)
================================================================
#This program select the records (or) read the records from
student table
#selectex2.py
import cx_Oracle
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor();
cur.execute("select * from student")
#apply fetchmany()
print("*"*50)
print("\tS t u d e n t D e t a i ls")
print("*"*50)
records=cur.fetchmany(3)
for record in records:
for recval in record:
print("\t{}".format(recval), end=" ")
print()
print("*"*50)
Note:
=>In fetchmany( n ), here 'n' can be +ve or -ve or 0
=>If n is +ve<total number of records of table then
fetchmany() gives 'n' number of records.
=>if n is +ve>total number of records of table then
fetchmany() gives all the records of table
=>if n is o then fetchmany() gives all the records of table
=>if n is -ve then fetchmany() will not give any records.
===========================================================
#This program select the records (or) read the records from
student table
#selectex3.py
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=con.cursor();
cur.execute("select * from student")
#apply fetchall()
print("*"*50)
print("\tS t u d e n t D e t a i ls")
print("*"*50)
records=cur.fetchall()
184
============================================================
Communication between Python and MySql DataBase Softwares
===============================================================
=>In Python Programming, to communicate with any database
software’s, First we must install corresponding database
module of python.
=>Suppose, If python programmer wants communicate with MYSQL,
we must install a pre-defined module mysql-connector by
using pip
tool.(C:\Users\nareshit\AppData\Local\Programs\Python\Python39
\Scripts)
==============================================================
Steps for python program to communicate with MYSQL Data base:
-------------------------------------------------------------
Step1:- import mysql.connector module
------------------------------------------------------------
185
passwd="password of MYSQL",)
import mysql.connector
con=mysql.connector.connect(host="localhost",
user="root",
passwd="root")
print("Python obtains connection from MySQL DB")
--------------------------------------------------------------
----------------------------------------------------
3) Create a an object Cursor. To get the cursor object, we use
cursor() which is present in connection object.
Syntax:-
varname=connectionobj.cursor()
user="root",
passwd="root" )
print("\nPython obtains connection from MySQL DB")
cur=con.cursor()
dq="create database kvr"
cur.execute(dq)
print("\ndata base created in MYSQL--plz verify")
user="root",
passwd="root",
database="kvr")
cur=con.cursor()
tq="create table student1(sno int primary key, sname
varchar(15) not null, marks float not null) "
187
cur.execute(tq)
print("Table created successfully--verify")
except mysql.connector.DatabaseError as db:
print("MySQL connection Problems ", db)
==============================================================
#insertrecordex1.py
#This program inserts the employee record values in employee
table of MYSQL
import mysql.connector
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch11am")
cur=con.cursor()
#design the query and execute
iq="insert into employee values(20,'Ramu',6.5)"
cur.execute(iq)
con.commit()
print("Employee Record inserted successfully--verify")
except mysql.connector.DatabaseError as db:
print("Data Rules are not followed ",db)
=============================================================
#insertrecordex2.py
#This program inserts the student record values in student
table of MYSQL by reading from KBD
import mysql.connector
while(True):
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch11am")
cur=con.cursor()
#accept the student values from KBD
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
smarks=float(input("Enter Student Marks:"))
#design the query and execute
cur.execute("insert into student values
(%d,'%s',%f)" %(sno,sname,smarks) )
con.commit()
print("-"*50)
print("{} student record in Student
table:".format(cur.rowcount))
print("-"*50)
188
===============================================
#selectex1.py
#This program reads the record from student table based on
student number
import mysql.connector
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch11am")
#accpt student number from KBD
stno=int(input("Enter Student Number:"))
cur=con.cursor()
cur.execute("select * from student where sno=%d" %stno)
rec=cur.fetchone()
if rec!=None:
for val in rec:
print("\t{}".format(val),end=" ")
print()
else:
print("Student Record Does not exist")
except mysql.connector.DatabaseError as db:
print("DataBase Rules not followed", db)
=============================================================
#selectex2.py
#This program reads the record from student table based on
student number
import mysql.connector
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch11am")
#accpt student number from KBD
stno=int(input("Enter Student Number:"))
cur=con.cursor()
cur.execute("select sname,marks from student where
sno=%d" %stno)
rec=cur.fetchone()
if rec!=None:
print("Student Name:{}".format(rec[0] ))
print("Student Marks:",rec[1])
else:
189
==================================
Introduction to regular Expression
============================================
Syntax: varname=matchobj.start()
-----------------------------------------------------------
4) end():
--------------------------------------------------------
=>This function is used obtaining end index+1 of matched
value
Syntax: varname=matchobj.end()
---------------------------------------------------------
5) search():
--------------------------------------------------------
Syntax:- varname=re.search("search-pattern","Given data")
=>here varname is an object of <class,'match'>
#regexpr4.py
#This program searches for either 'a' or 'b' or 'c'
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[abc]", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
=====================================================
#regexpr5.py
#This program searching all except 'a' or 'b' or 'c'
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[^abc]", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
=============================================================
#regexpr6.py
#This program searching all for lower case / small case
alphabets
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[a-z]", Givendata)
print("-"*50)
for onematch in matchtab:
print(“starting index={} ending index={} value={}”.format
(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
……………………………………………………………………………………………………………………………………………………………………
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
………………………………………………………………………………………………………………………………………………………………………………..
#regexpr9.py
#This program searching all except Upper case alphabets
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[^A-Z]", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
………………………………………………………………………………………………………………………………………………………………………………….
#This program searching all Upper and lower case alphabets only
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[A-Za-z]", Givendata)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
#regexpr11.py
#This program searching all except Upper and lower case
alphabets
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[^A-Za-z]", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
………………………………………………………………………………………………………………………………………………………………………………..
#regexpr12.py
#This program searching all digits
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[0-9]", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
……………………………………………………………………………………………………………………………………………………………………….
#regexpr13.py
#This program searching all digits
import re
Givendata="cAa3#pQ7!@b4GeWPaK*2%"
matchtab=re.finditer("[^0-9]", Givendata)
print("-"*50)
for onematch in matchtab:
194
======================================================
Pre-Defined Character Classes in Python
======================================================
=>Pre-Defined Character Classes are developed by Python
Language developers and they are available in Python Software
,which are used in preparing search patterns and they are
used for searching required data(wanted data) in given data
obtains desired result.
Syntax:-
"\Pre-Defined Character Class"
Note:-
--------------
a) [0-9][0-9][0-9[0-9] (or) \dddd or \d{4}----
search for 4 digit number
b) \d{2,4}----searching for min 2 digit numbers and max 4
digit number
c) \dd.\dd----search for 3 digit integer part and 2 digit
decimal part.
#regexpr16.py
#This program searching all space charcaters
import re
Givendata=" cAa3#pQ7!@b 4GeWPaK*2%"
matchtab=re.finditer("\s", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.grou
p()))
print("-"*50)
==========================================================
#regexpr17.py
#This program searching all except space characters
import re
Givendata=" cAa3#pQ7!@b 4GeWPaK*2%"
matchtab=re.finditer("\S", Givendata)#S IS BIG
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
……………………………………………………………………………………………………………………………………………………………………………….
#regexpr18.py
#This program searching any word character
import re
Givendata=" cAa3#pQ7!@b 4GeWPaK*2%"
matchtab=re.finditer("\w", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
……………………………………………………………………………………………………………………………………………………………………………
#regexpr19.py
#This program searching any special symbol except word character
import re
Givendata=" cAa3#pQ7!@b 4GeWPaK*2%"
matchtab=re.finditer("\W", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
………………………………………………………………………………………………………………………………………………………………………
#regexpr20.py
196
………………………………………………………………………………………………………………………………………………………………………………
#regexpr21.py
#This program searching for all except digit
import re
Givendata=" cAa3#pQ7!@b 4GeWPaK*2%"
matchtab=re.finditer("\D", Givendata)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
=========================================
Quantifiers in Regular Expressions
=========================================
=>Quantifiers in Regular Expressions are used for searching number
of occurrences of the specified search pattern in the given data and
obtains desired result.
E:\KVR-PYTHON-11AM\REGEXPRESSIONS>py regexpr23.py
--------------------------------------------------
Starting index=0 End Index=1 Value=k
Starting index=1 End Index=1 Value=
Starting index=2 End Index=4 Value=kk
Starting index=4 End Index=4 Value=
Starting index=5 End Index=8 Value=kkk
Starting index=8 End Index=8 Value=
Starting index=9 End Index=10 Value=k
Starting index=10 End Index=10 Value=
Starting index=11 End Index=11 Value=
Starting index=12 End Index=12 Value=
-------------------------------------------------
#This program searching for either one 'k' more 'k' s
197
import re
Givendata="kvkkvkkkvkvr"
matchtab=re.finditer("k+", Givendata)
print("-"*50)
for onematch in matchtab:
print("Starting index={} End Index={}
Value={}".format(onematch.start(),onematch.end(),onematch.group()))
print("-"*50)
Output
E:\KVR-PYTHON-11AM\REGEXPRESSIONS>py regexpr22.py
--------------------------------------------------
Starting index=0 End Index=1 Value=k
Starting index=2 End Index=4 Value=kk
Starting index=5 End Index=8 Value=kkk
Starting index=9 End Index=10 Value=k
--------------------------------------------------"""
REGULAR EXPRESSIONS WITH FILES:
………………………………………………………………………………
#”STUDMAIL.DATA”
Srikanth got 44 marks and whose e-mail id is [email protected] ,
Rossum got 56 marks whose e-mail id is [email protected] , Swagtika
got 66 marks whose e-mail id is [email protected], Apoorva got 67
marks and whose email is is [email protected], Gosling got 22 marks
whose e-mail id is [email protected] , Bisen got 55 marks whose e-mail
id is [email protected] and Ritche got 44 marks whose e-mail id is
[email protected] and Rk got 99 marks whose e-mail id is
[email protected] and Rajesh got 88 marks whose e-mail id is
[email protected] and Krishna got 77 marks whose e-mail id is
[email protected]
#maisprog.py
import re
try:
with open("studmail.data") as rp:
filedata=rp.read()
mailslist=re.findall("\S+@\S+",filedata)
print("--------------------------------------")
print("Mails List:")
print("--------------------------------------")
for mail in mailslist:
print("\t{}".format(mail))
print("--------------------------------------")
nameslist=re.findall("[A-Z][A-Za-z]+",filedata)
print("Mails List:")
print("--------------------------------------")
for name in nameslist:
print("\t{}".format(name))
print("--------------------------------------")
print("\tName\t\tmail-id")
print("--------------------------------------")
for name,mail in zip(nameslist,mailslist):
print("\t{}\t\t{}".format(name, mail))
print("--------------------------------------")
198
……………………………………………………………………………………………………………………………………………………………….
EXAMPLE 2:WITH FILES
#”STUDDATA.INFO”
Srikanth got 44 marks, Rossum got 56 marks , Swagtika got 66 marks,
Apoorva got 67 marks, Gosling got 22 marks Bisen got 55 marks and
Ritche got 44 marks and Rk got 99 marks and Rajesh got 88 marks and
Krishna got 77 marks
#namesmarksex2.py
import re
try:
with open("studdata.info", "r") as rp:
filedata=rp.read()
nameslist=re.findall("[A-Z][A-Za-z]+",filedata)
print("---------------------------------------")
print("names of Students")
print("---------------------------------------")
for name in nameslist:
print("\t{}".format(name))
print("---------------------------------------")
markslist=re.findall("\d{2}",filedata)
print("Marks of Students")
print("---------------------------------------")
for marks in markslist:
print("\t{}".format(marks))
print("---------------------------------------")
print("---------------------------------------")
print("\tNames\t\tMarks")
print("---------------------------------------")
for name,marks in zip(nameslist,markslist):
print("\t{}\t\t{}".format(name,marks))
print("---------------------------------------")
……………………………………………………………………………………………………………………………………………………….
#namesmarksex1.py
import re
studdata="Srikanth got 44 marks, Rossum got 56 marks , Swagtika got 66
marks, Apoorva got 67 marks, Gosling got 22 marks Bisen got 55 marks
and Ritche got 44 marks and Rk got 99 marks and Rajesh got 88 marks
and Krishna got 77 marks"
nameslist=re.findall("[A-Z][A-Za-z]+",studdata)
print("---------------------------------------")
print("names of Students")
print("---------------------------------------")
for name in nameslist:
print("\t{}".format(name))
print("---------------------------------------")
markslist=re.findall("\d{2}",studdata)
print("Marks of Students")
print("---------------------------------------")
for marks in markslist:
199
print("\t{}".format(marks))
print("---------------------------------------")
print("\tNames\t\tMarks")
print("---------------------------------------")
for name,marks in zip(nameslist,markslist):
print("\t{}\t\t{}".format(name,marks))
print("---------------------------------------")
…………………………………………………………………………………………………………………………………………
SPECIAL EXAMPLE:
#mobilenovalid.py
import re
while(True):
mno=input("Enter Mobile Number:")
if (len(mno)==10):
res=re.search("\d{10}" ,mno)
if (res!=None):
print("Ur Mobile Number is Valid")
break
else:
print("Ur Mobile Number is InValid")
else:
print("Length of Mobile Number must be 10 digits")
=========================================
#findallex1.py
import re
res=re.findall("an", "python is an oop lang and python is also
fun lang")
if(len(res)>0):
print("Number of occurences of
'an'={}".format(len(res)))
else:
print("Search is Un-successful")
==============================================================
#searchex1.py
import re
res=re.search("python", "python is an oop lang and python is
also fun lang")
if res!=None:
print("Search is successful--",res)
else:
print("Search is Un-successful--")
200
==================================================
Object Oriented Principles in Python (OOP’S)
==================================================
=>In real time, To develop any project, we need to choose a
language and it can satisfy any of the following principles.
1) Procedure Oriented Principles (or Functional Programming)
2) Object Oriented Principles
=>Python Programming satisfied both Functional Programming
Principles and object oriented principles.
=>Even though Python satisfies both both Functional
Programming Principles and object oriented principles,
internally Every thing treated as "object"
Benefits is treating "Every Thing is an Object "
--------------------------------------------------------
=>It allows us to store large volume data
=>The data transferred between two remote application in the
form Cipher text / Encrypted format and hence secuity in
enhanced.
=>The large volume of data can be transferred all at once
between two remote applications.
=>The Data is always stored in the form of Objects and on the
objects we can perform the operations by using corresponding
Functions.
1) Classes
2) Objects
3) Data Encapsulation
4) Data Abstraction
5) Inheritance
6) Polymorphism
7) Message Passing
=====================================
Classes
=====================================
=>The purpose of classes concept is that "To develop Programmer-
defined Data type + To Develop any Real Time Application"
=>The reason for developing Programming-defined Data type is that to
decide what values to store and what operation to perform.
=>To develop any Programmer-defined data type by using classes
concept, we use a key word called 'class'.
=>Programmatically, Every Class name is treated as data type.
-----------------------
Def. of Class:-
-----------------------
=>A class is a collection of Data Members and Methods
=>When we define a class, we never get memory space for Data Members
and Methods but we get the memory space for Data Members and Methods
when we create an object w.r.t class.
201
-------------------------------------------------
=>Syntax for defining a Class:
-------------------------------------------------
class <class-name>:
Class Level Data Members
def instancemethodname(self, list of formal params):
--------------------------------------
Block of statements
Instance Data Memebers
--------------------------------------
@classmethod
def classlevelmethodname(cls, list of formal params):
--------------------------------------
Block of statements
Class Level Data Members
--------------------------------------
@staticmethod
def staticmethodname(list of formal params if any):
--------------------------------------
Block of statements
--------------------------------------
=============================================================
#empex1.py
class Employee:
def getempdata(self):
self.empno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
def dispempdata(self):
print("Employee Number:{}".format(self.empno))
print("Employee Name:{}".format(self.ename))
print("Employee Salary:{}".format(self.sal))
#main program
eo1=Employee()
eo1.getempdata()
eo1.dispempdata()
============================================================
#studex1.py
class Student:
def getstuddet(self):
self.stno=100
self.name="KVR"
#main program
so1=Student()
so1.getstuddet()
print("content of so1=", so1.__dict__) # {stno:100, name : "kvr" }
print(" id of so1 main program=",id(so1))
202
3)example:
class Sum:
def getvalues(self):
self.a=float(input("Enter First value:"))
self.b=float(input("Enter Second value:"))
def calculate(self):
self.c=self.a+self.b
def dispresult(self):
print("Val of a={}".format(self.a))
print("Val of b={}".format(self.b))
print("Sum={}".format(self.c))
#main program
s1=Sum()
s1.getvalues()
s1.calculate()
s1.dispresult()
=========================================================
Types of Data Members in Class
============================================
=>In a class of python, we can define two types of Data
Members. They are
a) Instance Data Members
b) Class Level Data Members
-------------------------------------------
a) Instance Data Members:
--------------------------------------------
=>Instance Data Members are always used for storing Specific
Values
=>Instance Data Members Memory space is created Every Time
when we
create an object and hence they are also object Level
data members
=>Instance Data Members will be created as part Instance
Methods and Constructors Only by using "self". here "self" is
one of the implicit object which contains id of explicit
object (or) current object.
self.Instance Data member name=value
(OR)
object.Instance Data member name=value
=>Instance Data Members are always accessed either w.r.t
object name or self.
self.Instance Data member name
(OR)
objectname.Instance Data member name
203
-------------------------------------------------
b) Class Level Data Members:
------------------------------------------------
=>Class Level Data Members are always used for storing Common
Values.
=>Class Level Data Members memory space created only once
irrespective of
number of objects are created.
=>Class Level Data Members will be created as part Class Level
Methods Only by using "cls" or "classname" (or) we can define
inside of Class Definition.
Syntax: cls.ClassLevel data member=value
classname.ClassLevel data member=value
=======================X=====================================
Types of Methods in Class
============================================
=>In a class of python, we can define 3 types of methods. They
are
a) Instance Methods
b) Class Level Methods
c) Static Methods
------------------------------------
a) Instance Methods:
------------------------------------
=>Instance methods are always used for performing specific
Operations. In other words Instance methods always on operates
in Instance data Members which are stored in Object.
=>Instance methods must be accessed w.r.t object name (or)
self
=>Every Instance method takes "self" as a First Parameter
Syntax:-
def methodname(self, list of formal params):
----------------------------------------------
------------------------------------------------------
204
-----------------------------------------
b) Class Level Methods
-----------------------------------------
=>Class Level methods are always used for performing Common
Operations. In other words Class Level methods always on
operates in Class Level data Members which are common for all
Object.
=>Class Level Methods can be accesssed w.r.t Class Name (or)
cls (or) self (or) object name.
=>Every Class Level method must takes "class" as a First
Parameter and whose definition must be preceded with
@classmethod decorartor
Syntax:-
@classmethod
def methodname(cls, list of formal params):
-----------------------------------------
------------------------------------------
--------------------------
c) Static Method:
---------------------------
=>These methods are used for performing Utility Operation
(Universal Operations (or) Independent Operations ).
=>Static Methos must be accessed w.r.t Class Name (or) Object
Name (or) self
=>Static Methods definition must be preceded with a pre-
defined decorator @staticmethod and this will not take "self"
or "cls"
=>Syntax:-
@staticmethod
def staticmethodname(list of formal params if any):
-----------------------------------------------
-----------------------------------------------
===========================================================
#circle.py
class Circle:
@classmethod
def setpi(cls):
cls.pi=3.14
def area(self):
Circle.setpi()
self.r=float(input("Enter radious for area:"))
self.ac=Circle.pi*self.r**2
print("Radious={}".format(self.r))
print("Area of Circle={}".format(self.ac))
def peri(self):
self.r=float(input("Enter radious for peri:"))
self.pc=2*self.pi*self.r;
print("Radious={}".format(self.r))
205
print("Peri of Circle={}".format(self.pc))
#main program
c=Circle()
c.area()
c.peri()
============================================================
#empex1.py
class Employee:
def getempdata(self):
self.empno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
def dispempdata(self):
print("Employee Number:{}".format(self.empno))
print("Employee Name:{}".format(self.ename))
print("Employee Salary:{}".format(self.sal))
#main program
eo1=Employee()
eo1.getempdata()
eo1.dispempdata()
===============================================
#InstanceClassLevelDm.py
class Student:
@classmethod
def course(cls):
cls.crs="PYTHON"
def getdata(self):
self.stno=int(input("Enter Student Number:"))
self.name=input("Enter Student Name")
self.marks=float(input("Enter Student Marks:"))
def dispdata(self):
print("Student Number:{}".format(self.stno))
print("Student Number:{}".format(self.name))
print("Student Marks:{}".format(self.marks))
print("Student Course:{}".format(Student.crs))
#main program
Student.course()
s1=Student()
print("Enter First Student Details")
s1.getdata()
s2=Student()
print("Enter Second Student Details")
s2.getdata()
print("Enter Third Student Details")
s3=Student()
206
s3.getdata()
print("S1 object data ")
s1.dispdata()
print("S2 object data ")
s2.dispdata()
print("S3 object data ")
s3.dispdata()
============================================================
#InstanceClassLevelDm1.py
class Student:
crs="PYTHON with DS" # class level Data Member
def getdata(self):
self.stno=int(input("Enter Student Number:"))
self.name=input("Enter Student Name")
self.marks=float(input("Enter Student Marks:"))
def dispdata(self):
print("Student Number:{}".format(self.stno))
print("Student Number:{}".format(self.name))
print("Student Marks:{}".format(self.marks))
print("Student Course:{}".format(Student.crs))
#main program
s1=Student()
print("Enter First Student Details")
s1.getdata()
s2=Student()
print("Enter Second Student Details")
s2.getdata()
print("Enter Third Student Details")
s3=Student()
s3.getdata()
print("S1 object data ")
s1.dispdata()
print("S2 object data ")
s2.dispdata()
print("S3 object data ")
s3.dispdata()
============================================================
#InstatMethod.py
class Sum:
def getvalues(self):
self.a=float(input("Enter First value:"))
self.b=float(input("Enter Second value:"))
self.calculate()# calling Instance method from another iinstance
self.dispresult()#calling Instance method from another iinstance
def calculate(self):
self.c=self.a+self.b
def dispresult(self):
print("Val of a={}".format(self.a))
print("Val of b={}".format(self.b))
207
print("Sum={}".format(self.c))
#main program
s1=Sum()
s1.getvalues()
======================================================================
#staticmethodex1.py
class Aop:
def readvalues(self):
self.a=float(input("Enter First Value:"))
self.b=float(input("Enter Second Value:"))
class MathCal:
@staticmethod
def calculation(obj,op ):
if(op=="+"):
print("{} + {}={}".format(obj.a,obj.b,obj.a+obj.b))
elif(op=="-"):
print("{} - {}={}".format(obj.a,obj.b,obj.a-obj.b))
elif(op=="*"):
print("{} * {}={}".format(obj.a,obj.b,obj.a*obj.b))
elif(op=="/"):
print("{} / {}={}".format(obj.a,obj.b,obj.a/obj.b))
elif(op=="//"):
print("{}//{}={}".format(obj.a,obj.b,obj.a//obj.b))
elif(op=="%"):
print("{} % {}={}".format(obj.a,obj.b,obj.a%obj.b))
elif(op=="**"):
print("{} ** {}={}".format(obj.a,obj.b,obj.a**obj.b))
else:
print("Invalid Symbol")
#main program
op=Aop()
op.readvalues()
sym=input("Enter Any Arithmetic Operation Symbol:")
MathCal.calculation(op,sym)
=========================================
#staticmethodex2.py
class Employee:
def readempvalues(self):
self.eno=int(input("Enter Employee Number:"))
self.name=input("Enter Employee Name:")
class Student:
def readstudvalues(self):
self.stno=int(input("Enter Student Number:"))
self.name=input("Enter Student Name:")
self.marks=int(input("Enter Student Marks:"))
208
class Book:
def readbookvalues(self):
self.bno=int(input("Enter Book Number:"))
self.name=input("Enter Book Name:")
self.price=int(input("Enter Book Price:"))
class Kvr:
@staticmethod
def dispobjectsdata(x ):
print(""*50)
for k,v in x.__dict__.items():
print("{}-->{}".format(k,v))
print(""*50)
#main program
eo=Employee()
eo.readempvalues()
so=Student()
so.readstudvalues()
bo=Book()
bo.readbookvalues()
print("Employee Object Values:")
Kvr.dispobjectsdata(eo )
print("Student Object Values:")
Kvr.dispobjectsdata(so )
print("Book Object Values:")
Kvr.dispobjectsdata(bo )
==============================================================
objects in Python
===================================================
=>When we define a class, memory space is not created for Data
Members and Methods but whose memory is created when we create
an object w.r.t class name.
=>To do any Data Processing, It is mandatory to create an
object.
=>To create an object, there must exists a class Definition
otherwise we get NameError
Definition of object:
-----------------------------------
=>Instance of a class is called object ( Instance is nothing
but allocating sufficient memory space for the Data Members
and Methods of a class)
-------------------------------------------------
Syntax for creating an object
-------------------------------------------------
varname=classname()
209
so=Student()
Example:- create an object Employee
eo=Employee()
-----------------------------------------------------------
class Hyd:
@staticmethod
def dispHumanInfo(obj):
print("------------------------------------")
for k,v in obj.__dict__.items():
print("{}-->{}".format(k,v))
else:
print("------------------------------------")
#main program
stud=Human()
stud.stno=10
stud.name="Ramesh"
stud.cls="X"
210
emp=Human()
emp.eno=100
emp.name="Rahul"
emp.sal=3.4
teach=Human()
teach.tno=111
teach.tname="Rossum"
teach.dsg="Author"
teach.place="NL"
print("------------------------------------")
print("Student Information")
Hyd.dispHumanInfo(stud)
print("Employee Information")
Hyd.dispHumanInfo(emp)
print("Teacher Information")
Hyd.dispHumanInfo(teach)
stud.living="HYD"
print("Student Information")
Hyd.dispHumanInfo(stud)
===========================================================
MULTI THREADING CONCEPT
=======================================================
211
========================================
Module Name----> threading
========================================
=>To develop thread based applications, In python Programming,
we muse a pre-defined module called "threading".
=>In Thread Based Applications, we have two types of threads.
They are
a) main thread
b) child / Fore ground threads
=>By Default , A Python Program contain a single thread called
"main thread"
=>Programmatically, In a Python Program, we can create
multiple Threads called "Child / Fore ground Threads" and
they are all monitored by Main Thread.
=>Hence Programmatically, we can two types of threads. they
are
a) Main Thread
b) Child / Fore ground threads
=>The purpose of main thread is that to create Child threads
and monitoring
their execution status.
=>The purpose of Child / Fore ground threads is that "To
execute the logic of
the program which is written in the form of Functions /
Methods concurrently ".
============================================================
Multi Threading in Python
===========================================
=>In OS, we have the concept called Multi Tasking. The Multi
tasking concept
of OS brought into Python on the Name of Multi Threading.
=>Hence Multi Threading is one of the specialized form of
Multi Tasking of OS.
=>The aim / purpose of Multi Threading is that "To achieve
Concurrent
Execution (or) Parallel (or) Simultaneous execution". So that
we get Fastest
Execution.
=>Definition of Thread:- A flow of control is called Thread.
=>The purpose creating a thread is that "To perform certain
operations
simultaneously / concurrently.
--------------------------------------------------------------
=>In Real time , we have two types applications. They are
a) Process Based Applications
b) Thread Based Applications.
212
----------------------------------------------------
a) Process Based Applications / Single Threaded Modelling
Languages:
--------------------------------------------------------------
----------------------------------------------------
=>These Applications contains execution environment Single
Thread
=>These Applications Provides Sequential Execution.
=>These Applications Takes More Execution time.
=>All Process Based Applications are considered as Heavy
weight
components.
Examples:- C,Cpp ...etc
--------------------------------------------------------------
--------------------------
b) Thread Based Applications / Multi Threaded Modeling
Languages:
----------------------------------------------------------
=>These Applications execution environment contains multiple
Thread
=>These Applications Provides Concurrent Execution.
=>These Applications Takes Less / fastest Execution time.
=>All Thread Based Applications are considered as light weight
components.
Examples:- Python, Java, C#.NET...etc
-------------------------------------------------------------
213
====================================
214
-------------------
Functions in threading module:
-------------------------------------------------
1)currentThread() or current_thread():
-----------------------------------------------------------
This Function is used for which thread is currently
executing
2) active_count():
------------------------
This Function is used for finding number of threads which
are actively executing in python program.
=======================================================
threading Module contains a pre-defined class called
"Thread"
-------------------------------------------------------------
Thread class:
---------------------
1) Therad(target,args)
----------------------------------
=>It is used for creating Child / Sub / Fore ground threads
=>here "target" represents the function name, which is to
be executed by
Child Thread where it contains logic.
=>here "args" represents the values to the Function name in
the form of tuple
Example:
t1=Thread(target=hello)
t2=Thread(target=hi, args=("Rossum",) )
2) start():
-------------
=>This function is used for dispatching the child Threads.
-------------
Syntax:-
--------------
threadobj.start()
3) run(self):
-------------------
=>This function is used for defining the logic of Python
program, which is executed by Child / Sub / Fore Ground
Threads.
=>This method is defined in Thread class and it must be re-
defined / Overridden inside sub class of Thread class.
4) is_alive():
-------------------
=>This function is used for checking the execution status of
a thread.
215
5) join():
-------------
=>This Function is used for making the main therad to wait
until the child thread(s) to join with main thread.
===========================================================
Number of approaches to create a thread
====================================================
=>In Python Programming, we have 3 approaches to develop
Thread based application (or) to cerate threads.
I) Developing Thread Based Application By using Functional
Approach.
II) Developing Thread Based Application By Using Sub Class of
Thread class(with OOPs).
III) Developing Thread Based Application By Non-Sub class of
Thread class(with OOPs).
----------------------------------------------------------
I) Developing Thread Based Application By using Functional
Approach.
--------------------------------------------------------
Steps:
-----------
1) import threading module
2) Define The programmer-defined Function, which
contains logic
3) create the child thread by using pre-defined class
Thread, which is present in threading module.
4) dispatch the child thread(s) by using start()
Examples:
------------------
#approach1.py
from threading import *
def hello():
print("\nName of thread executed by
hello()=",current_thread().name)
print("Hello, Good Morning")
def hi(a):
print("\nName of thread executed by
hi()=",current_thread().name)
print("Hi, Good Eveining:",a)
216
#main program
print("Name of main thread=",current_thread().name)
print("-------------------------------------------------------
---")
#create two child threads
t1=Thread(target=hello)
t2=Thread(target=hi, args=("Rossum",) )
#set the User-friendly name to the child threads
t1.name="Rakesh"
t2.name="Ram"
#dispatch the child threads
t1.start()
t2.start()
==================================X===========================
#approach11.py
from threading import *
import time
def numgen(n):
print("-"*50)
print("Numbers within {}:".format(n))
print("-"*50)
for i in range(1,n+1):
print("Val of i={}".format(i))
time.sleep(2)
print("-"*50)
#main program
print("Name of main thread=",current_thread().name)
print("Number of threads active at lineNo:15",active_count())
n=int(input("Enter How many Numbers u want to generate:"))
t1=Thread(target=numgen,args=(n,) )
#dispatch the child thread---start()
t1.start()
print("Number of threads active at lineNo:19",active_count())
=============================================================
#threadex1.py
import threading # currentThread() (or) current_thread()
def sumop():
print("By Default, Name of thread-
sumop()=",threading.current_thread().name)
a=10
b=2
c=a+b
print("Sum=",c)
def subop():
print("By Default, Name of thread-
subop()=",threading.current_thread().name)
a=10
b=2
c=a-b
print("Sub=",c)
217
#main program
print("Default Name of
thread=",threading.current_thread().name)
print("This is python Program")
print("Executed by main Thread")
print("--------------------------------------------")
sumop()
print("--------------------------------------------")
subop()
==============================================================
II) Developing Thread Based Application By Using Sub Class of
Thread class(with OOPs).
--------------------------------------------------------------
Steps:
----------
1) import threading module
2) Choose the Programmer-Defined class
3) The Programmer-defined class must inherit from Thread Class
4) The Programmer-defined class must override run() of Therad
class
Examples:
-------------------
#approachex2.py
from threading import * # step-1
class Kvr(Thread): # step-2,3
def run(self): # 4
print("i am from run()-defined in Kvr Class")
#main proram
k=Kvr() # here 'k' is an object of Kvr which itself is an
object of Thread class.
k.start()
=============================================================
#approachex21.py
import time
from threading import *
class Hyd(Thread):
def run(self):
print("\nName of thread executed by
run()=",current_thread().name)
try:
n=int(input("Enter Range, where Even Numbers u want
to generate:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*40)
print("Even Numbers within:{}".format(n))
218
print("-"*40)
for i in range(2,n+1,2):
print("Val of i={}".format(i))
time.sleep(1)
else:
print("-"*40)
except ValueError:
print("Don't enter Strs / alphanumerics/ special
sym,bols")
#main program
print("\nProgram exeuction started
with=",current_thread().name)
print("--------------------------------------------")
h=Hyd()
print(" Execution status of Child Thread Before
start=",h.is_alive()) # False
h.start()
print("Execution status of Child Thread after
start=",h.is_alive()) # True
h.join()
print("Execution status of Child Thread after
execution=",h.is_alive()) # False
=============================X=============================
III) Developing Thread Based Application By Using Non-Sub
class of Thread class(with OOPs).
---------------------------------------------------------
Steps:
-----------
1) import threading module
2) Choose the Programmer-Defined class
3) The Programmer-defined class must contain an Instance
method which contains logic of Python program executed by
Child / Sub thread(s)
Examples:
-------------------------------
#approach3.py
from threading import *
class Kvr:
def hello(self):
print("i am from hello()")
def hi(self,ms):
print("Hi,{}-> Good Morning".format(ms))
#main program
k=Kvr()
t1=Thread(target=k.hello)
t1.start()
219
t2=Thread(target=k.hi,args=("Rossum",) )
t2.start()
===================================X==========================
#approach31.py
from threading import *
import time
class MulTable:
def table(self,n):
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*40)
print("Mul Table for {}".format(n))
print("-"*40)
for i in range(1,11):
print("\t{} x {} =
{}".format(n,i,n*i))
time.sleep(1)
else:
print("-"*40)
#main program
try:
mt=MulTable()
print("Line:20->Number of Threads
active=",active_count()) # 1
n=int(input("Enter a Number for generating Mul table:"))
t=Thread(target=mt.table, args=(n,) )
t.start()
print("Line:24->Number of Threads
active=",active_count()) # 2
t.join()
print("Line:26->Number of Threads
active=",active_count()) # 1
except ValueError:
print("Don't enter Strs / alphanumerics/
special sym,bols")
==============================================================
Synchronization in Multi 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.
=>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.
220
--------------------------------------------------------------
=>Steps for implementing Synchronization Concept:
--------------------------------------------------------
1) obtain / create an object of Lock class, which is present
in threading module.
Syntax:-
----------------
lockobj=threading.Lock()
2) To obtain the lock on the sharable resource, we must use
acquire()
Syntax:
--------------
lockobj.acquire()
Once current object acquire the lock, other objects are made
wait until curent object releases the lock.
3) To un-lock the sharable resource/current object, we must
use release()
Syntax:
-------------
lockobj.release()
#syncex1.py
from threading import *
import time
def multable(n):
lk.acquire() # obtain the lock
if (n<=0):
print("{} is invalid input:".format(n))
else:
print("-"*40)
print("Mul table for :{}".format(n))
print("-"*40)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
time.sleep(1)
else:
print("-"*40)
lk.release() # release the lock
#main program
lk=Lock() # create an object of lock
t1=Thread(target=multable,args=(9,) )
t1.start()
t2=Thread(target=multable,args=(19,) )
t2.start()
t3=Thread(target=multable,args=(5,) )
t3.start()
t4=Thread(target=multable,args=(-25,) )
t4.start()
=============================================================
#non_threadex.py
import time
import threading
def squares(lst):
print("Name of thread=",threading.current_thread().name)
for val in lst:
print("square({})={}".format(val,val**2))
time.sleep(1)
def cubes(lst):
print("\nName of
thread=",threading.current_thread().name)
for val in lst:
print("cubes({})={}".format(val,val**3))
time.sleep(1)
def sqroot(lst):
print("\nName of
thread=",threading.current_thread().name)
for val in lst:
print("sqrt({})={}".format(val,val**0.5))
time.sleep(1)
222
#main program
bt=time.time()
lst=[2,5,6,-4,8,12]
squares(lst)
cubes(lst)
sqroot(lst)
et=time.time()
print("Execution time of this program is ={}".format(et-bt))
=============================================================
#threadex.py
import time
import threading
def squares(lst):
print("Name of thread=",threading.current_thread().name)
for val in lst:
print("square({})={}".format(val,val**2))
time.sleep(1)
def cubes(lst):
print("\nName of
thread=",threading.current_thread().name)
for val in lst:
print("cubes({})={}".format(val,val**3))
time.sleep(1)
def sqroot(lst):
print("\nName of
thread=",threading.current_thread().name)
for val in lst:
print("sqrt({})={}".format(val,val**0.5))
time.sleep(1)
#main program
bt=time.time()
lst=[2,5,6,-4,8,12]
t1=threading.Thread(target=squares, args=(lst,) )
t1.start()
t2=threading.Thread(target=cubes, args=(lst,) )
t2.start()
t3=threading.Thread(target=sqroot, args=(lst,) )
t3.start()
t1.join()
t2.join()
t3.join()
et=time.time()
print("Execution time of this program is ={}".format(et-bt))
223
============================================
Networking Programming in Python
============================================
=>The purpose of Network Programming is that "To share the
data between multiple machines(clients) where the common data
present in one centralized machine(Server)".
=>In Network Programming, we have to write two types of
Programs. They are
a) Server Side Program
b) Client Side Program
--------------------------------------------------------------
a)Server Side Program:
-------------------------------
=>This program ,which receives the client side program
request, Process the request and gives Response back to
client.
---------------------------------
b) Client Side Program
---------------------------------
=>This Program always makes requests to the server side
program and receives the responses from server side program.
-----------------------------------------------------
Def. of DNS(Domain Naming Service)--Host machine:
--------------------------------------------------------------
=>It is the name of machine, where the server side program
resides.
=>The Default DNS of a machine is "localhost".
--------------------------------------------------------------
Def of IP Address:
------------------------------
=>It is the Four Parts Numerical Address, where the server
side program resides.
=>The default IP address of the machine is 127.0.0.1
-----------------------------------------------------------
Def. of Port number:
------------------------------
=>It is the logical numerical Id, where server side program
is running.
-----------------------------------------------------------
Steps for developing Server Side Program:
--------------------------------------------------------------
1.Every Server Side Program must resides at DNS / IP Address
and runs at Unique Port number.
2. Server Side Program must ACCEPT the Client Side Program
request.
3. Server Side Program must READ the client side program
request, PROCESS the client side program request ( decode() ).
4. Server Side program must SEND the response back to Client
Side Program( encode() )
224
Note:
---------
=>As long as Client Side Program makes a request , the Server
side program performs steps(2)(3) and (4)
--------------------------------------------------------------
------------------------------
Steps for developing Client Side Program:
--------------------------------------------------------------
1) Every Client Side Program must get CONNECTION from Server
side Program by passing DNS/IP address and port number.
2) Client Side Program must SEND a request to the server side
Program ( encode() ).
3) Client Side Program RECEIVE the response from Server Side
Program ( decode() ).
------------
NOTE:
------------
=>If the Client Side Program want to make multiple Requests
and receives multiple responses then perform steps(2) and (3)
============================X===============================
Module Name in Networking Programming
============================================
=>To deal with Networking in python, we use a pre-defined module called
"socket".
=>The module socket contains functions for developing both client and
server side programs.
-----------------------------------------------------------------------
Functions of socket module used in Server Side Program
----------------------------------------------------------------------
1) Socket():
-----------------
=>This function is used for creating an object of Socket and it acts as
Bi-directional communication Entity between Client Side Program and
Server Side Program.
Syntax:-
sockobj=socket.socket()
-------------------------------------------------------------------
2) bind():
------------
=>This function is used making the program as Server Side Program by
passing DNS (or) IP address and port number in the form tuple that
program acts as server side program.
Syntax:- sockobj.bind( (DNS, portno) )
Examples:--
sockobj.bind( ("localhost", 99999) )
(or)
sockobj.bind("127.0.0.1", 88888)
print("Server Side Program is ready to accept any client side
request")
-------------------------------------------------------------------
225
3) listen():
---------------
=>This function is used for configuring the Server Side program in such
way that how many requests can handle and can provide responses to
client side program(s).
Syntax:- var1,var2=sockobj.accept()
here var1, and var2 represents connection and address of Client Side
Program.
Examples:- conn,addr=sockobj.accept()
-----------------------------------------------------------------------
5) recv():<-----decode()
-------------
=>This function is used for receving the data of client side program
at server side (request receiving ) program and it can be in client
side program for receiving server side program data (response receiving
)
=>The function receives data of size 1024 bytes (or) 2048 bytes (or)
4096 bytes etc.
=>while we are applying the recv(), data must be decoded with decode()
and it returns
the data in the form of str.
Syntax:-
strdata=sockobj.recv(1024).decode()
-----------------------------------------------------------------------
6) send():
--------------
=>This Function is used for sending the data of the client(request) and
sending the data of server(response) to the client by encoding.
Syntax:- sockobj.send("clientdata".encode())
-----------------------------------------------------------------------
7) connect():
---------------------------
=>This function is used for getting the coinnection by client side
program from server side program by passing DNS and Portno.
Examples: sockobj.connect("localhost",9999)
print("client program obtains connection with Server
Side Program")
============================X======================================
226
===============================================
EXAMPLE-1:
#chatclient.py
import socket
#step-1
s=socket.socket()
#step-2
s.connect(("localhost",11111))
print("-"*50)
print("CSP got connected to SSP")
print("-"*50)
#step-3
cdata=input("Enter Client Message:")
s.send(cdata.encode())
#step-4
sdata=s.recv(1024).decode()
print("SSP data at CSP-->{}".format(sdata))
#ChatServer.py
import socket
#step-1
s=socket.socket()
s.bind(("localhost",11111) )
227
s.listen(2)
print("-"*50)
print("SSP is ready to accept any CSP request")
print("-"*50)
while(True):
#step-2
con,adr=s.accept()
#step-3
cdata=con.recv(1024).decode()
print("Client Data at Server->{}".format(cdata))
sdata=input("SSP Message to Client:")
#step-4
con.send(sdata.encode())
==============================================================
EXAMPLE-2:
----------
#ClientSquare.py
import socket
#step-1
sobj=socket.socket()
sobj.connect( ("localhost",9999) )
print("-"*50)
print("Client Side Program got connection from Server Side
Program")
print("-"*50)
#step-2
cdata=input("Enter a number:")
sobj.send(cdata.encode())
#step-3
serverdata=sobj.recv(1024).decode()
print("Result from Server Side Program at
Client={}".format(serverdata))
#ServerSquare.py
import socket
#step-1
sockobj=socket.socket()
sockobj.bind( ("localhost",9999) )
sockobj.listen(4)
print("-"*50)
print("Server Side Program Ready to receive the Client
Requests:")
print("-"*50)
while(True):
228
conn,addr=sockobj.accept() # step-2
#step-3
clientdata=conn.recv(1024).decode()
print("Client Data at Server Side
Program={}".format(clientdata))
val=float(clientdata)
result=val**2 #Process
#step-4
conn.send(str(result).encode() )
==============================================================
String Handling in Python
=========================================
=>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 operations on String data, we have to use the following the
functions.
---------------------------------------------------
1) capitalize():
----------------------
=>This function is used for capitalizing the given str data
=>Syntax: varname=strobj.capitalize()
-----------------
Examples:
-----------------
>>> s="python is an oop lang"
>>> print(s,type(s))---------python is an oop lang <class 'str'>
>>> cs=s.capitalize()
>>> print(cs,type(cs))---- Python is an oop lang <class 'str'>
>>> print(s,type(s))---- python is an oop lang <class 'str'>
---------------------------------------------------------------------------------
2) title():
--------------
=>This Function is used for all words First Characters as capital.
=>Syntax:- varname=strobj.title()
Examples:
----------------
>>> s="python is an oop lang"
>>> ts=s.title()
>>> print(ts,type(ts))--------Python Is An Oop Lang <class 'str'>
>>> print(s,type(s))-----python is an oop lang <class 'str'>
------------------------------------------------------------------------------
3) find():
-------------
=>This function is used for finding an index of the first occurance of specified str
data in the given str data.
=>If the data found then it returns Its +ve index value
=>If the data not found then it returns -1
229
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"
>>> s.isalnum()-----------False
>>> s="python"
>>> s.isalnum()--------True
-------------------------------------------------------------------------------------------------
5) isalpha():
----------------
230
=>This Function returns True provided str data contains only Alphabets otherwise it
returns False.
=>Syntax:- varname=strobj.isalpha()
Examples:
-----------------
>>> s="Python"
>>> b=s.isalpha()
>>> print(b)------------True
>>> s="1234"
>>> print(s.isalpha())--------False
>>> s="python1234"
>>> print(s.isalpha())-------False
>>> s="python_1234"
>>> print(s.isalpha())-------False
------------------------------------------------------------------------------
6) isdigit():
-------------------
=>This Function returns True provided str data contains only purly digits(0-9)
otherwise it returns False.
Syntax:- varname=strobj.isdigit()
or
strobj.isdigit()
Examples:
-----------------
>>> a="1234"
>>> print(a.isdigit())------------True
>>> a="pyth1234"
>>> print(a.isdigit())--------False
>>> a="python"
>>> print(a.isdigit())------False
>>> a="pyth#$123"
>>> print(a.isdigit())---------False
------------------------------------------------------------------------------
7) islower() :
--------------------
=>This Function returns True provided the str data is completely available in
lowercase otherwise it returns False.
Syntax:- varname=strobj.islower()
or
strobj.islower()
Examples:
-----------------
>>> s="python"
>>> print(s.islower())----------True
>>> s="Python"
>>> print(s.islower())---------False
>>> s="python is an oop lang"
231
>>> print(s.islower())----True
>>> s="python is An oop lang"
>>> print(s.islower())-------False
------------------------------------------------------------------------------
8) isupper() :
--------------------
=>This Function returns True provided the str data is completely available in upper
case otherwise it returns False.
Syntax:- varname=strobj.isupper()
or
strobj.isupper()
Examples:
------------------
>>> s="Python"
>>> print(s.isupper())----------False
>>> s="PYTHON"
>>> print(s.isupper())-------True
>>> s="python is an oop lang"
>>> print(s.isupper())---------False
>>> s="PYTHON IS AN OOP LANG"
>>> print(s.isupper())-------True
--------------------------------------------------------------------------------
9) isspace()
-------------------
=>This Function returns True provided str data contains purely space otherwise it
returns False.
=>Syntax:- varname=strobj.isapce()
(or)
strobj.isapce()
Examples:
-----------------
>>> s="Python is an oop"
>>> print(s.isspace())--------False
>>> s=" "
>>> print(s.isspace())--------True
>>> s=" "
>>> print(s.isspace())--------True
>>> s="123 345"
>>> print(s.isspace())---False
---------------------------------------------------------------------------------------
10) upper():
--------------------
=>This Function is used for converting lower case data into upper case data.
Syntax:- varname=strobj.upper()
232
11) lower():
--------------------
=>This Function is used for converting upper case data into lower case data.
Syntax:- varname=strobj.lower()
Examples:
-----------------
>>> s="python is an oop lang"
>>> uc=s.upper()
>>> print(uc)-------PYTHON IS AN OOP LANG
>>> print(s)-------python is an oop lang
>>> print(uc)---- PYTHON IS AN OOP LANG
>>> lc=uc.lower()
>>> print(lc)-------- python is an oop lang
--------------------------------------------------------------------------------
12) join():
--------------
=>This Function is used concatinating all the sequence of values which are available
in the form str
Syntax:- varname=strobj1.join(iterable obj)
Examples-:
----------------
>>> print(tpl, type(tpl))--('java', 'python', 'Data Science') <class 'tuple'>
>>> s2=""
>>> s3=s2.join(tpl)
>>> print(s3)---->javapythonData Science
---------------------------------------------------------------------------------------
13)split():
--------------------
=>This function is used for splitting the given str data into different tokens based
spitting value. The default splitting value is space
=>This Function returns splitting values in the form of list.
Syntax:- listobj=strobj.split()
listobj=strobj.split("spliting value")
Examples:
----------------
>>> s="Python is an oop lang"
>>> s.split()--------- ['Python', 'is', 'an', 'oop', 'lang']
>>> s="9-11-2021"
>>> l=s.split("-")
>>> print(l)----------['9', '11', '2021']
>>> s="apple#kiwi#guava-banana"
>>> l=s.split("#")
>>> print(l)----------['apple', 'kiwi', 'guava-banana']
>>> l[2].split("-")--------['guava', 'banana']
============================X===================================
233
14) len():
---------------
=>This functions is used for finding number of values present
in str data
Syntax:- len(strobj)
varname=len(strobj)
Example:
----------------
>>> s1="python"
>>> len(s1)
6
----------------------------------------------------------
15) max():- Used for finding max letter from str data
Syntax:- max(strobj)
15) min():- Used for finding min letter from str data
Syntax:- min(strobj)
Examples:
------------------
>>> s="PYTHON"
>>> max(s)-------------'Y'
>>> min(s)------------'H'
------------------------------------------------------------
===========================================================
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 keeping object empty
---------------------------------------
Definition of Constructor:
---------------------------------------
=>A constructor is one of the Special Method which is
automatically / implicitly called by PVM during Object
Creation and whose purpose is To Initialize the object with
our own values( Without empty).
-------------
Syntax:
-------------
def __init__(self,list formal params if any):
------------------------------
block of stmts--Initlization
------------------------------
234
#consex1.py
class Test:
def __init__(self): # Default Constructor
self.a=10
self.b=20
print("Val of a={}".format(self.a))
print("Val of b={}".format(self.b))
235
#main program
print("Object T1 Values:")
t1=Test()
print("Object T2 Values:")
t2=Test()
print("Object T3 Values:")
t3=Test()
=============================================================
1) Parameterized Constructor:
--------------------------------------------------------------
=>A Constructor is said to be a Parameterized Constructor if
and only if it always takes parameters.
#consex2.py
class Test:
def __init__(self, sno,sname):# Parameterized
constructor
self.sno=sno
self.name=sname
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.name))
#main program
print("Object T1 Values:")
t1=Test(10,"RS")
print("Object T2 Values:")
t2=Test(20,"JG")
print("Object T3 Values:")
t3=Test(30,"DR")
============================================================
=>In class of python, we can't define both default and
parameterized constructors. But we can achieve the
functionality of both default and parameterized constructors
with default parameter passing mechanism.
236
#consex3.py
class Employee:
"""def __init__(self): Don't write this
self.eno=1
self.ename="Rossum"""
def __init__(self,eno=1,ename="Rossum"):
self.eno=eno
self.ename=ename
print("Emp Number:{}".format(self.eno))
print("Emp Name:{}".format(self.ename))
#main program
print("Object eo1 Values:")
eo1=Employee()
print("Object eo2 Values:")
eo2=Employee(10,"Gosling")
print("Object eo3 Values:")
eo3=Employee(20,"Ritche")
========================================================
#emp.py
class Employee:
def setvalues(self):
self.eno=10
self.ename="KVR"
#main program
eo=Employee()
print("content of eo before setvalues()=",eo.__dict__) # { }
eo.setvalues()
print("content of eo after setvalues()=",eo.__dict__) # { }
========================================================
#empex1.py
class Employee:
def __init__(self):
print("i am from constructor:")
self.eno=10
self.ename="KVR"
#main program
eo=Employee()
print("content of eo =",eo.__dict__) # { }
237
========================================
Destructors in Python
========================================
=>Destructor is one of the program / Function / Method, which
is automatically called by Garbage Collector once program
execution completed .
=>A Garbage Collector is one of the program, which is running
behind of Python Program which collecting un-used memory
space.
=>A Garbage Collector is internally calling a pre-defined
function called __del__(self)
=>We can make the Garbage Collector forcibly to call
__del__(self) by making object value as None.( Syntax:
objname=None )
print("-"*40)
def __del__(self):
print("\nThis Fun called by Garbage Collector
automatically")
#main program
eo1=Employee(10,"Sai",3.4)
eo2=Employee(20,"Shekar",3.45)
eo3=Employee(30,"Srinu",4.5)
print("\nProgram execution completed")
time.sleep(5)
===========================================
#destex2.py
import time
class Employee:
def __init__(self,eno,ename,sal):
self.eno=eno
self.ename=ename
self.sal=sal
print("-"*40)
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("Employee Salary:{}".format(self.sal))
print("-"*40)
def __del__(self):
print("\nThis Fun called by Garbage Collector
automatically")
#main program
eo1=Employee(10,"Sai",3.4)
print("We are no longer interested to maintain eo1 memory
space")
time.sleep(10)
eo1=None
eo2=Employee(20,"Shekar",3.45)
print("We are no longer interested to maintain eo2 memory
space")
time.sleep(10)
eo2=None
eo3=Employee(30,"Srinu",4.5)
print("We are no longer interested to maintain eo3 memory
space")
time.sleep(10)
eo3=None
239
#destex3.py
import time
class Employee:
def __init__(self,eno,ename):
self.eno=eno
self.ename=ename
print("-"*40)
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("-"*40)
def __del__(self):
print("\nThis Fun called by Garbage Collector
automatically")
#main program
eo1=Employee(10,"Sai")
eo2=eo1 # deep copy
print("We are no longer interested to maintain eo1 memory
space")
time.sleep(10)
eo1=None
print("We are no longer interested to maintain eo2 memory
space")
time.sleep(10)
eo2=None
==============================================================
#gc1.py
import gc
print("Is GC running behind of this program by default
=",gc.isenabled())
gc.disable()
print("Is GC running behind of this program after disabled
=",gc.isenabled())
gc.enable()
print("Is GC running behind of this program after enable
=",gc.isenabled())
print("This is a python program")
l=list()
l.append(10)
l.append("Python")
print("content of l",l)
240
#gcdestex4.py
import time,gc
class Employee:
def __init__(self,eno,ename):
self.eno=eno
self.ename=ename
print("-"*40)
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("-"*40)
def __del__(self):
print("\nThis Fun called by Garbage Collector
automatically")
#main program
print("Is GC running behind of this program by default
=",gc.isenabled())
gc.disable()
print("Is GC running behind of this program after disabled
=",gc.isenabled())
print("-"*50)
eo1=Employee(10,"Sai")
eo2=eo1 # deep copy
print("We are no longer interested to maintain eo1 memory
space")
time.sleep(10)
eo1=None
print("We are no longer interested to maintain eo2 memory
space")
time.sleep(10)
eo2=None
===========================================================
Introduction to Inheritance
============================================
=>The purpose of Inheritance is that "To build Re-usable
Applications".
----------------------------------
=>Def. of Inheritance:
----------------------------------
=>The process of obtaining the Data Members and
Methods(Features) from one class into another class .
-----------------------------------------------------------
Advantages of Inheritance:
-----------------------------------------------------------
=>Application development time is less.
=>Application Memory space is Less.
=>Application Execution time is less.
=>Redundancy(duplication) of the code is minimized.
=>Application Performance is Enhanced.
=============================X==========================
Types of Inheritances
=========================================
=>Types of Inheritances makes us to understand, how to re-use
the features from one class into another class.
=>We have 5 types of Inheritances. They are
1) Single Inheritance
2) Multi Level Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance
5) Hybrid Inheritance
-----------------------------------------------------------------------
=======================================================================
242
=============================================================
Inheriting the features of Base class into Derived Class
======================================================
=>Features of a class are nothing but Data Members, Methods
and
constructors.
=>To Inherit the Data Members, Methods and constructors from
Base class into Derived class, we use the following syntax:
-------------
Syntax:
------------
class <clsname-1>: # Base Class-1
-------------------
-------------------
-----------------------
Exaplanation:
----------------------
=>Here clsname-1,clsname-2......clsname-n are called Base
Classes.
=>here clsname-n+1 is called Derived class.
=>When we develop any inheritance application, It is always
recommended to create an object of Bottom most derived class
bcoz it inheritance all features of Base Class and
Intermediate Base classes.
243
#InhProg1.py
class BC:
def disp(self):
self.a=10
self.b=20
def show(self):
print("Val of a=",self.a)
print("Val of b=",self.b)
class DC(BC):
def show1(self):
print("Val of a of BC={}".format(self.a))
print("Val of b of BC={}".format(self.b))
#main program
do1=DC()
do1.disp()
do1.show()
do1.show1()
========================================================
#InhProg2.py
class Company:
def getcompdet(self):
self.cname=input("Enter Company Name:")
self.cloc=input("Enteer Company Location:")
def dispcompdet(self):
print("Company Name:{}".format(self.cname))
print("Company Location:{}".format(self.cloc))
class Employee(Company):
def getempdet(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
def dispempdet(self):
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("Employee Salary:{}".format(self.sal))
#main program
eo=Employee()
eo.getempdet()
eo.getcompdet()
print("--------------------------------------------")
eo.dispempdet()
eo.dispcompdet()
print("--------------------------------------------")
244
#InhProg3.py
class Company:
def getcompdet(self):
self.cname=input("Enter Company Name:")
self.cloc=input("Enteer Company Location:")
def dispcompdet(self):
print("Company Name:{}".format(self.cname))
print("Company Location:{}".format(self.cloc))
class Employee(Company):
def getempdet(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
self.getcompdet() # calling base class method
def dispempdet(self):
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("Employee Salary:{}".format(self.sal))
self.dispcompdet() # calling base class method
#main program
eo=Employee()
eo.getempdet()
eo.dispempdet()
============================================================
#comp.py----File Name and treated as Module Name(comp.cpython-
39.pyc)
class Company:
def getcompdet(self):
self.cname=input("Enter Company Name:")
self.cloc=input("Enteer Company Location:")
def dispcompdet(self):
print("Company Name:{}".format(self.cname))
print("Company Location:{}".format(self.cloc))
#empcompdemo.py
from emp import Employee
eo=Employee()
eo.getempdet()
eo.dispempdet()
============================================================
Method Overriding
==================================
=>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 Various Operations
is called Method Overriding.
=>To use Method Overriding in Python Program , we must apply
Inheritance Process.
=>The Method Overriding Programming Facility used in
Polymorphism Principle.
==================================
Polymorphism
==================================
=>Polymorphism is one of the distinct feature of OOPs
=>The main purpose of Polymorphism is that "To get Efficient
Memory Management (Less Memory Space)"
-------------------------------
=>Def of Polymorphism:
-------------------------------
=>The Process of Representing "One Form in Multiple Forms" is
called Polymorphism.
-------------------------------------------------------------
#PloyEx1.py
class Circle:
def draw(self): # Original Method--one form
print("Drawing Circle:")
class Rect(Circle):
def draw(self): # Overridden method--multiple forms
print("Drawing Rectangle")
#super().draw() # will call draw() of Circle
class
class Square(Rect):
def draw(self): # Overridden method--multiple forms
print("Drawing Square")
super().draw() # will call draw() of Rect class
#super().super().draw() ---Invalid Syntax
#main program
so=Square()
so.draw()
========================================================
#PolyEx2.py
class Circle:
def draw(self): # Original Method--one form
print("Drawing Circle:")
class Rect(Circle):
def draw(self): # Overridden method--multiple forms
print("Drawing Rectangle")
class Square(Rect):
def draw(self): # Overridden method--multiple forms
print("Drawing Square")
Rect.draw(self) # will call draw() of Rect class
Circle.draw(self)
#main program
so=Square()
so.draw()
247
#ployex3.py
class Teacher:
def __init__(self,tname): #original Constructor
print("{} is Teacher always
teaches".format(tname))
class Business(Teacher):
def __init__(self,bmname): # Overridden Constructor
print("{}, is Business man will do
business".format(bmname))
super().__init__("Rossum") # OR
Teacher.__init__(self,"Gosling")
#main program
b=Business("Ravi")
==============================================================
#polyex4.py
class Circle:
def area(self): # original method
self.r=float(input("Enter Radious:"))
self.ac=3.14*self.r**2
print("Area of Circle={}".format(self.ac))
class Rect(Circle):
def area(self): #overridden method
self.l=float(input("Enter Length:"))
self.b=float(input("Enter Breadth:"))
self.ar=self.l*self.b
print("Area of Rectangle:{}".format(self.ar))
print("----------------------------------------")
super().area() # calling area() of Circle
class Square(Rect):
def area(self): #overridden method
self.s=float(input("Enter Side:"))
self.as1=self.s**2
print("Area of Square={}".format(self.as1))
print("---------------------------------------")
super().area() # calling area() of Rect
#main program
so=Square()
so.area()
=============================================================
#polyex5.py
class Circle:
def area(self): # original method
self.r=float(input("Enter Radious:"))
self.ac=3.14*self.r**2
print("Area of Circle={}".format(self.ac))
class Rect(Circle):
def area(self): #overridden method
self.l=float(input("Enter Length:"))
self.b=float(input("Enter Breadth:"))
self.ar=self.l*self.b
248
print("Area of Rectangle:{}".format(self.ar))
print("---------------------------------------")
class Square(Rect):
def area(self): #overridden method
self.s=float(input("Enter Side:"))
self.as1=self.s**2
print("Area of Square={}".format(self.as1))
print("--------------------------------------")
Rect.area(self) # calling area() of Rect class
Circle.area(self) # calling area() of Circle
class
#main program
so=Square()
so.area()
============================================================
#polyex6.py
class Circle:
def __init__(self,r): # original method
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
class Rect(Circle):
def __init__(self): #overridden method
self.l=float(input("Enter Length:"))
self.b=float(input("Enter Breadth:"))
self.ar=self.l*self.b
print("Area of Rectangle:{}".format(self.ar))
print("---------------------------------------")
super().__init__(float(input("Enter Radious:")))
class Square(Rect):
def __init__(self): #overridden method
self.s=float(input("Enter Side:"))
self.as1=self.s**2
print("Area of Square={}".format(self.as1))
print("---------------------------------")
super().__init__()
#main program
so=Square()
===========================================================
#polyex7.py
class Circle:
def __init__(self,r): # original method
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
class Rect(Circle):
def __init__(self): #overridden method
self.l=float(input("Enter Length:"))
self.b=float(input("Enter Breadth:"))
self.ar=self.l*self.b
print("Area of Rectangle:{}".format(self.ar))
print("---------------------------------")
249
class Square(Rect):
def __init__(self): #overridden method
self.s=float(input("Enter Side:"))
self.as1=self.s**2
print("Area of Square={}".format(self.as1))
print("---------------------------------")
Rect.__init__(self)
Circle.__init__(self,float(input("Enter
Radious:")))
#main program
so=Square()
=============================================================
#ploy8.py
class India:
def lang(self):
print("Indians can speak multiple languages:")
def type(self):
print("India is a developing country:")
class USA:
def lang(self):
print("Americans can speak English languages:")
def type(self):
print("USA is a developed country:")
#main program
io1=India()
uo=USA()
l=list()
l.append(io1)
l.append(uo)
for obj in l: # here obj contains reference of io1 and uo
and obj is called
polymorphic object.
obj.lang()
obj.type()
print("---------------------------------------")
==========================================================
Data Encapsulation and Data Abstraction
================================================
=>The Process of Hiding the data members and methods of a
class from external programmers is called Data Encapsulation.
=>Data Hinding is fundamental purpose of Data Encapsulation.
=>In python, to Implement Data Encapsulation, the data members
and methods of the class must be preceded with __
250
---------------
Example:
--------------
#account.py--File name and acts as Module name
class Account:
def __init__(self):
self.__acno=1111
self.cname="Rossum"
self.__bal=3.4
self.bname="SBI"
self.__pin=1234
def __openpin(self):
print("i am from openpin()")
--------------------------------------------------------------
=>The process of retrieving the essential details without
considering Hidden details is called Data Abstraction.
#others.py
from account import Account
ao=Account()
#print("Account Number=",ao.acno)-----> can't access
print("Account Holder Name=",ao.cname)
#print("Account Balance=",ao.bal)----->can't access
print("Account Branch Name=",ao.bname)
#print("Account Pin=",ao.pin)---->can't access
==========================================
Numpy
==========================================
Introduction to Numpy:
-------------------------------------
=>Numpy stands for Numerical Python.
=>Numpy is one of the pre-defined third party module / Library.
=>To use numpy as a part of our python program, we must install
numpy
=>module explicitly by using a tool called pip and it present in
(C:\Users\nareshit\AppData\Local\Programs\Python\Python39\Scripts
)
=>Syntax for installing any module:
>>> print(a.ndim)----1
>>> print(a.shape)----(4,)
-------------------------------------------
>>> l1=[10,20,30,40]
>>> a=np.array(l1,dtype='float')
>>> print(a,type(a))----[10. 20. 30. 40.] <class 'numpy.ndarray'>
>>> a--------------array([10., 20., 30., 40.])
>>> l1=[12.3,34.5,56.78]
>>> a=np.array(l1,dtype='float')
>>> print(a, type(a))--------[12.3 34.5 56.78] <class
'numpy.ndarray'>
>>> a------------array([12.3 , 34.5 , 56.78])
>>> print(a.ndim)-------1
>>> print(a.shape)-------(3,)
>>> print(a.dtype)------float64
-----------------
>>> l1=[10,10.25,24,23.45,30]
>>> a=np.array(l1)
>>> print(a)------[10. 10.25 24. 23.45 30. ]
>>> a---------array([10. , 10.25, 24. , 23.45, 30. ])
>>> print(a.dtype)-------float64
>>> l2=[10,20,30]
>>> a=np.array(l2)
>>> a---------array([10, 20, 30])
>>> print(a.dtype)--------int32
---------------------------------
>>> l1=["RS","RT","JG"]
>>> a=np.array(l1)
>>> a
array(['RS', 'RT', 'JG'], dtype='<U2')
>>> print(a.dtype)----<U2
>>> l1=["Rossum","RT","JG"]
>>> a=np.array(l1)
>>> a
array(['Rossum', 'RT', 'JG'], dtype='<U6')
----------------------------------
>>> l1=[10,"KVR",23.45,True,2+3j]
>>> a=np.array(l1)
>>> print(a)----['10' 'KVR' '23.45' 'True' '(2+3j)']
>>> print(a.ndim)------1
>>> print(a.shape)----(5,)
>>> print(a.dtype)---- <U64
-------------------------------------------------------------------
>>> l1=[ [10,20], [30,40] ]
>>> a=np.array(l1)
>>> a------->array([[10, 20],
[30, 40]])
>>> print(a.ndim)
2
>>> print(a.shape)
(2, 2)
>>> print(a.dtype)
int32
-------------------------------------
>>> l1=[[10,20,30], [40,50,60],[70,80,90]]
>>> a=np.array(l1)
254
>>> a
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
>>> print(a.ndim)
2
>>> print(a.shape)
(3, 3)
>>> print(a.dtype)
int32
------------------------------------------------------
>>> l1=[[10,20,30], [40,50,60]]
>>> a=np.array(l1)
>>> a
array([[10, 20, 30],
[40, 50, 60]])
>>> print(a.ndim)
2
>>> print(a.shape)
(2, 3)
>>> b=a.reshape(3,2)
>>> b
array([[10, 20],
[30, 40],
[50, 60]])
>>> print(b.ndim)
2
>>> print(b.shape)
(3, 2)
---------------------------------------
>>> l1=[[[10,20],[30,40]],[[50,60],[70,80]] ]
>>> a=np.array(l1)
>>> a
array([[[10, 20],
[30, 40]],
[[50, 60],
[70, 80]]])
>>> print(a.ndim)
3
>>> print(a.shape)
(2, 2, 2)
>>> print(a[0])
[[10 20]
[30 40]]
>>> print(a[1])
[[50 60]
[70 80]]
255
2) arange():
--------------------
=>Syntax:- ndarrayobjname=numpy.arange(begin,end,step, dtype)
>>> a=np.zeros(12,dtype=int)
>>> a
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> b=a.reshape(3,4)
>>> c=a.reshape(4,3)
>>> print(b)
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
>>> print(c)
[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
>>> print(type(a),type(b),type(c))------→
<class 'numpy.ndarray'> <class 'numpy.ndarray'> <class
'numpy.ndarray'>
>>> a=np.zeros((3,3) )
>>> a=np.zeros(shape=(3,3),dtype=int )
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros(shape=(2,3),dtype=int )
>>> a
array([[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros(shape=(4,2),dtype=int )
>>> a
array([[0, 0],
[0, 0],
[0, 0],
[0, 0]])
--------------------------------------------------------------
-----------------------------------
4)ones()
--------------
=>This function is used building a matrix with 1's (or)
creating an object ndarray by initializing with all 1's.
=>Syntax:- ndarrayobj=numpy.ones(shape,dtype)
Examples:
-----------------
>>> a=np.ones(6)
>>> print(a,type(a))
[1. 1. 1. 1. 1. 1.] <class 'numpy.ndarray'>
>>> print(a.ndim,a.shape,a.dtype)----→1 (6,) float64
>>> print(a.reshape(3,2))
[[1. 1.]
[1. 1.]
[1. 1.]]
>>> print(a.reshape(2,3))
258
[[1. 1. 1.]
[1. 1. 1.]]
>>> a=np.ones(8,dtype=int)
>>> print(a,type(a))
[1 1 1 1 1 1 1 1] <class 'numpy.ndarray'>
>>> print(a.reshape(4,2))
[[1 1]
[1 1]
[1 1]
[1 1]]
>>> a=np.ones( (3,4),dtype=int)
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> print(a.reshape(4,3))
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]]
>>> a=np.ones( (2,3,4),dtype=int)
>>> a
array([[[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=np.ones( (3,3,4),dtype=int)
>>> a
array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]])
>>> print(a.ndim)----→3
>>> print(a.shape)----→(3, 3, 4)
-------------------------------------------------------------
5) full():
------------
=>Syntax:- ndarrayobj=numpy.full(shape, fill_value, dtype)
259
[[8, 8],
[8, 8]],
[[8, 8],
[8, 8]]])
6) eye()
-----------------
Syntax:- ndarrayobj=numpy.eye(N,M=None,K=0,dtype)
=>Here N represents No. of Rows
=>Here M represents No. of Columns. If we don't specify the M
value then N value will be considered as M value.
=>If we take M value explicitly then It will form Possible
Identity matrix (NXM)and remaining elements filled with
zeros.
=>Here K represents Principal Diagonal
( if K=0 then it is Principal Diagonal and it is default)
( if K=-1,-2...then it is considered as bellow Principal
Diagnal)
260
>>> np.eye(3,4,dtype=int)
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
>>> np.eye(4,3,dtype=int)
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]])
>>> np.eye(5,6,dtype=int)
array([[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]])
>>> np.eye(5,6,k=-1,dtype=int)
array([[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]])
>>> np.eye(5,6,k=-2,dtype=int)
array([[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]])
>>> np.eye(5,6,k=-3,dtype=int)
array([[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]])
>>> np.eye(5,6,k=1,dtype=int)
array([[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
261
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1]])
>>> np.eye(5,6,k=2,dtype=int)
array([[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]])
>>> np.eye(5,6,k=3,dtype=int)
array([[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
>>> np.eye(5,6,k=4,dtype=int)
array([[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
----------------------------------------------------------
7)identity()
------------------
=>This function generates only Square Identity Matrix
Syntax:- ndarrayobj=numpy.identity(n,dtype)
=>Here 'n' represent nxn identity matrix and it will be
considered as Rows and columns.
Example:
---------------
>>> a=np.identity(3)
>>> print(a, type(a))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] <class 'numpy.ndarray'>
>>> a
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> a=np.identity(3,dtype=int)
>>> a
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> a=np.identity(4,dtype=int)
>>> a
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
262
=========================================
Numpy--Arithmetic Operations
=========================================
=>To perform Arithmetic Operations on the objects of ndarray
in numpy programming, we use the following functions.
a) add()
b) subtract()
c) multiply()
d) divide()
a) add():
--------------
Syntax:- varname=numpy.add(ndarrayobj1, ndarrayobj2)
=>This function is used for adding elements of ndarrayobj1,
ndarrayobj2 and result can be displayed
Examples:
-----------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
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
263
array([[2, 3],
[4, 5]])
>>> kvr=np.add(x,k)----ValueError: operands could not be
broadcast together with shapes (2,3) (2,2)
---------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=a+b # we used operator + instead of add()
>>> c
array([[11, 22],
[33, 44]])
=================================
b) subtract()
Syntax:- varname=numpy.subtract(ndarrayobj1, ndarrayobj2)
=>This function is used for subtracting elements of
ndarrayobj1, ndarrayobj2 and result can be displayed
Examples:
------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.subtract(a,b)
>>> c
array([[ 9, 18],
[27, 36]])
-----------------------------------
>>> d=a-b
>>> d
array([[ 9, 18],
[27, 36]])
===================================
264
c) multiply():
-----------------------
Syntax:- varname=numpy.multiply(ndarrayobj1, ndarrayobj2)
=>This function is used for performing element-wise
multiplication of ndarrayobj1, ndarrayobj2 and result can be
displayed
Note:- To perform Matrix Multiplication we dot()
Syntax: varname=numpy.dot(ndarrayobj1, ndarrayobj2)
Examples:
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> c=np.multiply(a,b)
>>> c
array([[ 5, 12],
[12, 12]])
>>> e=a*b
>>> e
array([[ 5, 12],
[12, 12]])
------------------------------------------
>>> d=np.dot(a,b)
>>> d
array([[13, 12],
[31, 30]])
--------------------------------------------------------------
---------------
d) 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)
265
>>> c
array([[10., 10.],
[10., 10.]])
>>> d=a/b
>>> d
array([[10., 10.],
[10., 10.]])
---------------------------------------------
>>> e=a%b
>>> e
array([[0, 0],
[0, 0]], dtype=int32)
>>> f=a**b
>>> f
array([[ 10, 400],
[ 27000, 2560000]], dtype=int32)
==================================X==========================
Numpy--Statstical Functions
===============================================
=>The most essential Numpy—Statistical Functions are
a) amax()
b) amin()
c) mean()
d) median()
e) var()
f) std ()
--------------------------------------------------------------
------------------------------------------------------
a) amax()
-------------------------------
=>This function are used for finding max element from given
ndarray object
>>> a=np.array([[10,20,30],[40,50,60],[12,13,14]])
>>> print(a)
[[10 20 30]
[40 50 60]
[12 13 14]]
>>> a
array([[10, 20, 30],
[40, 50, 60],
[12, 13, 14]])
266
>>> np.amax(a)-----→60
>>> np.amin(a)----→10
>>> np.amax(a,axis=0)------→array([40, 50, 60])
>>> np.amax(a,axis=1)------→array([30, 60, 14])
>>> np.amin(a,axis=0)------→array([10, 13, 14])
>>> np.amin(a,axis=1)-----→array([10, 40, 12])
>>> a[:,0:1]
array([[10],
[40],
[12]])
>>> b=a[:,0:1]
>>> print(b)
[[10]
[40]
[12]]
>>> np.amax(b)----→40
>>> np.amin(b)----→10
>>> np.amax(b,axis=0)-----→array([40])
>>> np.amax(b,axis=1)-----→array([10, 40, 12])
=============================================================
b) amin():
----------------
=>This function are used for finding min element from given
ndarray object
c) mean():
--------------
=>The mean is defined as "Sum of all elements of ndarray
divided by total number of elements".
Syntax1:- numpy.mean(array1) # here without axis all the
elements of matix
# elements will be considered and calculated mean
Example:
-------------
>>> import numpy as np
>>> l1=[ [2,1],[4,3],[3,5] ]
>>> a=np.array(l1)
>>> a
array([[2, 1],
[4, 3],
[3, 5]])
>>> print("Mean=",np.mean(a))
Mean= 3.0
>>> np.var(a)---------1.6666666666666667
>>> np.var(a,axis=0)----------array([0.66666667, 2.66666667])
>>> np.var(a,axis=1)-----------array([0.25, 0.25, 1. ])
-----------------------------------------
269
f) std () :
------------
The formula for std=sqrt(var)
Examples:
-----------------
>>> l1=[ [2,1],[4,3],[3,5] ]
>>> a=np.array(l1)
>>> a
array([[2, 1],
[4, 3],
[3, 5]])
>>> print("Mean=",np.mean(a))
Mean= 3.0
>>> np.var(a)
1.6666666666666667
>>> np.var(a,axis=0)
array([0.66666667, 2.66666667])
>>> np.var(a,axis=1)
array([0.25, 0.25, 1. ])
>>> l1=[ [2,1],[4,3],[3,5] ]
>>> a=np.array(l1)
>>> print("Mean=",np.mean(a))
Mean= 3.0
>>> print("Var=",np.var(a))
Var= 1.6666666666666667
>>> print("Std=",np.std(a))
Std= 1.2909944487358056
>>> print("Mean=",np.mean(a,axis=0))
Mean= [3. 3.]
>>> print("Var=",np.var(a,axis=0))
Var= [0.66666667 2.66666667]
>>> print("Std=",np.std(a,axis=0))
Stdr= [0.81649658 1.63299316]
>>> print("Mean=",np.mean(a,axis=1))
Mean= [1.5 3.5 4. ]
>>> print("Var=",np.var(a,axis=1))
Var= [0.25 0.25 1. ]
>>> print("Std=",np.std(a,axis=1))
Std= [0.5 0.5 1. ]
>>> l1=[ [10,20,30],[30,40,50],[25,35,65]]
>>> a=np.array(l1)
>>> a
array([[10, 20, 30],
[30, 40, 50],
[25, 35, 65]])
>>> print("Mean=",np.mean(a))
Mean= 33.888888888888886
>>> print("Var=",np.var(a))
Var= 237.6543209876543
>>> print("Std=",np.std(a))
270
Std= 15.41604102834623
>>> print("Mean=",np.mean(a,axis=0))
Mean= [21.66666667 31.66666667 48.33333333]
>>> print("Var=",np.var(a,axis=0))
Var= [ 72.22222222 72.22222222 205.55555556]
>>> print("Std=",np.std(a,axis=0))
Std= [ 8.49836586 8.49836586 14.33720878]
>>> print("Mean=",np.mean(a,axis=1))
Mean= [20. 40. 41.66666667]
>>> print("Var=",np.var(a,axis=1))
Var= [ 66.66666667 66.66666667 288.88888889]
>>> print("Std=",np.std(a,axis=1))
Std= [ 8.16496581 8.16496581 16.99673171]
>>> print("Std=",np.std(a,axis=1))
Std= [ 8.16496581 8.16496581 16.99673171]
…………………………………………………………………………………………………………………………………………………………………………………….
Select the elements based on Some Condition from ndarray
object
=============================================================
=>we can select any elements from ndarray based some
condition:
Steps:
---------
1) Prepare boolean array and it contains
[ True,False,False,true....]
Syntax:- booleanarrya= ndarray object with condition
2) pass boolean array to ndarray object
Syntax:- ndarray[booleanarray]
3) view the result
(OR)
======================================
Pandas
======================================
Introduction to Pandas:
----------------------------------
=>Pandas is an open source Python Library / Module providing
high performance and data manipulation and Analysis Tool.
=>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 Pandas as
an analysis tool.
=>Python Pandas can be used in wide range of fields like
Finance Services, Statistics , retail marketing sectors…etc
=>pandas module developed in C and Python Languages.
-----------------------------------------------
Installation of Pandas:
-----------------------------------------------
=>The standard python software / Distribution(CPYTHON) does
not contain any module for data analysis and now we are third
party module called PANDAS and whose module name is pandas
=>Programmatically to use pandas as part of our python
program, we must install pandas module by using pip tool.
================================
1)Series
================================
=>Series is one of the One-Dimensional Labelled array , which
is capable storing / holding Homogeneous/Heterogeneous data
(Internally treated as same type)
=>The axis labels are collectively called as Index
=>The series in pandas is nothing but a column in excel sheet
=>The values of Series are mutable.
======================================
Creating Series object
======================================
=>A series object can be created by using the following
Syntax: import pandas as pd
varname=pd.Series(object,index, dtype)
--------------------
Explanation:
--------------------
=>here varname is an object of type <class,
pandas.core.series.Series>
=>pd is an alias name of pandas module
=>Series() is a Function present in Series class and it be
used for creating One-Dimensional Labelled array whose object
can store Homogeneous/Heterogeneous data (Internally treated
as same type)
=>object represents either collections types and ndarry.
=>dtype represents data type of pandas
=>Index represents numerical Integer data starts from 0 to
numbervalues-1
by default and programmatically, we can give our own index.
--------------------------------------------------------------
---------------------------------------------------
Examples:----Creating a Series object by using Collection
type like list
-----------------
>>> import pandas as pd
>>> import numpy as np
>>> l1=[10,20,30,40,50]
>>> s=pd.Series(l1)
274
>>> s
0 10
1 20
2 30
3 40
4 50
dtype: int64
>>> s=pd.Series(l1,dtype="float")
>>> s
0 10.0
1 20.0
2 30.0
3 40.0
4 50.0
dtype: float64
>>> s=pd.Series([100,200,300,400,500])
>>> s
0 100
1 200
2 300
3 400
4 500
dtype: int64
>>> s=pd.Series([100,200,300,400,500],dtype="float")
>>> s
0 100.0
1 200.0
2 300.0
3 400.0
4 500.0
dtype: float64
--------------------------------------------------------------
Examples:---->Creating a Series object by using ndarray
object
-----------------
>>> lst=[100,200,10,20,400]
>>> a=np.array(lst)
>>> a
array([100, 200, 10, 20, 400])
>>> print(a,type(a))
[100 200 10 20 400] <class 'numpy.ndarray'>
>>> s=pd.Series(a)
>>> s
0 100
1 200
2 10
3 20
4 400
dtype: int32
275
>>> print(s,type(s))
0 100
1 200
2 10
3 20
4 400
dtype: int32 <class 'pandas.core.series.Series'>
>>> s=pd.Series(a,dtype="float")
>>> s
0 100.0
1 200.0
2 10.0
3 20.0
4 400.0
dtype: float64
--------------------------------------------------------------
---------------------------------
Examples:--Create a Series with different values of list and
ndarray
------------------
>>> lst=[10,"Rossum",34.56,"Python"]
>>> print(lst,type(lst))
[10, 'Rossum', 34.56, 'Python'] <class 'list'>
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 Rossum
2 34.56
3 Python
dtype: object <class 'pandas.core.series.Series'>
>>> s[0]
10
>>> s[1]
'Rossum'
>>> s[0:2]
0 10
1 Rossum
dtype: object
>>> s[::]
0 10
1 Rossum
2 34.56
3 Python
dtype: object
>>> s[0]=100
>>> s[::]
0 100
1 Rossum
2 34.56
3 Python
dtype: object
276
>>> lst=[10,"Rossum",34.56,"Python"]
>>> a=np.array(lst)
>>> s=pd.Series(a)
>>> s
0 10
1 Rossum
2 34.56
3 Python
dtype: object
>>> s=pd.Series(["Rossum","Gosling","Oliphant","McKinney"])
>>> s
0 Rossum
1 Gosling
2 Oliphant
3 McKinney
dtype: object
--------------------------------------------------------------
Example: Creating a Series object with Programmer-defined
index:
--------------------------------------------------------------
--------
>>> lst=[100,200,10,20,400]
>>> s=pd.Series(lst,index=[1,2,3,4,5],dtype="float")
>>> s
1 100.0
2 200.0
3 10.0
4 20.0
5 400.0
dtype: float64
>>> tpl=(100,200,10,20,400)
>>> s=pd.Series(tpl,index=[1,2,3,4,5],dtype="float")
>>> s
1 100.0
2 200.0
3 10.0
4 20.0
5 400.0
dtype: float64
>>>
s=pd.Series(tpl,index=["1.5","2:5","3:5","4:5","5:5"],dtype="f
loat")
>>> s
1.5 100.0
2:5 200.0
3:5 10.0
4:5 20.0
5:5 400.0
dtype: float64
277
>>>
s=pd.Series(tpl,index=["1:5","2:5","3:5","4:5","5:5"],dtype="f
loat")
>>> s
1:5 100.0
2:5 200.0
3:5 10.0
4:5 20.0
5:5 400.0
dtype: float64
>>>
s=pd.Series(tpl,index=["val1","val2","val3","val3","val5"],dty
pe="float")
>>> s
val1 100.0
val2 200.0
val3 10.0
val3 20.0
val5 400.0
dtype: float64
>>>
s=pd.Series(["Rossum","Gosling","Oliphant","McKinney"],index=[
100,110,120,130])
>>> s
100 Rossum
110 Gosling
120 Oliphant
130 McKinney
dtype: object
>>>
s=pd.Series(["Rossum","Gosling","Oliphant","McKinney"],index=[
"Name1","Name2","Name3","Name4"])
>>> s
Name1 Rossum
Name2 Gosling
Name3 Oliphant
Name4 McKinney
dtype: object
------------------------------------------------------------
>>> bank_int_rates=[6.5,7.75,6.0,7.5]
>>> bank_names=["SBI","ICICI","HDFC","AXIS"]
>>> s=pd.Series(bank_int_rates,bank_names)
>>> s
SBI 6.50
ICICI 7.75
HDFC 6.00
AXIS 7.50
dtype: float64
>>> print("Intrest Rate SBI=",s["SBI"])
Intrest Rate SBI= 6.5
278
Examples:
------------------
>>> d={10:"Apple",20:"Mango",30:"Kiwi",40:"Guava"}
>>> print(d,type(d))
{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Guava'} <class
'dict'>
>>> s=pd.Series(d)
>>> s
10 Apple
20 Mango
30 Kiwi
40 Guava
dtype: object
>>> print(s[10])
Apple
>>> d={"sub1":"Python","sub2":"Data
Sci","sub3":"ML","sub4":"DL","sub5":"AI"}
>>> s=pd.Series(d)
>>> s
sub1 Python
sub2 Data Sci
sub3 ML
sub4 DL
sub5 AI
dtype: object
>>> print("Subject 5={}".format(s["sub5"]))
Subject 5=AI
>>> print("Subject 5={}".format(s[4]))
Subject 5=AI
=======================================================
Accessing the Data from Series object
=====================================================
=>To access the data from Series object, we have two
approaches . They are
a) By using Index / Positions--->(Indexing, Slicing)
b) By using Labels (Programmer defined)
Examples:
------------------
>>> s=pd.Series([10,20,30,40,50,60,70,80,90])
>>> s
0 10
1 20
2 30
3 40
4 50
5 60
6 70
7 80
8 90
dtype: int64
>>> print(s[0])
10
>>> print(s[9])---KeyError
>>> print(s[6])
70
>>> print(s[3:8])
3 40
4 50
5 60
6 70
7 80
dtype: int64
>>> print(s[0:8:2])
0 10
2 30
4 50
6 70
dtype: int64
>>> print(s[::2])
0 10
2 30
4 50
6 70
8 90
dtype: int64
----------------------------------------------------------
>>> d={"sub1":"Python","sub2":"Data
Sci","sub3":"ML","sub4":"DL","sub5":"AI"}
>>> s=pd.Series(d)
>>> s
sub1 Python
sub2 Data Sci
sub3 ML
280
sub4 DL
sub5 AI
dtype: object
>>> print(s[::-1])
sub5 AI
sub4 DL
sub3 ML
sub2 Data Sci
sub1 Python
dtype: object
>>> print(s[::])
sub1 Python
sub2 Data Sci
sub3 ML
sub4 DL
sub5 AI
dtype: object
>>> print(s[::2])
sub1 Python
sub3 ML
sub5 AI
dtype: object
===========================================
DataFrame in Pandas
==============================================
=>A DataFrame is a Two-Dimensional Data Structure to organize
the data
(OR)
=>A DataFrame organizes the data in the tabular form and int
contains Rows
and Columns.
=>The size of the DataFrame is mutable
--------------------------------------------------------------
--------
Number of approaches to create DataFrame in pandas
--------------------------------------------------------------
--------------------------------------------
=>To create DataFrame in Pandas, we use DataFrame(), which is
present in pandas module and gives an object of DataFrame
class.
=>To create a DataFrame, we have 4 approaches. They are
a) list
b) dict
c) Series
d) ndarray
--------------------------------------------------------------
--------
Syntax for creating DataFrame in Pandas:
--------------------------------------------------------------
------
varname=pandas.DataFrame(object, index,columns,dtype)
281
Explanation:
---------------------
=>here varname is an object of
<class,'pandas.core.frame.DataFrame'>
=>object represents List types,dict type, Series and ndarray
types
=>index represents row indices (Axis=1) and by default whose
indices starts from 0 to n-1
=>columns represents column indices (Axis=0) and by default
whose indices 0,1,....
>>> df
stno name
0 10 RS
1 20 JG
2 30 RT
3 40 MCK
>>>
df=pd.DataFrame(lst,index=[1,2,3,4],columns=["stno","name"])
>>> df
stno name
1 10 RS
2 20 JG
3 30 RT
4 40 MCK
>>> lst=[["Rossum",75],["Gosling",85],["Ritche",90]]
>>> df=pd.DataFrame(lst)
>>> print(df)
0 1
0 Rossum 75
1 Gosling 85
2 Ritche 90
>>>
df=pd.DataFrame(lst,index=["rec1","rec2","rec3"],columns=["Nam
e","Age"])
>>> print(df)
Name Age
rec1 Rossum 75
rec2 Gosling 85
rec3 Ritche 90
--------------------------------------------------------------
>>>
d={"subcodes":[10,20,30,40],"subjects":["Python","DataSci","ML
","DL"] }
>>> print(d)
{'subcodes': [10, 20, 30, 40], 'subjects': ['Python',
'DataSci', 'ML', 'DL']}
>>> df=pd.DataFrame(d)
>>> print(df)
subcodes subjects
0 10 Python
1 20 DataSci
2 30 ML
3 40 DL
>>> df=pd.DataFrame(d,index=[1,2,3,4])
>>> df
subcodes subjects
283
1 10 Python
2 20 DataSci
3 30 ML
4 40 DL
>>>
d={"Names":["JG","RS","RT","MC"],"sub":["Java","Python","C","P
andas"] }
>>> df=pd.pandas(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> df=pd.DataFrame(d)
>>> df
Names sub
0 JG Java
1 RS Python
2 RT C
3 MC Pandas
>>> df=pd.DataFrame(d,index=[1,2,3,4])
>>> df
Names sub
1 JG Java
2 RS Python
3 RT C
4 MC Pandas
-------------------------------------------------------------
>>> data={"one":pd.Series([10,20,30,40],
index=['a','b','c','d']),
"two":pd.Series([100,200,300,400],index=['a','b','c','d'])}
>>> df=pd.DataFrame(data)
>>> print(df)
one two
a 10 100
b 20 200
c 30 300
d 40 400
-------------------------------------------------------------
>>> data={"one":pd.Series([10,20,30,40],
index=['a','b','c','d']),
"two":pd.Series([100,200,300,400],index=[1,2,3,4])}
>>> df=pd.DataFrame(data)
>>> print(df)
one two
a 10.0 NaN
b 20.0 NaN
c 30.0 NaN
d 40.0 NaN
1 NaN 100.0
2 NaN 200.0
284
3 NaN 300.0
4 NaN 400.0
--------------------------------------------------------------
>>> df['three']=pd.Series([1,2,3,4],index=['a','b','c','d'])
>>> print(df)
one two three
a 10 100 1
b 20 200 2
c 30 300 3
d 40 400 4
>>> df['total']=df['one']+df['two']+df['three']
>>> print(df)
one two three total
a 10 100 1 111
b 20 200 2 222
c 30 300 3 333
d 40 400 4 444
================================
>>> import pandas
>>> import pandas as pd
>>> import numpy as np
>>> l=[[10,20,30],["RS","RT","MCK"]]
>>> a=np.array(l)
>>> a
array([['10', '20', '30'],
['RS', 'RT', 'MCK']], dtype='<U11')
>>> print(a,type(a))
[['10' '20' '30']
['RS' 'RT' 'MCK']] <class 'numpy.ndarray'>
>>> df=pd.DataFrame(a)
>>> print(df)
0 1 2
0 10 20 30
1 RS RT MCK
===================================================
Working with CSV Files with Pandas
=================================================
=>CSV stands for Comma Separated Values
=>CSV file is one of the Simple file format used for storing
Tabular data such as spread sheet or data base
=>CSV files stores Tabular data (Numbers and text) in plain
text.
=>Each line of CSV is a data record. Each record contains
collection of values separated by comma
=>CSV files must be saved on some file name with an extension
.csv
=>To deal with CSV file, we must import a pre-defined module
called "csv"
285
Examples:
-----------------
stud.csv
--------------------
10,Rossum,34.56
20,Gosling,45.67
30,Ritche,56.78
40,Kinney,66.67
50,Oliphant,66.99
#pancsv.py
import pandas as pd
records=pd.read_csv("stud.csv")
print(records)
==========================================
#pandascsv.py
#pandas module contains a pre-defined function called
read_csv(csv file name)
import pandas as pd
records=pd.read_csv("stud.csv")
print("-----------------------------------------")
print("Student Information:")
print("-----------------------------------------")
print(records)
print("-----------------------------------------")
"""
E:\KVR-PYTHON-7AM\CSV>python pandascsv.py
-----------------------------------------
Student Information:
-----------------------------------------
stno sname marks
0 10 Rossum 34.56
1 20 Gosling 45.67
2 30 Ritche 56.78
3 40 Kinney 66.67
4 50 Oliphant 66.99
-----------------------------------------
E:\KVR-PYTHON-7AM\CSV>set
path=C:\Users\nareshit\AppData\Local\Programs\Python\Python39
#readcsvdata.py
import csv
with open("stud.csv","r") as fp:
286
records=csv.reader(fp)
print("Student Information from CSV file:")
print("----------------------------------------------")
for rec in records:
for val in rec:
print("{}".format(val),end=" ")
print()
print("-----------------------------------------")
=========================================================
#readcsvdata1.py
with open("stud.csv","r") as fp:
records=fp.readlines()
print("Student Information from CSV file:")
print("-----------------------------------------------")
for rec in records:
for val in rec:
print("{}".format(val),end="")
print()
print("---------------------------------------")
==============================================================
287
288
289