Python Programming: Features & Applications
Python Programming: Features & Applications
Contents
Real Time Applications of Python...................................................................................................................................... 4
Features of Python Programming ..................................................................................................................................... 5
1. Simple ........................................................................................................................................................................ 5
2. Freeware and Open Source ....................................................................................................................................... 6
3. Platform Independent ............................................................................................................................................... 6
4. Dynamically Typed ................................................................................................................................................... 6
5. Portable .................................................................................................................................................................... 7
6. Interpreted ............................................................................................................................................................... 7
7) High Level .................................................................................................................................................................. 8
8. Robust ....................................................................................................................................................................... 8
9. Extensible.................................................................................................................................................................. 8
10. Embedded ............................................................................................................................................................... 8
11) Extensive Third Party Library (or) API support ........................................................................................................ 8
Rules for Using Variables in Python................................................................................................................................... 9
Data Types in Python ....................................................................................................................................................... 10
1. Fundamental Category Data Types......................................................................................................................... 10
i) int .......................................................................................................................................................................... 11
ii) float...................................................................................................................................................................... 14
iii)bool ...................................................................................................................................................................... 15
iv)complex ............................................................................................................................................................... 15
2. Sequence Catagery Data Types .............................................................................................................................. 16
1. str ......................................................................................................................................................................... 16
Operations on Strings .............................................................................................................................................. 18
2. bytes .................................................................................................................................................................... 20
3. bytearray ............................................................................................................................................................. 21
[Link] ..................................................................................................................................................................... 21
Type Casting techniques in Python ............................................................................................................................. 25
List Catagery Data Types (Collection Data Types) ....................................................................................................... 30
Types of Copy Mechanisms ......................................................................................................................................... 35
Inner or Nested List ..................................................................................................................................................... 36
tuple (Collection type) ................................................................................................................................................. 37
Set Category Data Types (Collection Data Types) ...................................................................................................... 39
2. set (mutable and immutable) .......................................................................................................................... 39
Print by VIKASH Page - 2
2. frozenset .......................................................................................................................................................... 43
Dict Category Data Type(Collection data type) ........................................................................................................... 45
pre-defined functions in dict ................................................................................................................................... 46
none type data type................................................................................................................................................... 49
===========================================
Getting started with Python
===========================================
=>History of Python
=>Versions of Python
=>Downloading Process of Python
==================================================================================
=>History of Python
=>Python Programming language foundation stone laid in the year 1980.
=>Python Programming language implementation started in the year 1989.
=>Python Programming language officially released in the year 1991 Feb.
=>Python Programming language developed By GUIDO VAN ROSSUM.
=>Python Programming language developed at CWI Institute in Nether lands.
=>ABC programming language is the Predecessor of Python Programming language.
=>Versions of Python
=>Python Programming Contains two Versions. They are
1) Python 2.x----- Here x ---> 1 2 3 4 5 6 7 -----outdated---
2) Python 3.x----> here x 1 2 3 4 5 4 6 7 8 9 10
=>Python 3.x does not contain backward compatability with Python 2.x
=>To down load Python 3.x software , we use [Link]
=>Python Software and its updations are maintained by a Non-Commerical
Organization called " Python Software Foundation(PSF) "
==========================
1. Simple
==========================
=>Python is one of the SIMPLE programming, bcoz of 3 Important Tech Factors.
=>The Python which we down load from [Link] is called Standard Python and
Whose name Is "CPYTHON"
=>Open Source:
-------------------
=>Some of the Companies Came forward and customized CPYTHON for Their In-House
Requirements and those Open Source Software of python are called "Python
Distributions".
=>Some of the Python Distributions are :
======================================
3. Platform Independent
======================================
Concept / Definition:
-------------------------------
=>A language is said to be Platform Independent iff whose applications / Programs
runs on every OS
------------------
Property :
------------------
=>The property of Platform Independent in Python is that "All the Values in Python
Stored in the form Objects and Objects conatins unlimitedf amount of data
storage" . So that run on any OS.
=>In Python Programming all values are stored in the form Objects.
=========================================
4. Dynamically Typed
=========================================
=>We have two types of Programming Languages. They are
1. Static Typed Programming Languages
2. Dynamically Typed Programming Languages
==========================================
5. Portable
==========================================
=>A Portable Project is one which can run on all types of OSes with Considering
vendors and their Architectures.
Examples:--- PYTHON , JAVA
Example for NON
NON-portable: C,CPP...etc
==============================================
6. Interpreted
==============================================
=>When we run the python program, Two internal steps are taking place. They are
1) Compilation Process:
2) Execution Phase:
1) Compilation Process:
The Python Compiler Converts .py (Source Code) into .pyc Code( Byte Code) in
the form Line by Line.
Example: [Link]
[Link]-------->[Link]----during
during Compile Time
2) Execution Phase:
=>The PVM reads Line by Line of Byte Code and converted into Machine Understandable
Code(Binary Code) and It is read By OS and Processer and Gives Result.
=>Hence In Pyhon Execution Environment, Compilation Process and Executio
Execution is
Performing Line by Line anf Python is One of the Interpreted Programming.
==========================================
8. Robust
=========================================
=>python programming is Robust because it provide a programmer to programming
facilities, called exceptions handling and regular handling.
=>Our python program is Robust provide program must used Exception handling and
Regular handling facilities.
==========================================
9. Extensible
==========================================
=>Since Python Programming Provides its services (Programming Segments / snippets)
to other languages for fulfilling its requirements easily.
Examples:-C Programs-can call The coding segments of PYTHON.
==========================================
10. Embedded
==========================================
=>Since Python programming cal also the call / utilize the services of C, Other
Languages as part of its development and Hence Python is onbe of the Embedded
Programming Languages.
Examples:--Numpy, Scikit,Pandas,Scipy, matplot lib etc these developed
in Python and Uses C language.
=====================================================
11) Extensive Third Party Library (or) API support
=====================================================
=>With Traditional Python Programming APIs, we may not be able to perform complex
operations. To do these complex Operations , we use Third party Libraries and Some
of the Third party Libraries are
Examples:- numpy,Pandas,scipy,scikit,matplot lib...etc
===========================================
Data Representation in Python
(or)
Literals in Python
===========================================
=>Literals are nothing but values used for giveing inputs to the program.
=>Basically we have 4 types of Literals. They are
a) Integer Literals
b) Float Literals
c) String Literals
d) Boolean Literals.
=>In general to represent / store any type of Literals / Data in main memory of
computer, we need objects.
=>Def. of Variable:-
=> A Variable is an Identifier whose values are changing during execution of
the program.
3) Within in the Variable Name , special symbols are not allowed except
Under Score (_)
Examples:
tot sal=2.3---invalid
tot$sal=2.3--invalid
tot_sal=2.3--valid
4) All the Variables in Python are Case Sensitive.
Examples:
age=99---valid
AGE=89---valid
Age=79---valid
5) Keywords can't be used as Variables Names bcoz all the Key words are
Reserved Words they have some specfic meaning to the language Compilers.
Examples:
if=12---invalid
while=23---invalid
else=45---invalid
if123=56---valid
_while=34----valid
IF=45----valid
int=12.34---valid
Print by VIKASH Page - 9
float=45----valid
Examples:-
>>> sal_of_an_employee=1.2--Valid--Not Recommended
>>> emp_sal=1.2--Valid--Recommended
---------------------------------------------------------------------------------
================================================
1. Fundamental Category Data Types
================================================
=>The purpose of Fundamental Catagery Data Types is that to store Single Value but
they never allows us to store Multiple Values of same type or different type.
=>In Python Programming, we have 4 data Types Fundamental Catagery. They are
i) int
ii) float
iii) bool
iv) complex
=>Examples: Output
----------------- -----------------
>>> a=19
>>> b=8888888
>>> print(a,type(a))----------------------------------19 <class 'int'>
>>> print(b,type(b))---------------------------------8888888 <class
'int'>
=>with 'int' data type we can also store Different Number System Values.
=>In Programming, we have 4 types of Number Systems. They are
1) Decimal Number System (default)
2) Binary Number System
3) Octal Number System
4) Hexa Decimal Number System
a) bin():
----------------
=>This
This Function is used for converting any type of base value into binary number
system value.
Syntax:- varname=bin(decimal / octal / hexa decimal value)
Examples:
>> a=15
>>> print(a,type(a))
print(a,type(a))---------15 <class 'int'>
>>> b=bin(a)
>>> print(b,type(b))
print(b,type(b))---------0b1111
0b1111 <class 'str'>
>>> a=0o14
>>> print(a,type(a))
print(a,type(a))---------------12
12 <class 'int'>
>>> b=bin(a)
>>> print(b,type(b))
print(b,type(b))-------------0b1100
0b1100 <class 'str'>
>>> a=0xA
>>> print(a,type(a))
print(a,type(a))----------------10
10 <class 'int'>
>>> b=bin(a)
>>> print(b,type(b))
print(b,type(b))-------------- 0b1010 <class 'str'>
b) oct():
------------------
=>This Function is used for converting any type of base value into octal number
system value.
Syntax:- varname=oct(decimal / binary / hexa decimal value)
c) hex():
---------------
=>This Function is used for converting any type of base value into hexa Decimal
number system value.
Examples:
>>> a=2764
>>> print(a,type(a))---------------2764 <class 'int'>
>>> b=hex(a)
>>> print(b,type(b))--------------0xacc <class 'str'>
>>> b=hex(15)
>>> print(b,type(b))-----------0xf <class 'str'>
>>> a=0o15
>>> print(a,type(a))----------13 <class 'int'>
>>> b=hex(a)
>>> print(b,type(b))------------0xd <class 'str'>
>>> a=0b1010
>>> print(a,type(a))------------10 <class 'int'>
>>> b=hex(a)
>>> print(b,type(b))----------- 0xa <class 'str'>
ii) float
========
=>'float' is one of the pre-defined class and treated as Fundamental Data Type.
=>The purpose of float data type is that "To store Real Constant Values (or)
floating point values(numbers with decimal values) ".
=>Examples:--- Percentage of Marks, Taxamount, ..etc
23.45, 3.14...etc
=>The float data type can also be used for storing / representing Scientific
Notation of Numerical values and General format is Mantisa e Exponent
=>General format is Mantisa e Exponent is convertred into Normal Floating point as
mantisal x 10 to the power of exponent
=>Float data type does not support Binary, Octal and Hexa Decimal Number System but
it supports only Decimal Number System.
=>Examples:
>>> a=3.14
>>> print(a,type(a))--------3.14 <class 'float'>
>>> a=0.99
>>> print(a,type(a))-----------0.99 <class 'float'>
Print by VIKASH Page - 14
Example ( Scientific Notation )
>>> a=3.4e3
>>> print(a,type(a))-------------3400.0 <class 'float'>
>>> a=10e-2
>>> print(a,type(a))-----------0.1 <class 'float'>
Examples:
>>> a=0b1111.0b1010--------SyntaxError: invalid decimal literal
>>> a=0xAB.10------SyntaxError: invalid syntax.
>>> a=0o12.34----SyntaxError: invalid syntax.
iii)bool
========
=>'bool' is one of the pre-defined class and treated as Fundamental data type.
=>The purpose of bool data type is that "To store True and False Values (Known
as Logical Values) "
=>Internally, The value of True is treated as 1 and the value of False is 0.
Examples:
>>> a=True
>>> print(a,type(a))-----------True <class 'bool'>
>>> b=False
>>> print(b,type(b))----------False <class 'bool'>
-----------------------------------------------------------------------
Special Examples:
>>> a=True
>>> b=False
>>> print(a+b)----------------1
>>> print(True*False+True)------------1
>>> print(False+2+True+True)----------4
>>> print(True/True)-----------1.0
>>> print(True/False)----------ZeroDivisionError: division by zero
>>> print(2*False)------------0
>>> print(2*True-False)---------2
>>> print(2*False-True)-----------1
>>> print(0b1111*True)----------15
>>> print(0b1111-True)----------14
iv)complex
========
=>'complex' is one of the pre-defined class and treated as Fundamental data
type.
=>The complex data type is used for "Storing Complex Values in form of either a+bj
or a-bj, here 'a' is called Real Part and 'b' is called Imaginary Part and j is
called sqrt(-1) ".
=>To extract the real and imaginary parts from complex object, we use two pre-
defined attributes / Properties / Fileds / Variables. They are \
a) real
b) imag
Syntax: [Link]---->Gives Real part of Complex object
[Link]---->gives Imaginary of Complex object
Examples:
>>> a=2+3j
>>> print(a,type(a))------------------(2+3j) <class 'complex'>
>>> a=2-3j
>>> print(a,type(a))----------------(2-3j) <class 'complex'>
>>> a=2.5+3.6j
>>> print(a,type(a))--------------(2.5+3.6j) <class 'complex'>
Print by VIKASH Page - 15
>>> a=2.5-13.6j
>>> print(a,type(a))---------(2.5-13.6j) <class 'complex'>
>>> a=-5j
>>> print(a,type(a))---------(-0-5j) <class 'complex'>
>>> a=5.5j
>>> print(a,type(a))----------5.5j <class 'complex'>
>>> a=2+j4-------------NameError: name 'j4' is not defined
>>> a=2*3j
>>> print(a,type(a))----------6j <class 'complex'>
>>> a=2-3j
>>> print(a,type(a))-----------(2-3j) <class 'complex'>
Examples 2:
>>> a=10+12j
>>> print(a,type(a))------------(10+12j) <class 'complex'>
>>> k=10.5-12.6j
>>> print(k,type(k))-----------(10.5-12.6j) <class 'complex'>
>>> print([Link])---------10.0
>>> print([Link])--------12.0
>>> print([Link])--------10.5
>>> print([Link])-----------12.6
========================================
2. Sequence Catagery Data Types
========================================
=>Sequence Catagery Data Types are used for storing Sequence of Values / Multiple
values of same type.
=>We have 4 types Sequence Catagery. They are
1) str
2) bytes
3) bytearray
4) range
1. str
Index:
-----------
=>Purpose of str
=>Types of Strings
=>Types String Organization and Notations
=>Operations on Strings
a) Indexing
b) Slicing
str:-
=>The collection or sequence of characters enclosed within single / double
Quotes is called String (Python) :
Examples: "Python Proghramming" "Guido Van Rossum"
"A" 'A' 'Java Programming'
=>'str' is one of the pre-defined class and treated as Sequence Data Type
=>The Purpose of str data type is that "To store Sequence of values within Single
/ Double Quotes or tripple single / double Quotes.
=>We have two types of String data. They are
a) Single Line String Data
b) Multi Line String data
>>> x='''A'''
>>> y="""A"""
>>> a="""JAVA"""
>>> b='''PYTHON'''
>>> print(x,type(x))--------------A <class 'str'>
>>> print(y,type(y))------------A <class 'str'>
>>> print(a,type(a))-----------JAVA <class 'str'>
>>> print(b,type(b))-------PYTHON <class 'str'>
=>Hence With Single and double Quotes we can organize / store single line String
data only but organize / store multi line String data.
Examples:
>>> addr1="Guido van Rossum
SyntaxError: unterminated string literal
>>> addr1=' Guido van Rossum
SyntaxError: unterminated string literal
=>To organize multi line string data we must use Tripple Single or tripple double
Quotes.
>>> print(addr1,type(addr1))------
Guido van Rossum
HNO:3-4 Hill side
CWI ,Python Soft Fund.
Nether Lands--34567 <class
'str'>
>>> addr2='''James Gosling
... FNO: 45-56 River Side
... Sun Micro Sys,
... USA-12345678'''
>>> print(addr2,type(addr2))------------
James Gosling
Print by VIKASH Page - 17
FNO: 45-56 River Side
Sun Micro Sys,
USA-12345678 <class 'str'>
>>> x='''A'''
>>> y="""A"""
>>> a="""JAVA"""
>>> b='''PYTHON'''
>>> print(x,type(x))--------------A <class 'str'>
>>> print(y,type(y))------------A <class 'str'>
>>> print(a,type(a))-----------JAVA <class 'str'>
>>> print(b,type(b))-------PYTHON <class 'str'>
Operations on Strings
================================
=>On the String data, we can two types of Operations. They are
a) Indexing
b) Slicing
a) Indexing
=>The Process of obtaining one value at a time from given string object is called
Indexing.
=>In Python Programming , we have two types of Indices (or Indexes) . They are
a) Forward Indexing and starts from Left to Right (0,1,2.......)
b) Backward Indexing and starts from Right to Left (-1, -2 -3.......)
=>Syntax:
strobj [ Index ]
=>index represents either Possitive and Negative Index.
=>if we enter Invalid Index then we get "IndexError".
Examples:
>>> s="PYTHON"
>>> print(s[0])----------P
>>> print(s[-6])---------P
>>> print(s[-1])----------N
>>> print(s[5])-----------N
>>> print(s[3])----------H
>>> print(s[-4])----------T
>>> print(s[10])---------IndexError: string index out of range
>>> print(s[-10])----IndexError: string index out of range
b) Slicing:
=>The process of obtaining range of characters (or) sub string from given string
object is called String Slicing.
=>Syntax1:- strobj [ Begin : End ]
=>This Syntax obtaing the data from Begin Index Value to End Index-1 Value provided
Begin Index<End Index otherwise we never get Output (Empty).
Examples:
>>> s="PYTHON"
>>> print(s[3:6])------------HON
>>> print(s[6:3]))----------- empty output
>>> print(s[-6:-3])----------PYT
>>> print(s[2:5])---------THO
>>> print(s[-4:-1])-------THO
=>Syntax4:- strobj [ : ]
=>Here Begin Index is not Specified and End Index is also not specified.
=>When we are not specifiying Begin Index and End Index PVM takes Intial Index
as Begin Index and len(strobj)-1 as End Index.
Examples:
>>> s="PYTHON"
>>> print(s)-----------PYTHON
>>> print(s[:])----------PYTHON
>>> print(s[:6])----------PYTHON
>>> print(s[-6:])--------PYTHON
>>> print(s[100:200])-----------NO OUTPUT
>>> print(s[0:200])--------PYTHON
>>> print(s[0:])----------PYTHON
>>> print(s[-6:])----------PYTHON
>>> s="PYTHON"
>>> print(s[:0:2])-----------NO output----RULE-4
>>> print(s[:0:1])-----------NO output----RULE-4
>>> print(s[:-1:-1])---------NO output----RULE-5
>>> print(s[:-1:-2])---------NO output----RULE-5
2. bytes
=>'bytes' is one of the pre-defined class and treated as a sequential data type.
=>The purpose of this data type is that " To Store Sequence of Posstive Integer
values within the range of (0,256). ie. It stores (0,255 only)
=>To convert one type of value into bytes type, we use bytes()
=>An object of bytes maintains insertion order (Which ever order we insert the data
in the same order elements will be displyed )
=>On the object of bytes, we can perform Indexing and Slicing Operations
=>an object Bytes data types belongs to immutable
NOTE:- The Functionality of bytearray is exactly similar to bytes data type but the
object of bytes belongs to immutable where an object bytearray is mutable.
Examples:
>>> lst=[10,20,30,40,-2]
>>> print(lst,type(lst))------[10, 20, 30, 40, -2] <class 'list'>
>>> b=bytearray(lst)---------ValueError: byte must be in range(0, 256)
>>> lst=[10,20,30,40,256]
>>> b=bytearray(lst)---------ValueError: byte must be in range(0, 256)
>>> lst=[10,20,30,40,255]
>>> b=bytearray(lst)
>>> print(b, id(b),type(b))-----bytearray(b'\n\x14\x1e(\xff') 1723585740720
<class 'bytearray'>
[Link]
=>'range' is one pre-defined class and treated as sequence data type.
=>The purpose of range data type is that "To store sequence of Numerical Integer
values by maintaining equal Interval of value ".
=>An object of range is immutable bcoz range object does not allow Item assignment.
=>On the object of range , we can perform Indexing and slicing Operations.
=>To cerate an object of range , we use range()
=>range() contains 3 syntaxes. They are
=>Syntax1: varname= range(value)
=>This syntax creates an object of range from 0 to value-1
10 20 30 40 50 60 70 80 90 100----range(10,101,10)
100 90 80 70 60 50 ----range(100,49,-10)
----------------------------------------------------------
Print by VIKASH Page - 24
-10 - 9 -8 -7 -6 -5 -4 -3 -2 -1----range(-10,0,1)
-5 -4 -3 -2 -1 0 1 2 3 4 5---range(-5,6,1)
=================================================
Type Casting techniques in Python
(or)
Type Conversion techniques in Python
=================================================
=>The purpose of Type Casting techniques in Python is that "To Convert one
data type value into another data type value".
=>In Python Programming, Fundamentally, we have 5 Type Casting techniques in
Python. They are
1) int ()
2) float()
3) bool()
4) complex()
5) str()
1) int ()
=>int() is used for converting "one possible type of value into int type value."
=>Syntax:
varname=int( float / bool / complex / str value )
2. float()
=>float() is used for converting "one possible type of value into float type
value."
=>Syntax:
varname=float( int / bool / complex / str value )
Example: int value into float--->Possible
>>> a=12
>>> print(a,type(a))-----------------12 <class 'int'>
>>> b=float(a)
>>> print(b, type(b))----------------12.0 <class 'float'>
4) complex()
=>This function is used for converting one possible type of value into complex
type value.
=>Syntax: varname=complex(int / float / bool / str value)
Examples: int value-->complex--->Possible
>>> a=10
>>> print(a,type(a))----------------10 <class 'int'>
>>> b=complex(a)
>>> print(b, type(b))-------------(10+0j) <class 'complex'>
Examples: float value-->complex--->Possible
>>> a=12.3
>>> print(a,type(a))------------12.3 <class 'float'>
>>> b=complex(a)
>>> print(b, type(b))------------(12.3+0j) <class 'complex'>
Examples: bool value-->complex--->Possible
>>> a=True
>>> print(a,type(a))-------------True <class 'bool'>
>>> b=complex(a)
>>> print(b, type(b))---------------(1+0j) <class 'complex'>
Examples: Str value-->complex
>>> a="12" # int str---->complex-->Possible
>>> print(a,type(a))---12 <class 'str'>
>>> b=complex(a)
>>> print(b, type(b))---(12+0j) <class 'complex'>
>>> a="2.3" # float str---->complex-->Possible
>>> print(a,type(a))---------2.3 <class 'str'>
>>> b=complex(a)
>>> print(b, type(b))--------(2.3+0j) <class 'complex'>
>>> a="True" # bool str---->complex-->Not Possible
>>> print(a,type(a))---------True <class 'str'>
>>> b=complex(a)--------ValueError: complex() arg is a malformed string
>>> a="Python" # Pures Str--->complex--Not Possible.
>>> print(a,type(a))------Python <class 'str'>
>>> b=complex(a)------ValueError: complex() arg is a malformed string
>>> a=100
>>> print(a,type(a))
print(a,type(a))-----------100
100 <class 'int'>
>>> b=str(a)
>>> print(b, t
type(b))----------100
100 <class 'str'>
>>> b-------------
-------------'100'
>>> a=12.34
>>> print(a,type(a))
print(a,type(a))-----------12.34
12.34 <class 'float'>
>>> b=str(a)
>>> print(b, type(b))
type(b))---------12.34
12.34 <class 'str'>
>>> b---------------
---------------'12.34'
>>> a=True
>>> print(a,type(a))
print(a,type(a))-----------True
True <class 'bool'>
>>> b=str(a)
>>> print(b, type(b))
type(b))-----------True
True <class 'str'>
>>> b--------------
--------------'True'
>>> a=2+3.5j
>>> print(a,type(a))
print(a,type(a))-----------(2+3.5j)
(2+3.5j) <class 'complex'>
>>> b=str(a)
>>> print(b, type(b))
type(b))------------(2+3.5j)
(2+3.5j) <class 'str'>
>>> b-------------
-------------'(2+3.5j)'
Properties of list:
=>'list' is one of the pre-defined class and treated as List catagery data type.
=>The purpose of list data type is that "To store Multiple Values either of same
type or different type or both types with Unique and Duplicate Values in a single
variable"
=>The elements of list must written within Square Brackets [ ] and elements must
separated by comma.
=>An object of list maintains Insertion Order ( In which ever order we insert the
data in the object of list, in the same order elements will be displayed")
=>On the object of list , we can perform both indexing and slicing Operations.
=>An object of list is mutable
=>We create two types of lists. They are
a) Empty List
b) Non-empty list
=> An Empty List is one, whose length=0 (no elements presents)
Syntax:- listobj=[] (OR) listobj=list()
=> An Non Empty List is one, whose length>0 (elements presents)
Syntax:- listobj=[val1,val2,...val-n]
=>To convert one type elements into list values, we use list(object)
Examples:
>>> l=[10,12,-4,25,67]
>>> print(l,type(l))-------------[10, 12, -4, 25, 67] <class 'list'>
>>> len(l)-------5
>>> l1=[10,"Rossum",11.11,"CWI","NL",2+3j,True]
>>> print(l1,type(l1))--[10, 'Rossum', 11.11, 'CWI', 'NL', (2+3j),
True] <class ,'list'>
>>> len(l1)-------7
>>> l2=[]
>>> print(l2,type(l2))---------[] <class 'list'>
>>> len(l2)----------0
>>> l3=list()
>>> print(l3,type(l3))-----------[] <class 'list'>
>>> len(l3)-----------0
>>> l1=[10,"Rossum",11.11,"CWI","NL",2+3j,True]
>>> print(l1,type(l1))---[10, 'Rossum', 11.11, 'CWI', 'NL', (2+3j),
True] <class 'list'>
>>> print(l1[0])----10
>>> print(l1[-1])----True
>>> print(l1[0:4])--------[10, 'Rossum', 11.11, 'CWI']
>>> print(l1[::2])--------[10, 11.11, 'NL', True]
[Link]
>>> a=10
>>> l1=list([a])
>>> print(l1,type(l1))-------[10] <class 'list'>
(OR)
>>> a=100.2
>>> l1=[a]
>>> print(l1,type(l1))-------------[100.2] <class 'list'>
=================================================
Pre-defined Functions in list
=================================================
=>In addition to the indexing and slicing Operation on list, we can also perform
Various additional operations by using Pre-defined Functions present in list.
=>The pre-defined functions in list are
1. append() 5. POP(Index) 9. Index()
2. insert() 6. Pop() 10. Reverse()
3. clear() 7. Copy() 11. Sort()
4. remove() 8. Count() 12. Extend()
1) append():
=>This Function is used for adding the values to the list at end of existing
elements of list.
=>Syntax:- [Link](element)
Examples:
>>> l1=[]
>>> print(l1,type(l1))------------[] <class 'list'>
>>> len(l1)----------0
>>> [Link](10)
>>> print(l1,type(l1))----------[10] <class 'list'>
>>> [Link]("ROSUUM")
>>> print(l1,type(l1))--------[10, 'ROSUUM'] <class 'list'>
>>> [Link](10.22)
>>> print(l1,type(l1))---------[10, 'ROSUUM', 10.22] <class 'list'>
>>> l2=[10,20,30,40,-45]
>>> [Link]("Hyd")
>>> print(l2,type(l1))------------[10, 20, 30, 40, -45, 'Hyd'] <class
'list'>
2) insert():
=>This Function is used for inserting a Value at a perticyulat exiting index by
passing Index and Element.
=>Syntax: [Link](index,element)
Examples:
>>> l1=[10,20,30,40,-45]
>>> print(l1)-------------[10, 20, 30, 40, -45]
>>> [Link](2,"PYTHON")
>>> print(l1)------------[10, 20, 'PYTHON', 30, 40, -45]
>>> [Link](1,"Rossum")
>>> print(l1)-------------[10, 'Rossum', 20, 'PYTHON', 30, 40, -45]
Print by VIKASH Page - 31
>>> [Link](-3,44.44)
>>> print(l1)-----------[10, 'Rossum', 20, 'PYTHON', 44.44, 30, 40, -
45]
3) clear():
=>This function is used for removing / deleting all the elements of list object
=>Syntax:- [Link]()
Examples:
>>> l1=[10,20,30,40,-45]
>>> print(l1)-------------[10, 20, 30, 40, -45]
>>> len(l1)------------5
>>> [Link]()
>>> print(l1)-----------[]
>>> len(l1)------------0
4) remove():
=>This Function is used removing / deleting First Occurence of the specified
element
=>If the element is not present in list then we get ValueError
Syntax:- [Link](element)
Examples:
>>> l1=[10,"Python","Java",10,23.45,"PYTHON"]
>>> print(l1)--------[10, 'Python', 'Java', 10, 23.45, 'PYTHON']
>>> [Link](10)
>>> print(l1)---['Python', 'Java', 10, 23.45, 'PYTHON']
>>> [Link]("PYTHON")
>>> print(l1)------['Python', 'Java', 10, 23.45]
>>> [Link](100)----------ValueError: [Link](x): x not in list
5) pop(Index)
=> This function is used for deleting the element of list based on Valid Exiting
index otherwise we get IndexError.
=>Syntax:- [Link](index)
Examples:
>>> l1=[10,"Python","Java",10,23.45,"PYTHON"]
>>> print(l1)-----------[10, 'Python', 'Java', 10, 23.45, 'PYTHON']
>>> [Link](3)--------10
>>> print(l1)----------[10, 'Python', 'Java', 23.45, 'PYTHON']
>>> [Link](-2)---------23.45
>>> print(l1)-----------[10, 'Python', 'Java', 'PYTHON']
>>> [Link](13)----------IndexError: pop index out of range
>>> list().pop(1)-------IndexError: pop from empty list
>>> [].pop(-1)---IndexError: pop from empty list
6) pop():
=>This function is used for removing last element of list object (last indexed
element)
=>when we call pop() on empty list object then we get IndexError.
Syntax:- [Link]()
Examples:
>>> lst=[10,"Python","Rossum",34.56,True]
>>> print(lst)--------------[10, 'Python', 'Rossum', 34.56, True]
>>> [Link]()----------True
>>> print(lst)------------[10, 'Python', 'Rossum', 34.56]
>>> [Link]()-----------34.56
>>> print(lst)-----------[10, 'Python', 'Rossum']
>>> [Link]()----------'Rossum'
>>> print(lst)-----------[10, 'Python']
>>> [Link]()------------'Python'
>>> print(lst)-----------[10]
>>> [Link]()------------10
>>> print(lst)-----------[]
Print by VIKASH Page - 32
>>> [Link]()------IndexError: pop from empty list
>>> lst=[10,"Python","Rossum",34.56,True]
>>> print(lst)-----------[10, 'Python', 'Rossum', 34.56, True]
>>> [Link](3,"Java")
>>> print(lst)-----[10, 'Python', 'Rossum', 'Java', 34.56, True]
>>> [Link]()-----True
>>> print(lst)-----[10, 'Python', 'Rossum', 'Java', 34.56]
7) copy():
=>This Function is used copying the content of one list object into another list
object ( implementing shallow copy)
Syntax:- listobj2=[Link]()
Examples:
>> lst1=[10,"Python","Rossum",34.56]
>>> print(lst1,id(lst1))----[10, 'Python', 'Rossum', 34.56] 2955419270720
>>> lst2=[Link]()
>>> print(lst2,id(lst2))----[10, 'Python', 'Rossum', 34.56] 2955419255872
>>> [Link](True)
>>> print(lst1,id(lst1))--[10, 'Python', 'Rossum', 34.56, True] 2955419270720
>>> print(lst2,id(lst2))----[10, 'Python', 'Rossum', 34.56] 2955419255872
>>> [Link](2,"Java")
>>> print(lst1,id(lst1))--[10, 'Python', 'Rossum', 34.56, True] 2955419270720
>>> print(lst2,id(lst2))----[10, 'Python', 'Java', 'Rossum', 34.56]
2955419255872
Deep Copy:
--------------------
>> lst1=[10,"Python","Rossum",34.56]
>>> lst1=[10,"Python","Rossum",34.56]
>>> lst2=lst1 # Implementing Deep Copy Process
>>> print(lst1,id(lst1))------[10, 'Python', 'Rossum', 34.56] 2955419266624
>>> print(lst2,id(lst2))------[10, 'Python', 'Rossum', 34.56] 2955419266624
>>> [Link](True)
>>> print(lst1,id(lst1))--[10, 'Python', 'Rossum', 34.56, True] 2955419266624
>>> print(lst2,id(lst2))--[10, 'Python', 'Rossum', 34.56, True] 2955419266624
>>> [Link](2,"DS")
>>> print(lst1,id(lst1))--[10, 'Python','DS','Rossum',34.56,True] 2955419266624
>>> print(lst2,id(lst2))--[10,'Python','DS','Rossum', 34.56, True] 2955419266624
8)count():
=>This function is used for counting / finding number of occurences of the
specified element .
=>If the specified element does not exist in list object then we get 0.
Syntax:- [Link](element)
Print by VIKASH Page - 33
Examples:
>>> lst=[10,20,"python",10,"python",10,30,20,10]
>>> [Link](10)--------4
>>> [Link]("python")-----------2
>>> [Link](20)----------2
>>> [Link](30)---------1
>>> [Link](300)--------0
9) index()
=>This function is used for obtaining an index of the First occurence of specified
eleement
=>If element does not exists in list object then we get ValueError.
Syntax:- [Link](element)
Examples:
>>> lst=[10,20,"python",10,"python",10,30,20,10]
>>> print([Link](10))---------0
>>> print([Link](20))--------1
>>> print([Link]("python"))-----2
>>> print([Link]("python3.10"))-------ValueError: 'python3.10' is
not in list
10)reverse():
=>This function is used for obtaining reverse of elements of list object
Syntax:- [Link]()
Examples:
>>> lst1=[10,"Python","Rossum",34.56]
>>> print(lst1)---------------[10, 'Python', 'Rossum', 34.56]
>>> print([Link]())-------------None
>>> print(lst1)-----[34.56, 'Rossum', 'Python', 10]
>>> lst1=[10,"Python","Rossum",34.56]
>>> print(lst1)-----------[10, 'Python', 'Rossum', 34.56]
>>> [Link]()
>>> print(lst1)-------------[34.56, 'Rossum', 'Python', 10]
>>> lst2=[10,20,30,-23,45,2,67,34]
>>> print(lst2)--------[10, 20, 30, -23, 45, 2, 67, 34]
>>> [Link]()
>>> print(lst2)-----[34, 67, 2, 45, -23, 30, 20, 10]
11) sort():
=>This function is used for sorting the given homogeneous data of list object
either Ascending Order or in decending order.
=>If reverse=False then sort() sorts the data in Ascending order
=>If reverse=True then sort() sorts the data in Decending order
=>If we don't write reverse=False then ity similar to sort() and sorts the data in
Ascending order
Syntax: [Link](reverse=False / True )
Examples:
>>> lst2=[10,20,30,-23,45,2,67,34]
>>> print(lst2)---------[10, 20, 30, -23, 45, 2, 67, 34]
>>> [Link]()
>>> print(lst2)----------[-23, 2, 10, 20, 30, 34, 45, 67]
>>> [Link]()
>>> print(lst2)------[67, 45, 34, 30, 20, 10, 2, -23]
>>> lst3=["apple","sberry","guava","mango","abc"]
>>> print(lst3)---------['apple', 'sberry', 'guava', 'mango', 'abc']
>>> [Link]()
>>> print(lst3)----------['abc', 'apple', 'guava', 'mango', 'sberry']
>>> [Link]()
>>> print(lst3)------------['sberry', 'mango', 'guava', 'apple', 'abc']
Print by VIKASH Page - 34
>>> lst2=[10,20,30,-23,45,2,67,34]
>>> print(lst2)----------------[10, 20, 30, -23, 45, 2, 67, 34]
>>> [Link](reverse=True)
>>> print(lst2)-------------[67, 45, 34, 30, 20, 10, 2, -23]
>>> lst2=[10,20,30,-23,45,2,67,34]
>>> print(lst2)--------[10, 20, 30, -23, 45, 2, 67, 34]
>>> [Link](reverse=False)
>>> print(lst2)------------[-23, 2, 10, 20, 30, 34, 45, 67]
12) extend():
=>This function is used for extending functionality of source list object with
destination list object
Syntax: [Link](destination list obj)
Examples:
>>> lst1=[10,20,30]
>>> lst2=["Java","python","DS","AI"]
>>> [Link](lst2)
>>> print(lst1)------------[10, 20, 30, 'Java', 'python', 'DS', 'AI']
------------------------------------------------------
>>> lst1=[10,20,30]
>>> lst2=["Java","python","DS","AI"]
>>> lst3=["Oracle","MYSQL"]
>>> lst4=["Tomcat Ser","WebLogic","Web Sphere"]
>>> [Link](lst2,lst3,lst4)----TypeError: [Link]() takes
exactly one argument (3 given)
#we can achieve extend() task with + operator
>>> lst1=lst1+lst2+lst3+lst4
>>> print(lst1)-----[10, 20, 30, 'Java', 'python', 'DS', 'AI',
'Oracle', 'MYSQL','Tomcat Ser', 'WebLogic', 'Web Sphere']
==========================================
Types of Copy Mechanisms
==========================================
=>Copy Process is nothing but copying the content of one object into another
object.
=>WE have two types of Copy Process. They are
a) Shallow Copy
b) Deep Copy
Slicing Based Copy:
a) Shallow Copy:
=>In shallow Copy
i) Initial Content of both the objects are same
ii) Both the objects contains different address
iii) The Modifications on the objects are Independent.
(Modifications are not recflected)
=>To implement Shallow Copy, we use copy()
Syntax:- objname1=[Link]()
b) Deep Copy:
=>In Deep Copy
i) Initial Content of both the objects are same
ii) Both the objects contains Same Address
iii) The Modifications on the objects are dependent.
(Modifications are recflected to each other)
=>To implement Deep Copy, we use Assignment Operator
Syntax:- objname1=objname2
Print by VIKASH Page - 35
Slicing Based Copy:
=>The this copy process is also Shallow Copy implementation only.
Examples:
>>> lst1=[10,"Python","Rossum",34.56]
>>> print(lst1,id(lst1))
print(lst1,id(lst1))----[10,
[10, 'Python', 'Rossum', 34.56] 9255872
>>> lst2=lst1[::] # slice based copy
>>> print(lst2,id(lst2))
print(lst2,id(lst2))----[10,
[10, 'Python', 'Rossum', 34.56] 9270720
>>> [Link](34.56)
>>> print(lst1,id(lst1))
print(lst1,id(lst1))----[10,
[10, 'Python', 'Rossum'] 9255872
>>> print(lst2,id(lst2))
print(lst2,id(lst2))----[10,
[10, 'Python', 'Rossum', 34.56] >>> >>>
>>>lst3=lst1[0:3]
lst3=lst1[0:3] # slice based copy
>>> print(lst3,id(lst3))
print(lst3,id(lst3))---[10,
[10, 'Python', 'Rossum'] 2955419266624
>>> lst4=lst1[::
lst4=lst1[::-1] # slice based copy
>>> print(lst4,id(lst4))
print(lst4,id(lst4))---['Rossum',
['Rossum', 'Python', 10] 9517312
======================================
Inner or Nested List
======================================
=>The
The Process of defining one list inside of another list is called Inner / nested
list.
>Syntax:
listobj=[ val1,val2....[ val11,val12,...] , [val22,val23....] ....val
....val-n ]
===================================
========
(B) Tuple
uple (Collection type)
================================
==========================
=>'tuple' is one of the prepre-defined
defined class and terated list type data type.
=>The
The purpose of tuple data type is that "To store Multiple Values either of same
type or different type or both types with Unique and Duplicate Values in a single
variable"
=>The elements of tuple must written within braces ( ) and elements must separ separated
by comma.
=>An object of tuple maintains Insertion Order ( In which ever order we insert the
data in the object of tuple, in the same order elements will be displayed")
=>On the object of tuple , we can perform both indexing and slicing Operatio
Operations.
=>An object of tuple is immutable
=>We create two types of tuples. They are
a) Empty tuple
b) Non-empty
empty tuple
=> An Empty tuple is one, whose length=0 (no elements presents)
Syntax:- tupleobj=() (OR) tupleobj=tuple()
=> An Non Empty tuple is one, whose length>0 (elements presents)
Syntax:- tupleobj=(val1,val2,...val
tupleobj=(val1,val2,...val-n)
Print by VIKASH Page - 37
=>To convert one type elements into tuple values, we use tuple(object)
Note:- The Functionality of tuple is exactly similar to List but an object of list
belongs to mutable and an object of tuple belongs to immutable.
Examples:
>>> t1=(10,20,-3,45,123,67,20)
>>> print(t1,type(t1))----(10, 20, -3, 45, 123, 67, 20) <class 'tuple'>
>>> t2=(10,"Rossum",45.67,"Python",True)
>>> print(t2,type(t2))----(10, 'Rossum', 45.67, 'Python', True) <class
'tuple'>
>>> t3=()
>>> print(t3,type(t3), len(t3))--------() <class 'tuple'> 0
>>> t4=tuple()
>>> print(t4,type(t4), len(t4))---------() <class 'tuple'> 0
>>> t2=(10,"Rossum",45.67,"Python",True)
>>> print(t2[0])----10
>>> print(t2[-1])----True
>>> print(t2[0:3])----(10, 'Rossum', 45.67)
>>> print(t2[::2])----(10, 45.67, True)
>>> t2=(10,"Rossum",45.67,"Python",True)
>>> print(t2,type(t2), id(t2))--(10, 'Rossum', 45.67, 'Python', True)
<class 'tuple'> 2399350751152
>>> t2[2]=55.66 ---TypeError: 'tuple' object does not support item
assignment
>>> t1=(12,3,-4,45,23,78,4,1,12)
>>> print(t1,type(t1))----(12, 3, -4, 45, 23, 78, 4, 1, 12) <class
'tuple'>
>>> [Link]()----AttributeError: 'tuple' object has no attribute 'sort'
>>> l1=list(t1)
>>> print(l1,type(l1))--[12, 3, -4, 45, 23, 78, 4, 1, 12] <class'list'>
>>> print(l1,type(l1),id(l1))--[12, 3, -4, 45, 23, 78, 4, 1, 12] <class
'list'> 2399351145088
>>> [Link]()
>>> print(l1,type(l1),id(l1))--[-4, 1, 3, 4, 12, 12, 23, 45, 78] <class
'list'> 2399351145088
>>> t1=tuple(l1)
>>> print(t1,type(t1))--(-4, 1, 3, 4, 12, 12, 23, 45,78) <class'tuple'>
-----------------------------------------------------------------------
>>> x=10,20,"KVR","OUCET",True
>>> print(x, type(x))---(10, 20, 'KVR', 'OUCET', True) <class 'tuple'>
-----------------------------------------------------------------------
>>> t1=(10,"Rossum",(12,16,11),"NLU")
>>> print(t1,type(t1))--(10,'Rossum',(12, 16, 11),'NLU') <class'tuple'>
>>> print(t1[2])---------------(12, 16, 11)
>>> t1=(10,"Rossum",[12,16,11],"NLU")
>>> print(t1,type(t1))----(10,'Rossum',[12,16,11],'NLU')<class'tuple'>
>>> print(t1[2],type(t1[2]))-------[12, 16, 11] <class 'list'>
>>> t1[2].sort()
>>> print(t1,type(t1))--(10,'Rossum',[11,12,16],'NLU') <class 'tuple'>
>>> l1=[10,"KVR",(10,20,12),"OUCET"]
>>> print(l1,type(l1))-----[10,'KVR',(10,20,12),'OUCET'] <class 'list'>
==================================================
Set Category Data Types (Collection Data Types)
==================================================
>Set Category Data Types are used for storing Multiple Values either of same type
or different type or both types with Unique Values in a single variable.
=>Set Category Data Types are 2 types. They are
i) set (mutable and immutable)
2) frozenset ( immutable )
a) empty set:
=>An empty set is one, whose length is 0
Syntax: setobj=set()
b) non-empty set:
=>An non-empty set is one, whose length is >0
Syntax: setobj={val1,val2....val-n}
Examples:
>>> s1={10,20,10,20,30,123,-56}
>>> print(s1,type(s1))---{20, -56, 10, 123, 30} <class ‘set’>
>>> s1={10,”KVR”,33.33,”OUCET”,”HYD”,True}
>>> print(s1,type(s1))---{‘KVR’, 33.33, True, ‘OUCET’, 10, ‘HYD’}
<class ‘set’>
>>> s1[0]=100-TypeError: ‘set’ object does not support item assignment
>>> print(s1,type(s1),id(s1))—{‘KVR’, 33.33, True, ‘OUCET’, 10, ‘HYD’}
<class ‘set’> 1844977298208
>>> s1=set()
>>> print(s1,type(s1),id(s1))---set() <class ‘set’> 1844977297088
>>> len(s1)----------0
>>> [Link](10)
>>> [Link](“RS”)
>>> print(s1,type(s1),id(s1))---{‘RS’, 10} <class ‘set’> 1844977297088
=====================================
Pre-defined Functions in set
=====================================
1) add():
=>This function is used for adding an element to the set object
=>Syntax:- [Link](element)
Examples:
>>> s1={10,”Rossum”}
>>> print(s1,type(s1),id(s1))—{‘Rossum’, 10} <class ‘set’> 7298208
>>> [Link](“PYTHON”)
>>> [Link](11.11)
>>> print(s1,type(s1),id(s1))—{‘Rossum’,10,11.11,’PYTHON’}<class
‘set’> 7298208
2) remove():
=>This function is used for removing the specified element from set object.
=>If the specified element does not exists in set object we get KeyError.
=>Syntax:- [Link](element)
Examples:
>>> s1={‘Rossum’, 10, 11.11, ‘PYTHON’}
>>> print(s1)----{‘Rossum’, 10, 11.11, ‘PYTHON’}
>>> [Link](10)
>>> print(s1)--------------{‘Rossum’, 11.11, ‘PYTHON’}
>>> [Link](“Rossum”)
>>> print(s1)-----{11.11, ‘PYTHON’}
>>> [Link](101)-----------KeyError: 101
3) discard()
=>This function is used for removing the specified element from set object.
=>If the specified element does not exists in set object we nerver get any error.
=>Syntax:- [Link](element)
Examples:
>>> s1={‘Rossum’, 10, 11.11, ‘PYTHON’}
>>> print(s1)-----{‘Rossum’, 10, 11.11, ‘PYTHON’}
>>> [Link](10)
>>> print(s1)---------{‘Rossum’, 11.11, ‘PYTHON’}
>>> [Link](100) # here 100 does not exist and no error
>>> print(s1)-------{‘Rossum’, 11.11, ‘PYTHON’}
4) pop()
=>This function is used for removing an arbitrary element from set object.
=>Syntax: [Link]()
Examples:
>>> s1={‘Rossum’, 10, 11.11, ‘PYTHON’}
>>> print(s1)-----------{‘Rossum’, 10, 11.11, ‘PYTHON’}
>>> [Link]()------------‘Rossum’
>>> print(s1)-----------{10, 11.11, ‘PYTHON’}
>>> [Link]()------------10
Print by VIKASH Page - 40
>>> print(s1)-----------{11.11, ‘PYTHON’}
>>> [Link]()------------11.11
>>> print(s1)-----------{‘PYTHON’}
>>> [Link]()------------‘PYTHON’
>>> s1={10,20,30,40,50,60,70,-123,3456}
>>> [Link]()----------3456
>>> s1={10,20,30,40,50,60,70,-123,3456}
>>> print(s1)---------{3456, -123, 70, 40, 10, 50, 20, 60, 30}
>>> [Link]()----------3456
>>> print(s1)---------{-123, 70, 40, 10, 50, 20, 60, 30}
>>> [Link]()----------123
>>> [Link]()----------70
>>> [Link]()----------40
>>> [Link]()----------10
>>> [Link]()----------50
>>> s1={“apple”,”Mango”,”kiwi”,”abc”,23.45,67,2+3j}
>>> [Link]()----------‘apple’
>>> [Link]()----------‘kiwi’
>>> print(s1)---------{67, ‘abc’, 23.45, (2+3j), ‘Mango’}
>>> [Link]()---------67
>>> [Link]()---------‘abc’
>>> set().pop()----------KeyError: ‘pop from an empty set’
5) isdisjoint():
=>Syntax:- [Link](setobj2)
=>This Function returns True provided setob1 and setobj2 does contains common
elements
=>This Function returns False provided setob1 and setobj2 contains at least one
common element.
Examples:
>>> s1={10,20,30,40}
>>> s2={15,25,35,10}
>>> s3={12,24,36,48}
>>> [Link](s2)---------False
>>> [Link](s3)---------True
>>> [Link](s1)------False
>>> [Link](set())----True
>>> set().isdisjoint(set())---True
6) issuperset()
Syntax:- [Link](setobj2)
=>This Function returns True provided all the 41lements of setobj2 must present in
setobj1. Otherwise we get False.
Examples:
>>> s1={10,20,30,40}
>>> s2={15,25,35,10}
>>> s3={12,24,36,48}
>>> [Link](s2)----------------False
>>> [Link](s3)----------------False
>>> s4={10,20}
>>> [Link](s4)----------------True
>>> [Link](s1)----------------True
>>> [Link](set())-------------True
>>> set().issuperset(set())----------True
>>> set().issubset(set())------------True
>>> {10,20}.issuperset({20,10})------True
>>> {10,20,25}.issuperset({20,10})---True
>>> {10,20}.issuperset({20,10,”pyt”})—False
Print by VIKASH Page - 41
7) issubset()
Syntax:- [Link](setobj2)
=>This Function returns True provided all the elements of setobj1 are present in
setobj2. Otherwise we get False
Examples:
>>> s1={10,20,30,40}
>>> s2={10,20}
>>> s3={15,20}
>>> [Link](s1)--------True
>>> [Link](s1)-------False
>>> set().issubset(set())----True
8) Union()
=>Syntax:- setobj3=[Link](setobj2)
=>This takes all the elements of setobj1 and setobj2 , combine them and place them
in setobj3 uniquely.
Examples:
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> print(s1)----------------{‘RS’, ‘JG’, ‘DR’, ‘Stup’}
>>> print(s2)------------{‘RS’, ‘TRAVIS’, ‘MCK’}
>>> allcptp=[Link](s2)
>>> print(allcptp)------------{‘RS’, ‘DR’, ‘Stup’, ‘JG’, ‘TRAVIS’,
‘MCK’}
9)difference()
Syntax:- setobj3=[Link](setobj2)
=>This function removes the common elements from setobj1 and setobj2 and takes
remaining elements from setobj1 and place them in setobj3.
Examples:
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> print(s1)----------{‘RS’, ‘DR’, ‘Stup’, ‘JG’}
>>> print(s2)--------{‘RS’, ‘TRAVIS’, ‘MCK’}
>>> onlycp=s1-s2
>>> print(onlycp)---------{‘JG’, ‘DR’, ‘Stup’}
>>> onlytp=s2-s1
>>> print(onlytp)--------{‘TRAVIS’, ‘MCK’}
>>> onlycp=[Link](s2)
>>> print(onlycp)--------{‘JG’, ‘DR’, ‘Stup’}
>>> onlytp=[Link](s1)
>>> print(onlytp)-----{‘TRAVIS’, ‘MCK’}
10) intersection():
Syntax:- setobj3=[Link](setobj2)
=>This obtains common elements from setobj1 and setobj2 and place tthem setobj3.
Examples:
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> s3=[Link](s2)
>>> print(s3)--------{‘RS’}
>>> s3=[Link](s1)
>>> print(s3)----{‘RS’}
11) symmetric_difference():
Syntax:- setobj3=setobj1.symmetric_difference(setobj2)
=>This function removes common elements from setobj1 and setobj2 and takes
remaining elements from both setobj1 and setobj2 and place them in setobj3.
Print by VIKASH Page - 42
Examples:
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> print(s1)---------------{‘RS’, ‘DR’, ‘Stup’, ‘JG’}
>>> print(s2)------------{‘RS’, ‘TRAVIS’, ‘MCK’}
>>> excptp=s1.symmetric_difference(s2)
>>> print(excptp)--------{‘DR’, ‘TRAVIS’, ‘Stup’, ‘JG’, ‘MCK’}
Special Cases:
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> s3=[Link](s2)
>>> print(s3)----------{‘RS’, ‘DR’, ‘Stup’, ‘JG’, ‘TRAVIS’, ‘MCK’}
>>> s4=s1|s2 # Bitwise OR ( | )
>>> print(s4)-----------{‘RS’, ‘DR’, ‘Stup’, ‘JG’, ‘TRAVIS’, ‘MCK’}
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> s3=[Link](s2)
>>> print(s3)----------{‘RS’}
>>> s4=s1&s2 # Bitwise AND ( & )
>>> print(s4)----------{‘RS’}
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3)-------{‘DR’, ‘TRAVIS’, ‘Stup’, ‘JG’, ‘MCK’}
>>> s4=s1^s2 # Bitwise XOR (^)
>>> print(s4)---------{‘DR’, ‘TRAVIS’, ‘Stup’, ‘JG’, ‘MCK’}
>>> s1={“RS”,”JG”,”DR”,”Stup”}
>>> s2={“TRAVIS”,”MCK”,”RS”}
>>> s3=[Link](s2)
>>> print(s3)----{‘JG’, ‘DR’, ‘Stup’}
>>> s4=s1-s2
>>> print(s4)----------{‘JG’, ‘DR’, ‘Stup’}
12) update():
Syntax:- [Link](setobj2)
=>This Function updates / adds the elements of setobj2 to setobj1.
Examples:
>>> s1={“C”,”CPP”}
>>> s2={“PYTHON”,”DS”}
>>> [Link](s2)
>>> print(s1)
{‘C’, ‘CPP’, ‘PYTHON’, ‘DS’}
>>> print(s2)
{‘PYTHON’, ‘DS’}
2. frozenset
==================
=>'frozenset' of one of the pre-defined class treated as Set category 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 in a single
variable".
=>The elements of frozenset organized within curly braces { } after converting
from tuple, list,set ..etc by using frozenset() and elements separated by
comma.
=>The elements of frozenset never maintains insertion Order bcoz it displays its
elements in any of the possibilities.
Print by VIKASH Page - 43
=>On the object of frozenset, we can't perform indexing and Slicing Operations bcoz
it can't maintain insertion order.
=>An object of frozenset belongs to immutable (never allows add(),item assignment )
=>To convert one type value into frozenset type values , we use frozenset().
=>We have two types of frozenset objects.
a) empty frozenset
b) non-empty frozenset
a) empty frozenset:
=>An empty frozenset is one, whose length is 0
Syntax: frozensetobj=frozenset()
b) non-empty frozenset:
=>An non-empty frozenset is one, whose length is >0
Syntax: frozensetobj=frozenset( {val1,val2....val-n} )
Syntax: frozensetobj=frozenset( [val1,val2....val-n] )
Syntax: frozensetobj=frozenset( (val1,val2....val-n) )......etc
Note:- The functionality of frozenset is exactly similar to set but an object set
belongs to both mutable ( add() ) and immutable ( item assignment) where an object
frozenset is immutable ( not possible to add() and item assignment)
Examples:
>>> s1={10,20,30,40,30}
>>> print(s1,type(s1))-----------{40, 10, 20, 30} <class 'set'>
>>> fs=frozenset(s1)
>>> print(fs,type(fs))----frozenset({40,10,20,30}) <class 'frozenset'>
>>> tp=(10,"RS","PYTHON")
>>> fs=frozenset(tp)
>>> print(fs,type(fs))--frozenset({'RS',10,'PYTHON'})<class'frozenset'>
>>> lst=[10,12.34,"Python","Java",2+3j]
>>> fs=frozenset(lst)
>>> print(fs,type(fs))---frozenset({'Python', 10, (2+3j), 12.34,
'Java'}) <class'frozenset'>
>>> print(fs[0])----TypeError: 'frozenset' object is not subscriptable
>>> print(fs[0:3])---TypeError: 'frozenset' object is not subscriptable
>>> fs[0]="Data Sci"---TypeError: 'frozenset' object does not support
item assignment
>>> [Link]("Data Sci")---AttributeError: 'frozenset' object has no
attribute 'add'
>>> fs=frozenset()
>>> print(fs,type(fs))----frozenset() <class 'frozenset'>
>>> len(fs)---------0
>>> fs=frozenset([10,20,20,30,30,10])
>>> print(fs,type(fs))----frozenset({10, 20, 30}) <class 'frozenset'>
>>> len(fs)----------3
=>'dict' is one of the pre-defined class and treated as Dict Category Data Type
=>The purpose of dict data type is that " To Organize / store the data in the form
of (Key,Value)
=>In (Key,Value), The values of Key represents Unique and values of Value may
or may not be unique.
=>In organize / store the data in the object of dict, those (Key,Value) must
written with curly braces { }
=>An object of dict maintains Insertion Order .
=>On the object of dict, we can't perform Indexing and slcing Operation bcoz values
of Key itself acts index.
=>We have two types of dict objects. they are
a) Empty Dict
b) Non-Empty Dict
a) Empty Dict:
=>An empty dict does not contain any elements and whose length is 0
=> Syntax: dictobj={}
(or)
dictobj=dict()
Syntax for adding (Key,Value) to dict object
dictobj[Key1]=Value1
dictobj[Key2]=Value2
--------------------------------
dictobj[Key-n]=Value-n
Examples:
>>> d1={}
>>> print(d1,type(d1),id(d1))------{} <class 'dict'> 2186120856832
>>> d1[10]="RS"
>>> d1[20]="DR"
>>> d1[30]="TR"
>>> d1[40]="MCK"
>>> print(d1,type(d1),id(d1))
{10: 'RS',20: 'DR', 30: 'TR', 40: 'MCK'} <class 'dict'>56832
(OR)
>>> d1=dict()
>>> print(d1,type(d1),id(d1))----{} <class 'dict'> 17760
>>> d1[10]="RS"
>>> d1[20]="DR"
>>> d1[30]="TR"
>>> d1[40]="MCK"
>>> print(d1,type(d1),id(d1))
{10: 'RS', 20: 'DR', 30: 'TR', 40: 'MCK'} <class 'dict'> 17760
b) Non-Empty Dict:
=>An non-empty dict contains any elements and whose length is >0
Syntax:
dictobj={Key1:Value1,Key2:Value2.......Key-n:Value-n}
Examples:
>>> d1={10:"Rossum",20:"Ritche",30:"Gosling",40:"Travis"}
>>> print(d1,type(d1))
{10:'Rossum',20: 'Ritche',30:'Gosling',40:'Travis'}<class 'dict'>
>>> d1[10]="MCKinney"
>>> print(d1,type(d1))
{10:'MCKinney',20:'Ritche',30:'Gosling',40:'Travis'}<class 'dict'>
>>> len(d1)---4
>>> d1={10:"Rossum",20:"Ritche",30:"Gosling",40:"Travis"}
=============================================
2) 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 in dict object then we get KeyError.
> Syntax:- [Link](key)
Examples:
>>> d1={'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> print(d1)
{'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> [Link]("Sberry")-----100.34
>>> print(d1)---{'Apple': 25.67, 'Kiwi': 30, 'Mango': 80}
>>> [Link]("Mango")-------80
>>> print(d1)-------{'Apple': 25.67, 'Kiwi': 30}
>>> [Link]("Mangoes")------KeyError: 'Mangoes'
4) get():
=>This function is used for obtaining value of Value by passing value of Key.
=>If the value of Key does not exists then we get None
=>Syntax:- varname=[Link](Key)
Examples:
>>> d1={'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> print(d1)--{'Apple':25.67,'Kiwi':30,'Sberry':100.34,'Mango': 80}
>>> v1=[Link]("Apple")
>>> print(v1)---25.67
>>> v1=[Link]("Guava")
>>> print(v1)---None
5) keys()
=>This Function obtains list of keys from non-empty dict object.
=> when we call keys() upon empty dict then we get empty list
=>Syntax: keys=[Link]()
Examples:
>>> d1={'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> print(d1)---{'Apple':25.67,'Kiwi':30,'Sberry':100.34,'Mango': 80}
>>> [Link]()---dict_keys(['Apple', 'Kiwi', 'Sberry', 'Mango'])
>>> ks=[Link]()
>>> print(ks)----dict_keys(['Apple', 'Kiwi', 'Sberry', 'Mango'])
>>> for k in [Link]():
... print(k)
...
Apple
Kiwi
Sberry
Mango
>>> dict().keys()---dict_keys([])
>>> {}.keys()---dict_keys([])
>>> {'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}.keys()
dict_keys(['Apple', 'Kiwi', 'Sberry', 'Mango'])
6) values()
=>This Function obtains list of values from non-empty dict object.
=> when we call values() upon empty dict then we get empty list
=>Syntax: values=[Link]()
Examples:
>>> d1={'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> print(d1)---{'Apple':25.67,'Kiwi':30,'Sberry':100.34,'Mango': 80}
Print by VIKASH Page - 47
>>> vs=[Link]()
>>> print(vs)----dict_values([25.67, 30, 100.34, 80])
>>> [Link]()----dict_values([25.67, 30, 100.34, 80])
>>> for val in [Link]():
... print(val)
...
25.67
30
100.34
80
>>> {'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34,}.values()
dict_values([25.67, 30, 100.34])
>>> {}.values()----dict_values([])
>>> dict().values()---dict_values([])
Special Case:
>>> d1={'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> print(d1)---{'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango':
80}
>>> for x in d1:
... print(x)
...
Apple
Kiwi
Sberry
Mango
7) items():
=>This function obtains all (Key,value) from from dict object in the form tuple.
=>when we call items() upon empty dict object then we get empty list.
Syntax:- keyvalue=[Link]()
Examples:
>>> d1={'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
>>> [Link]()
dict_items([('Apple', 25.67), ('Kiwi', 30), ('Sberry', 100.34),
('Mango', 80)])
>>> kv=[Link]()
>>> print(kv)
dict_items([('Apple', 25.67), ('Kiwi', 30), ('Sberry', 100.34),
('Mango', 80)])
>>> for kv in [Link]():
... print(kv)
...
('Apple', 25.67)
('Kiwi', 30)
('Sberry', 100.34)
('Mango', 80)
>>> for k,v in [Link]():
... print(k,"--->",v)
...
Apple ---> 25.67
Kiwi ---> 30
Sberry ---> 100.34
Mango ---> 80
>>> dict().items()-------dict_items([])
8) copy() :
=>This function is used for copying the content of one dict object into another
dict object (shallow Copy)
=>Syntax:- dictobj2=[Link]()
9)update():
Examples:
>>> d1={"Praveen":"Python","Kiran":"Java"}
>>> d2={"RS":"Django","DR":"C"}
>>> d3=[Link](d2)
>>> print(d1)---{'Praveen':'Python','Kiran':'Java','RS':'Django','DR': 'C'}
>>> print(d2)---{'RS': 'Django', 'DR': 'C'}
>>> print(d3)---None
>>> d1={"Praveen":"Python","Kiran":"Java"}
>>> d2={"Praveen":"Django","DR":"C"}
>>> [Link](d2)
>>> print(d1)--{'Praveen': 'Django', 'Kiran': 'Java', 'DR': 'C'}
>>> print(d2)---{'Praveen': 'Django', 'DR': 'C'}
=======================================
none type data type
=======================================
=>'None Type' is one the pre-defined class and treated as None type Data type
=> "None" is keyword acts as value for <class,'NoneType'>
=>The value of 'None' is not False, Space , empty , 0
=>An object of NoneType class can't be created explicitly.
=>If the function is not returning any value and if we print by using print() then
we get None as result.
Examples:
>>> a=None
>>> print(a,type(a))------------None <class 'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType' is not defined
>>> d1={10:"ABC",20:"PQR"}
>>> print([Link](10))--------ABC
>>> print([Link](100))-----None
=================================================
Number of approaches to develop python programs
=================================================
=>In Python Programming Environment, we have 2 approaches to develop a python
Program. They are
a) Interactive Mode
b) Batch Mode
a) Interactive Mode:
=> This Mode of Development, The Python Programmer Issued One statement and
got its result immediately and such statements can't be saved . So that we can't
re-use in further applications development.
=> This mode develop is useful for Testing one instruction at time and not
recommended to develop bunch of instruction for big problem solving.
=> Industry Recommeded to Batch Mode for developing Batch of instruction for big
problem solving..
2) Batch Mode:
=> In Batch Mode Programming, we develop batch of optimized instructions for
solving any problem statement and it saved on filename with an extension .py
(Source Code).
Examples: [Link] [Link] [Link]....etc
====================================================
Displaying the Result (or) Data on the Console
====================================================
=>To Display the Result of Python Program , we use pre-defined Function called
print()
=>In otherwords, print() is used for Displaying the Result of python on the
console.
=>Syntax-1: Displaying only Data / values
print(val1,val2....val-n)
Examples:
>>> a=10
>>> print(a)----------10
>>> s="Python"
>>> print(s)--------Python
>>> print(a,s)-----10 Python
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum of %d and %d=%d" %(a,b,c))---Sum of 10 and 20=30
>>> print("Sum of %f and %f=%f" %(a,b,c))--
Sum of 10.000000 and 20.000000=30.000000
>>> print("Sum of %0.2f and %0.2f=%0.3f" %(a,b,c))--Sum of 10.00 and
20.00=30.000
>>> a=2.3
>>> b=3.4
>>> c=a+b
>>> print("sum(%f,%f)=%f" %(a,b,c))---sum(2.300000,3.400000)=5.700000
>>> print("sum(%0.1f,%0.1f)=%0.2f" %(a,b,c))--sum(2.3,3.4)=5.70
>>> print("sum(%d,%d)=%0.2f" %(a,b,c))---sum(2,3)=5.70
>>> print("sum(%d,%d)=%d" %(a,b,c))---sum(2,3)=5
=======================================================
Reading the Data (or) Input Values from Key Board
========================================================
=>To read the data Dynamically from Keyboard, we have 2 pre-defined functions. They
are
a) input()
b) input(Message)
a) input()
=>input() is used reading any type of data / value dynamically from keyboard
in the form of str always.
=>Syntax:
varname=input()
=> here 'varname' is an object of <class,'str'>. To convert str values into other
data type values, we Type casting Functions (int(), float(), bool(), str(),
complex()....etc)
=> input() is a pre-defined function and it reads at a time only one value in the
form of str.
Write a Program for accepting two values and find their sum
#[Link]
print("Enter Value for a:")
a=input()
print("Enter Value for b:")
b=input()
#convert a and b values into int type
n=int(a)
m=int(b)
res=n+m
print("sum of {} and {}={}".format(n,m,res))
Write a Program for accepting two values and find their sum
#[Link]
print("Enter Two Values for a and b:")
a=input()
b=input()
#convert a and b values into int type
n=float(a)
m=float(b)
res=n+m
print("sum of {} and {}={}".format(n,m,res))
==========================================
Operators in Python
==========================================
=>An Operator is a symbol, which is used to perform certain operation.
=>Any two or more object / variables connected with an operator is called
Expression.
=>In Python Programming, we have 7 types of Operators. They are
=========================================
1) Arithmetic Operators
=========================================
=>Arithmetic Operators are used for performing all types of Arithmetic Operations
such as addition , subtraction, multiplication..etc
=>If two or more variables / objects are connected with Arithmetic Operators then
it is called Arithmetic Expression.
=>The following table gives list of Arithmetic Operators.
=============================================================================
Slno Symbol Meaning Examples a=10 b=3
=============================================================================
1. + Addition print(a+b)----13
2. - Substraction print(a-b)-----7
3. * Multiplication print(a*b)-----30
4. / Division print(a/b)----3.3333333
(Float Quotient) print(10.0/3.0)--3.333333
7. ** Exponentiation print(a**b)
===================================================================================
===================================================================================
slno symbol meaning Examples a=10 b=20 c=10
===================================================================================
1 > Greater Than print(a>b)------False
print(b>c)------True
2. < Less Than print(a<b)------True
print(a<c)------False
3. == Equality print(a==b)----False
print(a==c)----True
4. != not equal to print(a!=c)-----False
print(a!=b)-----True
================================================
4. Logical Operators in Python
================================================
=>The purpose of Logical Operators is that " To combine two or more number of
Relational Expressions / Conditions".
=>If two or more Relational Expressions / Conditions connected with Logical
Operators then it is called Logical Expression / Compound Condition.
=>The reuslt of Logical Expression / Compound Condition is True or False
=>The Logical Operators are given in the following table
===============================================================
slno symbol meaning
===============================================================
1. or Physical ORing
2. and Physical ANDing
3. not --------------------------
===============================================================
Print by VIKASH Page - 55
1) or (Physical ORing)
=>The Functionality of 'or' operator is shown in the following truth table
Syntax:- RelExpr1 or RelExpr2
===============================================================
RelExpr1 RelExpr2 RelExpr1 or Relexpr2
===============================================================
True False True
False True True
False False False
True True True
Examples:
>>> 10>20 or 20!=30------------True
>>> 10!=20 or 10>20---------True
>>> 10!=100 or 10>20 or 20<10---True
>>> 10>20 or 10!=20 or -10!=-20---True
>>> 10>20 or 10==20 or -10!=-20----True
>>> 10>20 or 10==20 or -10<=-20----False
========================================
5. Bitwise Operators (Most Imp)
========================================
=>Bitwise Operators applied only on Integer Values but not on float values.
=>Bitwise Operators converts given Integer data into Binary format and performs
operations on binary data in the form of Bit by Bit and hence they named as
Bitwise Operators.
=>In Python Programming, we have 6 Bitwise Operators. They are
1) Bitwise Left shift Operator ( << )
2) Bitwise Right shift Operator ( >> )
3) Bitwise OR Operator ( | )
4) Bitwise AND Operator ( & )
5) Bitwise complement Operator ( ~ )
6) Bitwise XOR Operator ( ^ )
3) Bitwise OR Operator ( | ):
=> Syntax: resultantvar= value1 | value2
=>The Functionality of Bitwise OR Operator ( | ) is shown in the following table.
----------------------------------------------------
Value1 Value2 Value1 | Value2
----------------------------------------------------
0 0 0
0 1 1
1 0 1
1 1 1
----------------------------------------------------
>>>print(10|15)---------------> 1010
1111
------------
1111----Result--15
------------------------------------------------------------------------
Special Case of Bitwise OR (|)
>>>s1={10,20,30}
>>>s2={30,40,50}
>>>s3=[Link](s2)
>>> print(s3)-----------{50, 20, 40, 10, 30}
>>>
>>> s4=s1|s2
>>> print(s4,type(s4) )---------{50, 20, 40, 10, 30} <class 'set'>
Examples:
>>>a=5-------------> 0101 Special Case:
>>>b=4-------------> 0100 >>>s1={10,20,30}
--------------------------- >>>s2={30,40,50}
>>>c=a&b--------> 0100------ >>>s3=[Link](s2)
---------Result is 4 >>>print(s3)-----{30)
>>> print(c)---------4 >>>s4=s1&s2
>>> print(15&10)-------10 >>>print(s4)-------{30}
>>> print(7&2)--------2
>>> a=15
>>> b=10
>>> print(a^b)------------5
Special case:
>>>s1={10,20,30}
>>>s2={30,40,50}
>>>s3=s1.symmetric_difference(s2)
>>> print(s3)--------{40, 10, 50, 20}
>>> s4=s1^s2
>>> print(s4)-------{40, 10, 50, 20}
Write a program to swap a number using xor operator.
#[Link]
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*40)
print("Original Value of a:{}".format(a))
print("Original Value of b:{}".format(b))
print("-"*40)
#swapping logic by busing XOR ( ^ )
a=a^b
b=a^b
a=a^b
print("Swapped Value of a:{}".format(a))
print("Swapped Value of b:{}".format(b))
print("-"*40)
================================================
6. Membership Operators
================================================
=>The purpose of Membership Operators in python is that "To verify / check the
existence of whether the value present in sequence or collection obejcts"
=>In Python Programming, we have 2 Membership Operators. They are
a) in
b) not in
a) in:
Syntax:- Value in Sequence / Collection object
=====================================
7. Identity Operators
=====================================
=>The purpose of Identity Operators is that to "To compare the memory addresses of
two objects"
=>In Python Programming, we have 2 types of Identity Operators. They are
a) is
b) is not
a) is:
Syntax:- obj1 is obj2
=> "is" operator returns True provided both obj1 and obj2 contains same memory
address otherwise it returns False
>>> b1=True
>>> b2=True
>>> print(b1, id(b1))----------True 140703467879272
>>> print(b2, id(b2))----------True 140703467879272
>>> b1 is b2-------------------True
>>> b1 is not b2---------------False
-----------------------------------------------------------------------------------
>>> a=12.34
>>> b=12.34
>>> print(a, id(a))-------------12.34 1772239374960
>>> print(b, id(b))-------------12.34 1772239374352
>>> a is b----------------------False
>>> a is not b------------------True
-----------------------------------------------------------------------------------
>>> a=10
>>> b=10
>>> print(a, id(a))-------------10 1772238340624
>>> print(b, id(b))-------------10 1772238340624
>>> a is b----------------------True
>>> a is not b------------------False
>>> a=256
>>> b=256
>>> print(a, id(a))-------------256 1772238348496
>>> print(b, id(b))-------------256 1772238348496
>>> a is b----------------------True
===========================================
Flow control statements in python
===========================================
=>The purpose of Flow control statements in python is that "To perform
certain operation one time ( Perform X-Operation in the case of True
(or) Peform Y-Operation in the case of False ) (or) Peform certain
operation repeatedly for finite number of times until Condition is False."
=>In Python Programming, we have 3 types of Flow control statements in
python. They are
1) Conditional (or) Selection (or) Branching Statements
2) Looping (or) Iterative (or) Repeatative Statements
3) Misc Control statements.
EXAMPLE 1:- Write a program in python, find big number in input two value and print
them.
#[Link]
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:")) #b=20
if(a==b):
print("Both the v
values are Equal")
if(a>b):
print("big({},{})={}".format(a,b,a)) # big(100,20)=100
if(b>a):
print("big({},{})={}".format(a,b,b))
EXAMPLE 2:- Write a program in python, find big number in input three number and
print them.
#[Link]
a=int(input("Enter First Value:")) # 10
b=int(input("Enter Second Value:"))# 10
c=int(input("Enter Third Value:"))# c=10
if(a>b) and (a>c):
print("big({},{},{})={}".format(a,b,c,a))
if(b>a) and (b>c):
print("big({},{},{})={}".format(a,b,c,b))
if(c>a) and (c>b):
print("big({},{},{})={}".format(a,b,c,c))
if(a==b)and (b==c):
print("ALL VALUES ARE EQUAL")
(OR)
Syntax-1 Syntax-2
for varname in Iterable_Object: for varname in Iterable_Object:
statement-1 statement
statement-1
statement-2 statement
statement-2
---------------- ----------------
statement-n statement
statement-n
---------------------------- else:
Other Statements in program else Block of Statements
--------------------------------- ---------------------------------
Other Statements in program
======================================
match ...case concept
======================================
Syntax:-
match ChoiceExpression:
case label1: Block of statement-1
case label2: Block of statement-2
------------------------------------
------------------------------------
case label-n: Block of stetement-n
case _:
default Case Block statements
-------------------------------------
Other statements in Program
Explanation:
=================
=>The ChoiceExpression can be either int, str, bool etc (except float and complex)
=>If the Value of ChoiceExpression is equal to Case Label1 then PVM executes
corresponding Block of stateements-1 and later executes other statements in
Program.
=>If the Value of ChoiceExpression is not equal to Case Label1 then PVM compares
Value of ChoiceExpression with Case Label2 and if it is equal then executes
corresponding Block of stateements-2 and later executes other statements in
Program.
=>This process will be continued with all case labels. In general if the value of
Choice Expression is equal to any of the specified Case Labels then PVM executes
corresponding block of statements and later executes Other statements in Program.
=>If the Value of ChoiceExpression is not matching with any case labels then PVM
executes the block of statements written within default case block ( case _ : )
and later exeutes Other statements in Program.
======================================
break statement
======================================
=>break is a key word
=>The purpose of break statement is that "To terminate the execution of loop
logically when certain condition is satisfied and PVM control comes of
corresponding loop and executes other statements in the program".
=>Syntax: =>Syntax:
for var in Iterable_object: while(Test Cond-1):
if (test cond): ------------------
break if (test cond-2):
--------------------- break
--------------------- ----------------
----------------
#[Link] #[Link]
age=int(input("Enter the age:")) while(True):
if(age>=18): age=int(input("Enter the Correct age:"))
print("Citizen is eligible to Vote:") if(age>=18) and ( age<=100):
else: break
print("Citizen is not eligible to Vote:") print("Citizen is eligible to Vote:")
Q) write a program to input “PYTHON” and print them Q) write a program to input “PYTHON” and print them
“PYTON” “PYHN”
#[Link] #[Link]
s="PYTHON" s="PYTHON"
for val in s: #display PYHN
print("\t{}".format(val)) for val in s:
print("----------------------------------") if(val=="T") or (val=="O"):
#display PYTON continue
for val in s: print("\t{}".format(val))
if(val=="H"): else:
continue print("\nI am from else part:")
print("\t{}".format(val))
else:
print("\nI am from else part:")
#[Link]
tpl=(10,20,30,40,50,60,70,80)
for val in tpl:
if(val==20) or (val==50) or (val==70):
continue
print("\t{}".format(val))
else:
print("\nI am from else part:")
#[Link]
n=int(input("Enter How Many Numbes u have:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=list()
for i in range(1,n+1):
value=float(input("Enter {} value: ".format(i)))
=======================================
Nested (or) Inner Loops in Python
=======================================
=>The Process of defining one loop inside of another is called Nested / Inner Loop.
=>The Execution Process of Inner Loops is that "For Every value of Outer Loop inner
loop executed many times".
=>Syntax1: =>Syntax2:
for varname1 in Iterable_object1: # Outer loop ----------------------------
----------------------------------- while(Test Cond1): # outer loop
for vaname2 in Iterbale_object2: # Inner Loop -----------------------
--------------------------- -----------------------
--------------------------- while(Test Cond2): # inner loop
else: ---------------------
-------------------------------- ---------------------
else: else:
----------------------------------- ----------------------
else:
----------------------------
Syntax-3 =>Syntax4:
for varname1 in Iterable_object1: # Outer loop ----------------------------
----------------------------------- while(Test Cond1): # outer loop
while(Test Cond2): # inner loop -----------------------
--------------------- -----------------------
--------------------- for varname in iterable_object: # inner loop
else: ---------------------
---------------------- ---------------------
else else:
----------------------------------- ----------------------
else:
----------------------------
#[Link] #[Link]
for i in range(1,6): i=1
print("Val of i (outer Loop)=",i) while(i<6):
print("-------------------------------------") print("Val of i (outer Loop)=",i)
for j in range(1,4): print("-------------------------------------")
print("Val of j (Inner Loop)=",j) j=1
else: while(j<4):
print("I am out inner loop") print("Val of j (Inner Loop)=",j)
print("-------------------------------------") j=j+1
else: else:
print("i am out of outer loop") print("I am out of inner loop")
i=i+1
print("-------------------------------------")
else:
print("i am out of outer loop")
#[Link]
for i in range(5,0,-1): #[Link]
print("val of i (outer loop)=",i) i=1
print("----------------------------------") while(i<6):
j=3 print("Val of i (outer Loop)=",i)
while(j>0): print("-------------------------------------")
print("Val of j=",j) for j in range(3,0,-1):
j=j-1 print("Val of j(Inner Loop)=",j)
else: else:
print("out of inner while loop") print("I am out of inner loop")
print("----------------------------------") i=i+1
else: print("-------------------------------------")
print("Out of outer for loop") else:
print("i am out of outer loop")
#[Link]
lst=[-45,3,14,19,9,7,0,8]
for n in lst: # outer loop supplies values from lst
if(n<=0):
print("{} is invalid input".format(n))
else:
print("-------------------------------")
print("Mul Table of {}".format(n))
print("-------------------------------")
for i in range(1,11): # inner loop generates mul table for the val supplied by Outer loop
print("\t{} x {}={}".format(n,i,n*i))
else:
print("-------------------------------")
=>Types of Functions.
=>We have two types of Functions. They are
a) Pre-defined (or) Built-in Functions.
b) Programmer / User / Custom Defined Functions.
a) Pre-defined (or) Built-in Functions are those which are already developed and available in Python API and
They re-used by Python Programmers for dealing with Unversal Purpose.
Examples: int() float(), append(), print(), id() type()....etc
b) Programmer / User / Custom Defined Functions are developed by Python Programmers and re-used by other
Python programmers and they are meant for performing common operations.
Examples: deposit() withdraw() balenq() genotp()...etc
Types of Languages
---------------------------------------
=>In the context of Functions, we can classify the Programming languages into two types. They are
a) Un-Structured Programming Languages
b) Structured Programming Languages
Approach1:
INPUT:- Takes Inputs from Function Calls (Outside) Approach2:
PROCESS: Proces the input inside of Function Body(Inside) INPUT:- Takes Inputs in Function Body (Inside)
OUTPUT:- Function gives result to the Function call(Outside) PROCESS: Proces the input inside of Function Body(Inside)
OUTPUT:- Function gives result within Function Body(Inside)
#[Link]
def sumop(a,b): # here 'a' and 'b' are called #[Link]
Formal Params def sumop():
c=a+b # here 'c' is called local variable a=float(input("Enter First Value:"))
return c b=float(input("Enter Second Value:")) # INPUT
c=a+b # PROCESS
#main program print("\nsum({},{})={}".format(a,b,c)) # OUTPUT
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:")) #main program
res=sumop(x,y) # Function Call sumop() # Function Call
print("sum({},{})={}".format(x,y,res))
Approach3: Approach4:
INPUT:- Takes Inputs in Function Body (Inside) INPUT:- Takes Inputs from Function Calls (outside)
PROCESS: Proces the input inside of Function Body(Inside) PROCESS: Proces the input inside of Function Body(Inside)
OUTPUT:- Function gives result to the Function Call(outside) OUTPUT:- Function gives result within Function Body(Inside)
#[Link] #[Link]
def sumop(): def sumop(a,b):
a=float(input("Enter First Value:")) c=a+b
b=float(input("Enter Second Value:")) print("sum({},{})={}".format(a,b,c))
c=a+b
return("sum {} and {}={}".format(a,b,c)) #main program
a=float(input("Enter First Value:"))
#main program b=float(input("Enter Second Value:"))
result=sumop() sumop(a,b)
print(result)
Some example :-
#[Link]
def sumop(a,b): # here 'a' and 'b' are called Formal Params #[Link]
c=a+b # here 'c' is called local variable def sumop():
return c a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:")) # INPUT
#main program c=a+b # PROCESS
x=float(input("Enter First Value:")) print("\nsum({},{})={}".format(a,b,c)) # OUTPUT
y=float(input("Enter Second Value:"))
res=sumop(x,y) # Function Call #main program
print("sum({},{})={}".format(x,y,res)) sumop() # Function Call
#main program
n=int(input("Enter a number:"))
result=sqroot(n) # function call
print("sqrt({})={}".format(n,result))
#[Link] print("sqrt({})={}".format(n,res))
#Approach-2 print("===========OR===========")
def sqroot(): result=sqroot()
n=int(input("Enter a number:")) print("sqrt({})={}".format(result[0],result[1]))
res=n**0.5
print("sqrt({})={}".format(n,res))
#main program
sqroot() # function call
#[Link]
#[Link] #Approach-4
#Approach-3 def sqroot(n):
def sqroot(): res=n**0.5
n=int(input("Enter a number:")) print("sqrt({})={}".format(n,res))
res=n**0.5
return n,res #main program
n=int(input("Enter a number:"))
#main program sqroot(n) # function call
n,res=sqroot()
#[Link]
def disp(obj):
print("type of obj=",type(obj))
for val in obj: #[Link]
print("\t{}".format(val)) def table(n):
if(n<=0):
def show(obj): print("{} is invalid input:".format(n))
for k,v in [Link](): else:
print("\t{}\t{}".format(k,v)) print("-"*50)
print("Mul table for {}".format(n))
#main program print("-"*50)
print("List of Values:") for i in range(1,11):
lst=[10,23,45,4,56,123,-45,-6] print("\t{} x {} =
disp(lst) {}".format(n,i,n*i))
print("set of values") else:
s1={23,"Rossum",56.78,True} print("-"*50)
disp(s1) #main program
print("Dict Values") x=int(input("Enter a number:"))
d1={10:"Python",20:"Java",30:"DS",40:"ML"} table(x) # Function Call
show(d1)
#[Link]
def readvalues():
lst=[]
print("Enter how many values u have:")
n=int(input())
for i in range(1,n+1):
val=float(input("Enter {} value:".format(i)))
[Link](val)
return lst
def computesumavg(lst):
s=0
print("---------------------------------")
for val in lst:
print("\t{} ".format(val))
s=s+val
else:
print("---------------------------------")
print("\tsum={}".format(s))
print("\tAvg={}".format(s/len(lst)))
print("---------------------------------")
#main program
lst=readvalues() # function call
computesumavg(lst)
Print by VIKASH Page no -79
Argument (or) Parameter Passing Mechanisms.
=>Based on the values of arguments passing to Parameters , The mechanism of values passing are classfied
into 5 types. They are
1) Positional Parameters / Arguments (default)
2) Default Parameters / Arguments
3) Keyword Parameters / Arguments
4) Variable length Parameters / Arguments
5) Keyword Variable length Parameters / Arguments
#[Link]
def dispstuddet(stno,sname,marks):
print("\t{} \t{}\t{}".format(stno,sname,marks))
#main program
print("---------------------------------------")
print("\tStudent Information:")
print("---------------------------------------")
print("\tstno\tName\tMarks")
print("---------------------------------------")
dispstuddet(10,"RS",34.56)
dispstuddet(20,"JG",24.56)
dispstuddet(30,"DR",84.56)
print("---------------------------------------")
Rule-: When we use default parameters in the function definition, They must be used as last
Parameter(s) otherwise we get Error( Syntax Error: non-default argument follows default argument).
#[Link]
def area(r,PI=3.14):
ac=PI*r**2
print("Area of Circle={}".format(ac))
def peri(PI=3.14):
r=float(input("Enter Radius for cal peri:"))
pc=2*PI*r
print("Peri. of Circle={}".format(pc))
#main program
r=float(input("Enter Radius for cal Area:"))
area(r)
print("-----------------------------------------")
peri()
=>Rule:- The *param must always written at last part of Function Heading and it must be only one (but not multiple)
=>Rule:- When we use Variable length and default parameters in function Heading, we use default parameter
as last and before we use variable length parameter and in function calls, we should not use default
parameter as Key word argument bcoz Variable number of values are treated as Posstional Argument
Value(s)
==================================================
Keyword Variable length Parameters (or) Arguments
==================================================
=>When we have familiy of multiple function calls with Keyword Variable length number of values / arguments
then with normal python programming, we must define multiple function defintions. This process leads to more
development time. To overcome this process, we must use the concept of Keyword Variable length Parameters
=>To Implement, Keyword Variable length Parameters concept, we must define single Function Definition
and takes a formal Parameter preceded with a symbol called double astrik ( ** param) and the formal
parameter with double astrik symbol is called Keyword Variable length Parameter and whose purpose is to
hold / store any number of keyword variable length values coming from similar function calls and whose type
is <class, 'dict'>.
Syntax for function definition with Keyword Variables Length Parameters:
def functionname(list of formal params, **param) :
--------------------------------------------------
--------------------------------------------------
=>Here **param is called Keyword Variable Length parameter and it can hold any number of keyword variable
length values / argument values and **param type is <class,'dict'>
=>Rule:- The **param must always written at last part of Function Heading and it must be only one (but not
multiple)
#[Link] #[Link]
def dispinfo(**x): # here **x is called kwd var length def totalmarks(sname,cls, **infor):
parameter--<class,dict> print("-"*40)
print("-"*40) print("Student Name:{}".format(sname))
for k,v in [Link](): print("Student Studying in :{}".format(cls))
print("\t{}\t{}".format(k,v)) print("-"*40)
else: print("\tSubjects\tMarks")
print("-"*40) print("-"*40)
totmarks=0
#main program for subj,marks in [Link]():
dispinfo(rname="Rossum") print("\t{}\t\t{}".format(subj,marks))
dispinfo(sno=10,sname="RS") totmarks=totmarks+marks
dispinfo(eno=20,ename="RT",sal=4.6) else:
dispinfo(idno=111,name="Sandeep",hobby1="Reading print("-"*40)
",hobby2="practcing") print("\tTotal
Marks={}".format(totmarks))
#main program
totalmarks("RS","X",Eng=67,Tel=66,Sci=88,maths=99,soc=88)
totalmarks("DR","XII",Phy=56,Che=58,Mathematics=74)
totalmarks("TR","[Link]",C=60,Python=60)
totalmarks("MCK","Research")
Print by VIKASH Page no -82
==========================================
Special Functions in Python
==========================================
=>In Python Programming, we have 3 special Functions. They are
1) filter()
2) map()
3) reduce()
1) filter()
=>This function is used for " filtering out some elements based on some condition from any Collection /
Iterable objects by applying to the function."
Syntax:- varname=filter(Function_name, Iterable_object )
Explanation:
=>'varname' is an object of <class, 'filter'> and we can convert into any
iterable_object type.
=>"Function name" is either normal function and anonymous function and it must
return either True or False.
=>"Iterable_object " can any Sequence type or collection types.
=>Execution Process of filter() is that " filter() send every element of iterable_object to the
specified Function. if the function returns True then Filter() will consider / filter that element . if
The Function returns False then filter() will neglect that element ( not filtered). This Process will
be continued until all elements of Iterable object will complete."
EXAMPLE 1
#[Link]
def positive(n):
if n>0 :
return True
else :
return False
def negative(n):
if(n<0):
return True
else:
return False
#main program
lst=(10,20,-40,-56,0,23,-67,89,-25,45)
filtobj=filter(positive,lst)
print("type of filtobj var=",type(filtobj)) # <class, 'filter'>
#print("Content of filtobj=",filtobj) Content of filtobj= <filter object at 0x00000204745CF0D0>
pslst=list(filtobj) # convert filter object into any collection object type
print("--------------------------------------------")
print("Original Elements=",lst)
print("--------------------------------------------")
print("Possitive elements=",pslst)
print("--------------------------------------------")
chi=filter(negative,lst)
nslst=set(chi)
print("Negative elements=",nslst)
print("--------------------------------------------")
EXAMPLE 3 EXAMPLE 4
#[Link] #[Link]
lst=(10,20,-40,-56,0,23,-67,89,-25,45) #read the elements dynamically
pslst=list(filter(lambda n : n>0, lst)) lst=[]
nslst=tuple(filter(lambda n : n<0, lst)) n=int(input("Enter How many elements u want :"))
print("--------------------------------------------") print("Enter {} elements:".format(n))
print("Original Elements=",lst) print("------------------------------------------")
print("--------------------------------------------") for i in range(1,n+1):
print("Possitive elements=",pslst) val=float(input())
print("--------------------------------------------") [Link](val)
print("Negative elements=",nslst) else:
print("--------------------------------------------") print("--------------------------------------------")
print("Original Elements=",lst)
print("--------------------------------------------")
pslst=list(filter(lambda n : n>0, lst))
nslst=tuple(filter(lambda n : n<0, lst))
print("Possitive elements=",pslst)
print("--------------------------------------------")
print("Negative elements=",nslst)
print("--------------------------------------------")
newsals=[11,22,11,33,44]----new list
#[Link]
def hike(esal):
esal=esal+esal*0.1
return esal
#[Link] #[Link]
print("Enter Old Salaries of employees:") print("Enter List of values :")
oldsal=[ int(sal) for sal in input().split()] oldlst=[ float(val) for val in input().split()]
newsal=tuple(map(lambda esal: squarelist=list(map(lambda n: n**2, oldlst))
esal*1.1,oldsal)) sqrootlist=list(map(lambda k : k**0.5, oldlst))
print("---------------------------------------") print("--------------------------------------------------")
print("Old Salaries=",oldsal) print("Original values:{}".format(oldlst))
print("New Salaries=",newsal) print("Square values:{}".format(squarelist))
print("---------------------------------------") print("Square Rool values:{}".format(sqrootlist))
print("--------------------OR------------------------------")
result=zip(oldlst,squarelist,sqrootlist)
print("-"*50)
print("\tGiven Number\tSquare\tSquareRoot")
print("-"*50)
for on,sqn,sqt in result:
print("\t{}\t\t{}\t{}".format(on,sqn,sqt))
print("-"*50)
3)reduce()
=>The purpose of reduce() is that "To obtain single result from list of elements by applying to the function"
=>reduce() present in pre-defined module called 'functools' module.
Syntax:- varname=[Link](funcname,iterable_object)
=>varname is of type int, float, bool, complex and str.
#[Link]
import functools #[Link]
print("Enter Salaries of employees:") import functools
sallist=[float(sal) for sal in input().split()] print("Enter Number of values separated by space")
totsal=[Link](lambda x,y:x+y, nums=[ int(val) for val in input().split()]
sallist) big=[Link](lambda x,y: x if x>y else y, nums)
print("Total Sal=",totsal) print("---------------------------------------------")
print("type of totalsal=",type(totsal)) print("Original Elements={}".format(nums))
print("--------------------------------------------------") print("Biggest Element={}".format(big))
#[Link]
import functools #[Link]
print("Enter Number of values separated by space:") import functools
nums=[ int(val) for val in input().split()] print("Enter Number of values separated by space:")
big=[Link](lambda x,y: x if x<y else y, nums) nums=[ int(val) for val in input().split()]
print("---------------------------------------------") pssum=[Link](lambda x,y:x+y,
print("Original Elements={}".format(nums)) list(filter(lambda x: x>0,nums)))
print("Smallest Element={}".format(big)) nssum=[Link](lambda x,y:x+y,
print("---------------------------------------------") list(filter(lambda x: x<0,nums)))
print("---------------------------------------------")
print("Original Elements={}".format(nums))
print("Possitive Element sum={}".format(pssum))
print("Nagative Element sum={}".format(nssum))
print("---------------------------------------------")
=>When we come acrosss same global Variable names and Local Variable Names in same function definition
then PVM gives preference for local variables but not for global variables.
=>In this context, to extract / retrieve the global variables names along with local variables, we must use
globals() and it returns an object of <class,'dict'> and this dict object stores all global variable Names as Keys
and global variable values as values of value.
=>Syntax:-
var1=val1
var2=val2
--------------
var-n=val-n # var1, var2...var-n are called global Variables
def functionname():
------------------------
var1=val11
var2=val22
-----------------
var-n=val-nn # var1, var2...var-n are called local Variables
# Extarct the global variables
dictobj=globals()
globalval1=dictobj['var1'] # [Link]("var1") or globals()['var1'] or globals().get("var1")
globalval2=dictobj['var2'] # [Link]("var2") or globals()['var2'] or globals().get("var1")
-----------------------------------------------------
-----------------------------------------------------
#[Link] #[Link]
a=10 sno=10
b=20 sname="Ritche" # here sno,sname are called
c=30 Global Variables
d=40 # here 'a' 'b' 'c' and 'd' are called global def testing():
variables sno=100
def operations(): sname="Rossum" # here sno,sname are
global c,d called local Variables
c=c+1 # c=31 print("Local Variable Values:")
d=d+1 # d=41 print("--------------------------------------")
a=100 print("Student Number:",sno)
b=200 # here 'a' and 'b' are called Local print("Student Name:",sname)
Variables print("--------------------------------------")
print("-------------------------------------") gv=globals() # obtains all global variables
print("Values of our program") print("type of gv=",type(gv)) # type of
print("-------------------------------------") gv=<class,'dict'>
print("Val of a (Local )=",a) print("Global Variable Values:")
print("Val of b (Local )=",b) print("--------------------------------------")
print("Val of a (global )=",globals()['a']) print("Student Number:",gv['sno'] )
print("Val of b (global )=",globals()['b']) print("Student Name:",gv['sname'] )
print("-------------------------------------") print(" OR ")
res=a+b+c+d +globals()['a']+globals().get('b') print("Student Number:", [Link]("sno") )
# 100+200+31+41-->372+10+20 print("Student Name:", [Link]("sname"))
print("sum=",res) print(" OR ")
print("-------------------------------------") print("Student Number:", globals()['sno'])
#main program print("Student Name:", globals()['sname'])
operations() print(" OR ")
print("Student Number:", globals().get('sno'))
print("Student Name:", globals().get('sname'))
print("--------------------------------------")
#main program
testing()
Print by VIKASH Page no -87
=========================================
Modules In python
=========================================
=>We know that Functions concept meant for performing certain Operation and provides Code Re-usability
within in the same program but not able to provide code-reusability across the programs. To overcome this
type of Problem we use Modules.
=>The purpose of Modules concept is that to provide code-reusability across the programs.
=>Definition of Module:
=>A Module is a collection of Variables (Global Variables) , Functions and Classes.
=>In Python we have type of Modules. They are
a) Pre-defined Module
b) Programmer-defined module
a) Pre-defined Module:
=>These modules are already developed by Python Software developers and available in Python software and
Whose role is to deal with Universal Requirements.
=>Examples:-
builtins functools calendar math cmath re cx_Oracle
mysql-connector, threading, numpy pandas...etc
NOTE:- builtins is the default pre-defined module
b) Programmer-defined module:
=>These modules are developed by Python Language Programmers and available in Python Project and whose
role is to deal with Common Requirements.
Examples:
banking, mathformulas, otpgen.....etc
==================================================
Creating Programmer-defined Module
==================================================
=>Creating a Programmer-defined Module is nothing but
a) Define / choose the Variables with Values (Global variables)
b) Define the Functions for performing Common Operations
c) Define the classes (In OOPs we discuss )
Save the above on some file name with an extension .py ([Link])
=>Hence [Link] compiled Version([Link]) is treated as Module Name
=>Once the a module is created , whose module name is placed within a folder which is created automatically by
Python Environment.
Examples: __pycache__
----------------------------
[Link]
Example 1:-
#[Link]---file name and acts as module name- print("Time:{}".format(t))
-->([Link]) print("Rate of Interest:{}".format(r))
def simpleint(): print("-"*50)
p=float(input("Enter Principle Amount:")) print("Simple Interest :{}".format(si))
t=float(input("Enter the time:")) print("Total Amount to Pay:{}".format(totamt))
r=float(input("Enter Rate of Interest:")) print("-"*50)
==========================================
Techniques for Re-Using the modules
==========================================
=>In Python Programming, we have two techniques for Re-Using the modules. They are
1) by using import statement.
2) by using from.... import statement.
=>AFTER IMPORTING A PERTICULAR MODULE, THE VARIABLE NAMES, FUNCTION NAMES AND CLASS NAMES MUST BE
ACCESSED W.R.T MODULE NAME OTHERWISE WE GET ERROR.
Syntax:- Module [Link] Name
Module [Link] Name
Module [Link] Name
(OR)
Module Alias [Link] Name
Module Alias [Link] Name
Module Alias [Link] Name
Syntax3:-
from module name import *
=>This syntax imports all variable names, function names and Class names
=>This syntax is not recommended to to use bcoz it provides un-necessary information to the current
python program along required information.
Examples: from hyd import *
from bang import *
=>WITH THIS APPROACH , AFTER IMPORTING A PERTICULAR MODULE, THE VARIABLE NAMES, FUNCTION NAMES AND
CLASS NAMES CAN BE ACCESSED DIRECTLY WITHOUT USING MODULE NAME
Syntax:- Variable Name (OR) aliasname of variable name
Function Name (OR) aliasname of function name
Class Name (OR) aliasname of Class name
#[Link]---file name and treated as module name #[Link]---file name and treated as module name
( [Link]) ( [Link])
stateinfo="Karnataka" stateinfo="Telangana"
capinfo="BANGLORE" capinfo="HYD"
def hello(s): def hello(s):
print("{}, Good Evening from hello()--bang module".format(s)) print("{}, Good Morning from hello()--hyd module ".format(s))
def show(): def show():
print("i am from show()-bang module") print("i am from show()-hyd module")
#[Link]
from hyd import stateinfo,capinfo,hello,show #[Link]
print("------------------------------------") from hyd import stateinfo as sf1,capinfo as cf1,hello as
print("state name=",stateinfo) h1,show as s1
print("capital name=",capinfo) from bang import stateinfo as sf2,capinfo as cf2,hello as h2 ,show as s2
print("------------------------------------") print("------------------------------------")
hello("Rossum") print("state name=",sf1)
show() print("capital name=",cf1)
print("------------------------------------")
#[Link] print("state name=",sf2)
from bang import * print("capital name=",cf2)
from hyd import * print("------------------------------------")
print("------------------------------------") h1("Rossum")
print("state name=",stateinfo) s1()
print("capital name=",capinfo) print("------------------------------------")
print("------------------------------------") h2("Ritche")
hello("Rossum") s2()
show()
#[Link] #[Link]
import formula as f import formula as f , mathsinfo as k
import mathsinfo as hyd [Link]()
[Link]() print("val of pi=",[Link])
print("val of pi=",[Link]) print("val of e=",k.E)
print("val of e=",hyd.E)
Q) Write a python program which will implement the following menu driven application.
Arithmetic Operation
1. Addition 4. Division
2. Subtraction 5. Modules
3. Multiplication 6. Exponentiation
7. Exit
def expoop():
a=float(input("Enter Value for Base:"))
b=float(input("Enter Value for power:"))
print("\texp({},{})={}".format(a,b,a**b))
==========================================
realoding a modules in Python
==========================================
=>To reaload a module in python , we use a pre-defined function called reload(), which is present in imp module
and it was deprecated in favour of importlib module.
=>Syntax:- [Link](module name)
(OR)
[Link](module name) -----recommended
=>Purpose / Situation:
=>reaload() reloads a previously imported module. if we have edited the module source file
by using an external editor and we want to use the changed values
(OR)
To get the new version of previously loaded module then we use reload().
#main program
#[Link]
import shares
import time
import importlib
def disp(d):
print("-"*50)
print("\tShare Name\tValue")
print("-"*50)
for sn,sv in [Link]():
print("\t{}\t\t:{}".format(sn,sv))
else:
print("-"*50)
#main program
d=[Link]() #previously imported module
disp(d)
[Link](15)
[Link](shares) # relodaing previously imported module
d=[Link]() # obtaining changed / new values of previously imported module
disp(d)
Print by VIKASH Page no -92
#[Link]---file name and treated as module name
shinfo={"IT":1010,"Pharm":1170,"automobiles":100,"textiles":180}
#[Link] #[Link]
import time,importlib import shares,time,importlib
import sharesinfo def disp(d):
print([Link]) print("-"*40)
[Link](15) print("\tShare Name\tShare Value")
[Link](sharesinfo) print("-"*40)
print([Link]) for sn,sv in [Link]():
[Link](15) print("\t{}\t\t\t{}".format(sn,sv))
[Link](sharesinfo) else:
print([Link]) print("-"*40)
#main program
d1=[Link]()
disp(d1)
[Link](15)
[Link](shares) # reloading the module name
d1=[Link]()
disp(d1)
======================================
Packages in Python
======================================
=>We know that FUNCTIONS concept is used for Performing Certain operation and provides Code Re-usability
within the program but not able to provide Code Re-usability across the programs.
=>We know that MODULES concept is used for re-using the code across the programs provided the modules
must present in same Folder but not able to get Code Re-usability across Folders / Drives / Environments /
Networks..etc
=>The PACKAGES concept is used for getting the Code Re-usability across Folders / Drives / Environments /
Networks..etc through modules where modules contains Variables, Functions and Classes.
Def. of Packages:
=>A Package is a collection of Modules.
Creating a package:
Step-1: Create a folder
Step-2: Define / place an an empty python file on the name of __init__.py in folder to make the folder
name as Package Name.
Step-3: Define / place a module (s) in the package(Folder Name)
1) By using [Link]():
Syntax:-
[Link]("Absolute path of Package Name")
Examples:
#[Link]
import sys
[Link]("E:\KVR-PYTHON-7AM\PACKAGES\BANK")
from formula import simpleint
simpleint()
Print by VIKASH Page no -93
(OR)
#[Link]
import sys
[Link]("E:
[Link]("E:\KVR-PYTHON-7AM/PACKAGES/BANK")
from formula import simpleint
simpleint()
====================================
Introduction to Exception Handling
and
Types of Errors
====================================
=>The purpose of Exception Handling is that "To develop Robust (Strong) Applications"
=>In Real Time , To develop any project, we need to choose a language and by using it we can develop, compile
and execute various Programs. During this process, we get 3 types of Errors. They are
a) Compile Time Errors
b) Logical Errors
c) Runtime Errors
b) Logical Errors:
=>Logical Errors are those, which are occuring at Execution Time
=>Logical Errors are occuring due to wrong representation of Logic.
=>Logical Errors are always gives Wrong / Inconsista
Inconsistant Result.
=>These errors solved by Programmers at development level.
c) Runtime Errors
=>Runtime Errors are those, which are occuring at Execution Time
=>Runtime Errors are occuring due to "Wrong Inputs / Invalid Inputs entered by Application Users / En
End Users".
Runtime Errors must be handled by Programmer during Development time with Forecasting Knowledge.
=>Runtime
Print by VIKASH Page no -94
============================================
Points to be remembered in Exception Handling
============================================
1) When the application / end user enters wrong input / Invalid invalid then we get
Runtime Errors
2) Runtime Errors by default gives Technical Errors Messages. These messages are understanble
Programmers but not by End Users. Industry always recommends convert Technical Error Message into User
Friendly Error Messages by Using Exception Handling
5) Definition of exception handling:- The Process of converting Technical Error Messages into User Friendly
Error Messages is called Exceptional Handling.
6) When the exception occurs in Python Program, Three steps takes place internally. They are
a) PVM Terminates the Program execution abnormally.
b) PVM comes out of Program flow without executing rest of the statements
c) PVM by default generates Technical Error Messages.
7) To do the steps (a),(b) and (c) , PVM internally creates an object of appropriate exception classes.
8) Hence Every Invalid Input gives exception and every exception is treated as object and it is created w.r.t
appropriate exception classes.
(Invalid Input--->exception--->object---->appropriate exception class )
====================================
Types of exceptions in Python
====================================
=>In Python, we have two types of exceptions. They are
1. Pre-defined / Built-in exceptions.
2. Programmer / User / Custom-defined Exceptions.
Example -1 :-
#This Program demonstartes how to cal division of two numbers
#by accepting two integer values from KBD
#[Link]
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # ----- exception generated statement
b=int(s2) # ----- exception generated statement
c=a/b # -------exception generated statement
print("Val of a={}".format(a))
print("Val of b={}".format(b))
print("Div={}".format(c))
Example -2 :-
#This Program demonstartes how to cal division of two numbers
#by accepting two integer values from KBD
#[Link]
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1)
b=int(s2)
c=a/b
except ZeroDivisionError:
Print by VIKASH Page no -96
print("\nDON'T
nDON'T ENTER ZERO FOR DEN...")
except ValueError:
print("\nDON'T
nDON'T ENTER strs/symbols/alpha
strs/symbols/alpha-numeric
numeric values:")
else:
print("\nResult---
---else block")
print("-"*50)
print("Val of a={}".format(a))
print("Val of b={}".format(b))
print("Div={}".format(c))
print("-"*50)
finally:
print("\ni
ni am from finally block")
raise keyword
=>raise keyword is used for hitting / raising / generating the exception w when
hen certain condition is satisfied.
=>PVM uses raise keyword for hitting Pre Pre-defined
defined exceptions automatically. where as programmer makes the
PVM to use raise keyword to hit programmer
programmer-defined
defined exceptions when certain condition is satisfied.
Syntax:-
if(test cond):
raise exception-class-name
Syntax:
def function
function-name(list of formal params if any):
if(test cond):
raise exception-class-name
-----------------------------------------------
-----------------------------
-----------------------------------------------
========================================
Explanation for the keywords used
in
Syntax for handling the exceptions:
========================================
1) try block:
=>It
It is the block, in which we write block of statements generating exceptions. In otherwords what are all
the statements are generating exceptions then those statements must be written in try block and
hence try block is called exception monitoring block.
=>When the exception occurs in try block then PVM comes out of try block and executes appropriate
except block.
Print by VIKASH Page no -97
=>When the pvm executes appropriate except block, PVM never goes to try block for executing rest of
the statements in try block.
=>Every try block must be immediately followed by except block(Otherwise we get error).
=>Every try block must contain atleast one except block and it is recommended to write multiple except
blocks for generating multiple user-friendly error messages.
2) except block:
=>It is the block, in which write Block of statements generating User-Friendly Error Messages. In
otherwords, except block suppresses the technical error messages and generates user-friendly error
Messages and except block is called exception processing block.
Note:- Handling the Exception=try block+except block.
=>except block will execute when there is an exception occurs in try block.
=>Even though we write multiple except blocks , at any point of time only appropriate except block will
execute depends on type of exception occurs in try block.
=>The place of writing except block is after try block and before else block (if we write else block).
3) else block:
=>It is the block , In which we write block of statements generating Result of the program
=>else block will execute when there is no exception exception occurs in try block
=>Writing else block is optional
=>we write else block after except block and before finally block ( if we write finally block)
4) finally block:
=>It is the block, in which we write block of statements relinquish (release / close / give-up/ clean-up) the
resources ( Files/ Database) which are obtained in try block.
=>finally block will execute compulsorily irrespective of type of exception occurs or not
=>Writing finally block is optional.
=>finally block to be written after else block
Examples: Examples:
# [Link]----------(3) #[Link]--------(3)
(1) (2) (1) (2)
class PinError(Exception):pass class LoginError(BaseException):pass
Example: result=division(a,b)
#Phase-III: Handling the exceptions by using except KvrDivisionError:
try and except kwds. print("\nDon't Enter Zero for Den...")
#[Link] ---main program except ValueError:
from divop import division print("\nDon't enter strs / alpha-numerics/ special symbols:")
from kvr import KvrDivisionError else:
try: print("\nDiv({},{})={}".format(a,b,result))
a=int(input("Enter Value of a:")) finally:
b=int(input("Enter Value of b:")) print("\nI am from finally Block")
Print by VIKASH Page no -101
======================================
Types of Applications
======================================
=>The purpose of Files in any programming Language is that "To Store the data Permanently (Data Persistency )".
=>In the context of Files, we can develop two types of Applications / Programs.. They are
a) Non-Persistant
Persistant Applications
b) Persistant Applications
=>In Non-Persistant
Persistant Application Development, we read / accept the from input data from KBD, Stores in main
memory (temp storage) , process the inputs and displays its result on the console.
Examples: All previous program are comes under non non-persistan
persistant applications.
=>In Persistant Application Development, we read / accept the from input data from KBD, Stores in main
memory (temp storage) , process the inputs and stores the result Permanently.
=>In Industry , we have two types of approaches to st
store
ore the data permanently. They are
a) By Using Files
b) By using Database softwares
======================================
Operations on Files
======================================
=>On Files, we can perform two types of Operations. They are
a) Write Operation.
b) Read Operation.
a) Write Operation.
=>This operation is used for transfering Temporary data from Main Memory into the file of secondary memory .
Steps:
1) Choose the file name.
2) Open the file name in write mode
3) Perform Cycle of Write Operations
Operations.
=>During Write Operation, we get exceptio
exceptions like FileExistError,IOError..etc.
b) Read Operation.
=>This operation is used for transfering the Data of files from Secondary Memory into object of Main Memory .
Steps:
1) Choose the file name.
2) Open the File Name in Read Mode
3) Perform Cycle of Read Operations
=>During Read Operation, we get exceptions like FileNotFoundError,EOFError..etc
1) Text Files:
=>A Text File always contains the data in the form Alphabets, Digits and Special Symbols.
=>In Python Programming, text files are denoted by a letter 't'.
=>By default,When we deal with Files, File is considered as text file.
Examples: .txt .doc .py .java .cpp ...etc
2) Binary Files:
=>A Binary File always contains the data in the form Binary Format.
=>In Python Programming, Binary files are denoted by a letter 'b'.
Examples: .jpeg, .jpg, .gif, audio, video .pdf...etc
.exe. .png.....etc
=====================================
File Opening Modes
=====================================
=>File Opening Modes are used for opening the file in certain file Mode.
=>In otherwords , File Opening Modes makes us to understand, in which mode the file is opening.
=>In Python Programming we have 7 file opening modes. They are
1) r :
=>This mode is used for opening the File in read mode.
=>When we open the file in 'r' mode and if the file does not exist in Secondary Memory then we get
FileNotFoundError.
=>The default file mode is 'r' .
2) w :
=>This mode is used for Opening the File always in write mode newly.
=>If we open new file in 'w' mode then it open in write mode and data written to file from the begining.
=>If we open the existing file in 'w' mode then it open in write mode, existing data is replaced with new
data.(Overlapping)
3) a :
=>This mode is used for Opening the File always in write mode.
=>If we open new file in 'a' mode then it open in write mode and data written to file from the begining.
=>If we open the existing file in 'a' mode then it open in write mode and new data adding at end of
existing data( know as appending)
4) r+ :
=>This mode is used for opening the file in read mode.
=>When we open the file in 'r' mode then we can perform First Read Operation and latter we can perform
Write Operation(But not reverse order).
=>When we open the file in 'r+' mode and if the file does not exist in Secondary Memory then we get
FileNotFoundError.
5) w+ :
=>This mode is used for Opening the File always in write mode newly.
=>if we open new file in 'w' mode then it open in write mode and data written to file from the begining and
latter we can perform read operation.
=>If we open the existing file in 'w+' mode then it opens in write mode, existing data is replaced with new
data.(Overlapping)
=>When we write the data on file with this mode and if we have insufficient memory in Seconadry
Memory then we get IOError.
Print by VIKASH Page no -104
6) a+ :
=>This mode is used for Opening the File always in write mode.
=>If we open NEW FILE in 'a' mode then it open in write mode and data written to file from the begining
and later we can read the data.
=>If we open the EXISTING FILE in 'a' mode then it open in write mode and new data adding at end of
existing data( know as appending) and later we can perform read operation.
7) x :
=>This Mode is used for opening the file Exclusively in Write Mode only once.
=>If we open the existing file in x mode then we get FileExistError.
===================================
Opening the Files in Python
===================================
=>To do any operation on files, we have open the file.
=>To open the file , we have two syntaxes. They are
1) By using open()
2) By using " with open() as ".
1) By using open():
Syntax:- VarName=open("File Name", "File Mode")
=>here "VarName" repersent a pointer to the file and it called "File Pointer " and it is an object of type <class, _io.TextIOWrapper>
=>open() is pre-defined function, which is used for opening the file in specified File Mode.
=>"File Name" represents Name of File
=>File Mode represents r,w,a,r+,w+,a+ and x.
=>Once we open the files by using open(), we need to close the files explicitly by using close() . In otherwords
open() approach is unable to provide auto-closable property.
#This program demonstrates for obtaining the #This program demonstrates for obtaining the
information about files. information about files.
#[Link] #[Link]
try: try:
fp=open("[Link]","r") fp=open("[Link]","r+")
except FileNotFoundError: except FileNotFoundError:
print("File does not exists:") print("File does not exists:")
else: else:
print("id of fp=",id(fp)) print("File Opened in read mode successfully")
print("File Opened in read mode successfully") print("-"*40)
print("-"*40) print("Mode used={}".format([Link]))
print("Mode used={}".format([Link])) print("Is readable={}".format([Link]()))
print("Is readable={}".format([Link]())) print("Is writable={}".format([Link]()))
print("Is writable={}".format([Link]())) print("Line--13: is file
print("Line--14: is file closed={}".format([Link]))
closed={}".format([Link])) print("-"*40)
print("-"*40) finally:
finally: print("\nI am from finally block")
print("\nI am from finally block") [Link]()
[Link]() print("Line--18: is file
print("Line--19: is file closed={}".format([Link]))
closed={}".format([Link]))
#This program demonstrates for obtaining the #This program demonstrates for obtaining the
information about files. information about files.
#[Link] #[Link]
fp=open("[Link]","a+") try:
print("File Opened in append mode successfully") fp=open("[Link]","x")
print("-"*40) print("File Opened in x mode successfully")
print("Mode used={}".format([Link])) except FileExistError:
print("Is readable={}".format([Link]())) print("File alerady exist:")
print("Is writable={}".format([Link]())) else:
print("Line--13: is file closed={}".format([Link])) print("-"*40)
print("-"*40) print("Mode used={}".format([Link]))
print("Is readable={}".format([Link]()))
print("Is writable={}".format([Link]()))
print("Line--13: is file
closed={}".format([Link]))
print("-"*40)
finally:
print("\nI am from finally block")
[Link]()
print("Line--18: is file
closed={}".format([Link]))
=========================================
Writing the data to the files
=========================================
=>Once we open the file, it is necessary to perform the operations on the files.
=>On Files, we can perform two types of Operation and they can write and read.
=>To write the data to the files, we have two pre-defined functions which are
present in the object of TextIOWrapper. They are
1) write()
2) writelines()
1) write():
Syntax:- [Link](data)
=>here "filepointer" is an object, it always points to the file.
=>" write() " is a pre-defined function, which is used to write the data to the file always in the form of str.
=>"data" represents always any type of value but it should be always in the form of str.
Example:
#[Link]
with open("[Link]","a") as fp:
[Link]("Dennis Ritche\n")
[Link]("FNO:130,,Fort Side\n")
[Link]("Bell Labds \n")
[Link]("USA\n")
print("\nData Written to the File:")
2) writelines():
Syntax:- [Link]( Iterable object )
=>This function is used for writing the data int the Iterbable object and data of iterable object must be of type str.
=>If any iterable object contains other than str then we must convert entire iterable object into str type by using str()
Examples:
#[Link] #[Link]
d={10:"Mango",20:"Apple",30:"Kiwi"} tpl=(20,"Babani",88.88,"JNTU")
with open("[Link]","a") as fp: with open("[Link]","a") as fp:
[Link](str(d)+"\n") [Link](str(tpl)+"\n")
print("Data written to the file") print("Data written to the file")
#[Link] #[Link]
sti={40,"Sree Devi",88.48,"HCU"} lst=[10,"Rutuja",88.88,"OU"]
with open("[Link]","a") as fp: with open("[Link]","a") as fp:
[Link](str(sti)+"\n") [Link](str(lst)+"\n")
print("Data written to the file") print("Data written to the file")
1) read():
=>This function is used for reading entire data of file in the form of str.
Syntax: varname=[Link]()
Examples:
#This program reads entire data of the file by using read()
#[Link]
try:
fname=input("Enter File Name to read its content:")
with open(fname,"r") as fp:
filedata=[Link]()
print("Complete Content of the File:")
print("-------------------------------------")
print(filedata)
print("-------------------------------------")
except FileNotFoundError:
print("File does not exists")
2) read([Link] chars):
=>This Functions is used for reading specified number of characters.
=>Here "[Link] chars" represents How many Characters u want to erad.
Syntax:- varname=[Link](no. of chars)
Examples:
#This progfram demostarates how to read filedata=[Link](20)
specified number of chars. print("File Data=",filedata)
#[Link]------read(no. of chars) print("-"*40)
try: print("Now Index of fp=",[Link]()) #
with open("[Link]","r") as fp: filedata=[Link]()
print("Initial Index of fp=",[Link]()) # 0 print("File Data=",filedata)
filedata=[Link](6) print("-"*40)
print("File Data=",filedata) print("Now Index of fp=",[Link]()) #159 -last index
print("-"*40) print("-"*40)
print("Now Index of fp=",[Link]()) # 6 [Link](0) # here 0 says initial index of file
filedata=[Link](16) print("Line-23: Initial Index of fp=",[Link]()) # 0
print("File Data=",filedata) filedata=[Link]()
print("-"*40) print("File Data=",filedata)
print("Now Index of fp=",[Link]()) #23 except FileNotFoundError:
print("File does not exists:")
3) readline():
=>This Function is used for reading one line at a time in the form of str.
Syntax:- varname=[Link]()
Examples:
#This progfram demostarates how to read line by line from the file .
#[Link]------readline()
try: filedata=[Link]()
fp=open("[Link]","r") print(filedata,end="")
filedata=[Link]() filedata=[Link]()
print(filedata,end="") print(filedata,end="")
filedata=[Link]() except FileNotFoundError:
print(filedata,end="") print("File does not exists:")
Print by VIKASH Page no -108
4) readlines():
=>This function is used for reading all the lines of the file in the form of list type.
Syntax:- varname=[Link]()
Examples:
#This program demostarates how to reading all the flies from the file.
#[Link]------readlines()
try:
fp=open("[Link]","r")
filedata=[Link]()
for line in filedata:
print(line,end=" ")
print()
except FileNotFoundError:
print("File does not exists:")
#This Program will copy the content of one #Program for reading the data from key board
file(Source File) into another file(destination File) dynamically and write it to the file
#[Link] #[Link]
try: import sys
sfile=input("Enter Source File:") with open ("[Link]","a") as fp:
with open(sfile,"r") as rp: print("Enter The data for writing into the
dfile=input("Enter Destination File:") file(press 'stop' to terminate):")
with open(dfile,"a") as wp: print("-"*40)
filedata=[Link]() while(True):
[Link](filedata) filedata=input()
print("\nFile Copied --verify" if(filedata!="stop"):
except FileNotFoundError: [Link](filedata+"\n")
print("File Does Not exists") else:
print("-"*40)
[Link]()
#Program for finding number of lines, number of #Program for finding number of lines, number of
words and no. of chars from a given file. words and no. of chars from a given file.
#[Link] #[Link]
try: try:
nl,nw,nc=0,0,0 nl,nw,nc=0,0,0
fname=input("Enter File Name :") fname=input("Enter File Name :")
with open(fname) as fp: with open(fname) as fp:
for line in fp: fileinfo=[Link]() # here fileinfo is an obj. if list
print(line,end="") for line in fileinfo:
nl=nl+1 print(line,end="")
nw=nw+len([Link]()) nl=nl+1
nc=nc+len(line) nw=nw+len([Link]())
else: nc=nc+len(line)
print() else:
print("-"*40) print()
print("No. of lines in file={}".format(nl)) print("-"*40)
print("No. of Words={}".format(nw)) print("No. of lines in file={}".format(nl))
print("No. of Characters={}".format(nc)) print("No. of Words={}".format(nw))
print("-"*40) print("No. of Characters={}".format(nc))
except FileNotFoundError: print("-"*40)
print("File does not exists:") except FileNotFoundError:
print("File does not exists:")
a) tell():
=>This Function is used for obtaining the Position / Index of the file pointer.
Syntax:- Index=file [Link]()
b) seek():
=>This Function is used for re-positioning the file pointer withing file content by passing Index value.
Syntax:- [Link](index)
Example:-
#This progfram demostarates how to read specified number of chars.
#[Link]------read(no. of chars)
See [Link]
=>Definition of Pickling:
=>The process of writing / saving the entire object content into the file of Secondary Memory with single
write operation is called Pickling.
=>The Pickling always participates in write operation.
=>While we are implementing Pickling Concept, we must ensure that the file must be binary.
=>Definition of Un-Pickling:
=>The Process of Reading entire record content from the file of secondary memory into the object of
memory with single read operation is called Un-Pickling.
=>Un-Pickling participates in read operation.
=>While we are implementing Un-Pickling Concept, we must ensure that the file must be binary.
b) Creating a Folder:
=>To create a folder, we use mkdir() of os module.
=>This Function can create one folder at a time and unable create Folders hierarchy(Root Folder\sub-folder...etc ) and we get
OSError
=>If folder Name already exist and if try to create then we get FileExistsError
Syntax:- [Link]("FolderName")
Examples:
#Creating a Folder
#[Link]
import os
try:
[Link]("C:\apple\banana\kiwi")
print("Folder Created --Verify")
except FileExistsError:
print("Folder already created:")
except OSError:
print("Folders Hierarchy Can't be created")
Index :-
==========================================
Python Database Communication(PDBC)
==========================================
=====================
Limitations of Files
=====================
=>We achieved the data persistency by using files. But the concept of files having the following Limitations.
1) File concept of any language are un-secured bcoz files concept unable to provide security in the form
of User Name and password.
2) The data of Files does not contain column names. so that it is very difficult to process the [Link]
Otherwords, Processing and Selecting the data from files is very difficult.
3) The files concept is unable to store large volume of data.
4) The architecture of files may differ from One OS to another OS.
=>To over come these limitations of files , we use another concept called Data base software.
=======================================
Python DataBase Communication(PDBC)
=======================================
=>The Python DataBase Communication(PDBC) concept makes us to understand, How a python Program can
communicate with any RDBMS DataBase Software efficiently.
=>Examples of RDBMS DataBase Software:
a) Oracle b) MYSQL
c) Mongo DB d) Postgrey SQL
e) DB2 f) SQL Server...etc
=>To develop any Python database communication Applications, we must use the following steps.
1) import cx_Oracle
2) Every Python must establish the connection from Oracle databse
3) Create an object of Cursor.
4) Design the query(It is a request / Question to the data base) and place it
in an object of Cursor and execute.
5) Python Program Process the result of the Query.
6) Python Program closes the connection.
1) import cx_Oracle:
=>If a PYTHON program want to communicate with Oracle Database then we must import a pre-defined module
called "cx_Oracle".
Example:- import cx_Oracle
Examples:- kvrcon=cx_Oracle.connect("scott/tiger@localhost/orcl")
(OR)
kvrcon=cx_Oracle.connect("scott/tiger@[Link]/orcl")
print("Python Program obtained Connection from Oracle DB")
Note:- If we enter wrong Connection URL then we get an exception called "cx_Oracle.DatabaseError".
Examples:-
#This Program demonstartes how to get the connection from Oracle DB
#[Link]
import cx_Oracle # Step-1
try:
kvrcon=cx_Oracle.connect("scott/tiger@localhost/orcl") # step-2
print("\nPython Program obtained Connection from Oracle DB")
print("Type of kvrcon=",type(kvrcon)) # Type of kvrcon= <class 'cx_Oracle.Connection'>
except cx_Oracle.DatabaseError as db:
print("Connection Problem:",db)
#This
This Program demonstrates how to create an object of Cursor
#[Link]
import cx_Oracle # step-1
conobj=cx_Oracle.connect("scott/tiger@localhost/orcl") # step-2
print("\nPython
nPython Program obtains connection from Oracle DB:")
print("Type of conobj=",type(conobj))
curobj=[Link]() # step-3
print("\nPython
nPython Program Creates an object of Cursor class")
print("Type of curobj=",type(curobj))
curobj=",type(curobj))# Type of curobj= <class 'cx_Oracle.Cursor'>
4) Design the query(It is a request / Question to the data base) and place it in an object of Cursor and execute.
=>A Query is a request / Question to the database from Python Program to perform Certain database operation.
=>After designing the Query and we must execute by using execute(), which is present in
<class,"cx_Oracle.Cursor">
Syntax:- [Link](query)
=>here the query can be either DDL
DDL, DML and DRL.
=>cq="create table student(stno number(2) primary key, name varchar2(15) not null, marks
number(5,2) not null )"
In Python => [Link](cq)
=> print("Table created in Database
Database--verify")
Example:-
#This
This Program demonstrates how to create a table in Oracle DB
#[Link]
import cx_Oracle # step-1 1
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") #step-2
cur=[Link]() #step
step-3
#step-4---
cq="create table employee(eno number(2) primary key, name varchar2(10) not null, sal number(8,2))"
[Link](cq)
print("Table Created in Oracle database
database--plz verify")
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
EXAMPLE
#This program demonstartes how to alter (add) #This program demonstartes how to alter (modify)
by adding a new column to the table the column size of table
#[Link] #[Link]
import cx_Oracle import cx_Oracle
try: try:
con=cx_Oracle.connect("scott/tiger@[Link]/orcl") con=cx_Oracle.connect("scott/tiger@[Link]/orcl")
cur=[Link]() cur=[Link]()
[Link]("alter table employee add(cname amq="alter table employee modify(eno
varchar2(10) not null) ") number(3),name varchar2(15))"
print("Employee Table altered by new col name--verify") [Link](amq)
except cx_Oracle.DatabaseError as db: print("Employee Table altered--verify")
print("Problem in Database:",db) except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
c) drop:-
=>This command is used for removing table completely
Syntax(Oracle):
SQL> drop table <table-name>;
Examples: - SQL> drop table student;
a) insert:-
=>This command is used for inserting a record in a table
Syntax(Oracle):
SQL>insert into <table-name> values(val1 for col1,val2 for col2.....val-n for col-n)
Examples:- SQL> insert into employee values(10,'RS',3.4)"
Print by VIKASH Page no -120
#This program inserts an employee record in employee table--with static data
#[Link]
import cx_Oracle #step-1
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") #step-2
cur=[Link]() #step-3
#design the query and execute --step-4
iq="insert into employee values(40,'Sonali',4.8)" # DML Query
[Link](iq)
[Link]()
print("Employee Record Inserted Successfully..")
except cx_Oracle.DatabaseError as db:
print("Prob in inserting the data..",db)
#main program
empinsert()
b) delete:-
=>This command is used for deleting a record from a table.
=>Syntax(Oracle):-
Syntax1:- delete from <table-name> ;
#main program
empdelete()
c) update:-
=>This command is used for updating the records of a table.
=>Syntax1: update <table-name>
set col1=val1,col2=val2.....col-n=val-n;
=>After executing the select query from python program , all the records are available in cursor object.
To get the records from cursor object then we use 3 pre-defined Functions. They are
a) fetchone()
b) fetchmany(no. of records)
c) fetchall()
a) fetchone() is used for obtaining only one record from cursor object where ever cusror object is pointing.
b) fetchmany(no. of records) is used for obtaining sepecified number of records from cursor object.
Here, i) if we specify the "[Link] records" as -ve value then we never get any output.
ii) if we specify the "[Link] records" as +ve(more number of records than available) then we get all
the records.
iii) if we specify the "[Link] records" as 0 then we get all the records.
c) fetchall() is used obtaining all records from cursor object in the form list of tuples.
EXAMPLE
#Program for reading all the records from employee table fetchone()
#[Link] record=[Link]()
import cx_Oracle if(record!=None):
def readrecords(): for val in record:
try: print("\t{}".format(val),end="")
con=cx_Oracle.connect("scott/tiger@localhost/orcl") print()
cur=[Link]() else:
sq="select * from employee" print("-"*40)
[Link](sq) break
print("-"*40) except cx_Oracle.DatabaseError as db:
print("\tEmployee Records") print("Problem in reading the records:",db)
print("-"*40) #main program
while (True): readrecords()
Detailed Explanation:
=======================
1) import [Link]
=>If a PYTHON program want to communicate with MySql Database then we must import a pre-defined module
called "[Link]".
Example:- import [Link]
Examples:-
kvrcon=[Link](host="Localhost",user="root",passwd="root")
print("Python Program obtained Connection from MYSQL DB")
(OR)
kvrcon=[Link](host="[Link]",user="root",passwd="root")
print("Python Program obtained Connection from MYSQL DB")
Note:- If we enter wrong Connection URL then we get an exception called "[Link]".
#Program for getting connection from MySQL DB. #Program for Demonstrates how to create a data base
#[Link] #[Link]
import [Link] import [Link]
try: try:
kvrcon=[Link](host="[Link]", kvrcon=[Link](host="[Link]",
user="root",passwd="root" ) user="root",passwd="root" )
print("Python Program got connection from MySQL") kvrcur=[Link]()
except [Link] as db: dbc="create database batch7am"
print("Problem in MySQL: ",db) [Link](dbc) # (OR)
[Link]("create database batch7am")
print("Database created--verify")
except [Link] as db:
print("Problem in MySQL: ",db)
#Program for Demonstrates to insert employee record into the emplyee table--static records
#[Link]
import [Link]
def insertrecord():
try:
con=[Link](host="[Link]",user="root",passwd="root" ,database="batch7am")
cur=[Link]()
#design the query and execute
[Link]("insert into employee values(30,'Gosling',2.5)")
[Link]()
print("{} employee record inserted --verify".format([Link]))
except [Link] as db:
print("Problem in MySQL: ",db)
#main program
insertrecord()
#main program
empinsert()
#this program accept employee number and remove the record from employee table of mySql
#[Link]
import [Link] ,sys
def empdelete():
while(True):
try:
con=[Link](host="localhost",user="root",passwd="root" , database="batch7am")
cur=[Link]()
#accept employee number
empno=int(input("Enter Employee Number:"))
#design the query and execute
[Link]("delete from employee where eno=%d" %empno)
[Link]()
if([Link]>0): # here rowcount is an pre-defined attribute in cursor object
print("{} Record Ddeleted--Verify".format([Link]))
else:
print("Record Does not exists:")
except [Link] as db:
print("Problem in deleting the record:",db)
except ValueError:
print("\nDon't enter strs / symbols/ alpha-numerics for emp number")
ch=input("Do u want to delete another record(yes/no):")
if(ch=="no"):
print("\nThanks for using program:")
[Link]()
#main program
empdelete()
#Program for reading all the records from employee table with column names---fetchall()
#[Link]
import [Link]
def readrecords():
try:
con=[Link](host="localhost",user="root",passwd="root" , database="batch7am")
cur=[Link]()
sq="select * from employee"
[Link](sq)
print("-"*40)
print("\tEmployee Records")
print("-"*40)
#display the column names
colnames=[str(var[0]) for var in [Link]]
for colname in colnames:
print("\t{}".format(colname),end="")
print()
print("-"*40)
#display the records
records=[Link]()
for record in records:
for val in record:
print("\t{}".format(val),end="")
print()
print("-"*40)
except [Link] as db:
print("Problem in reading the records:",db)
#main program
readrecords()
=>Python Programming satisfies Both Procedure Oriended (Functional Programming ) and Object Oriended
Principles.
"Every Thing is an object in Python"
(or)
Benifits of Object Oriented Principles
=>The objects allows us to store un-limited amount of data and achives Platform Indepenent.
=>The large volume of data can be transfered between two remote machines all at once and we can achieve
Effective Communication.
=>The Confidential Data can be transfered between two remote machines in the form of object where it can be
available in the form of cipher text / encrypted format . so that we can achieve the security.
=>The Data always stored / available in the form of objects and on the objects data we can perform the
operations by using Functions.
===================================================
Object Oriented Principles / Features / Concetps
===================================================
=>To Say a programming Language is Object Oriented then it has to satisfy the
following object oriented principles.
1. classes
2. objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing ( we already discussed )
=>The above Object Oriented Principles are common in all Object Oriented Programming Languages But
their syntaxes differs from one Object Oriented Programming Language to another Object Oriented
Programming Language.
======================================
1. classes
======================================
Index:-
Purpose of classes in OOPs
Definition of class
Syntax for definition of class
Type of data members
a)instance data members
b)class level data members
type of methods
a)instance method
b)class level methods
c)static methods
programming examples
Definition of Class:
----------------------------
=>A class is a collection of Data Members( Instance Data Members and Class Level Data Members) and
Methods ( Instance Methods, Class L Level Methods and Static Methods ).
=>Once we define a class, there is no memory space created for Data Members and Methods(bcoz Class
definition is treated as specification ) but whose memory space is created when we create an Object w.r.t
Class Name.(Most Important )
=>Hence Every Program in Python must starts with Classes Concept and data can be stored in the form of
objects and it can be created w.r.t Class Name.
==========================
Syntax for defining a class
==========================
=======
=>We know that every Program of Python by using OOPs must starts with the concept of classes.
=>The Syntax for defining a class is shown bellow.
class <clsname>:
Class Level Data Members
def instancemethodname(self,list of formal params if any ):
-------------------------------
Block of stattaments--specific Operations
Specify Instance Data members
--------------------------------
@classmethod
def classlevelmethodname(cls,list of formal params if any ):
--------------------------------
Block of statements--class level operations
Specify Class Level Data Members
--------------------------------
@staticmethod
def staticmethodname(list of formal params if any):
--------------------------------
Block of statements--Utility Operations
=>Class
Class Level Data Members MUST SPECIFIED in two places. They are
a) through Inside class definition
b) though Inside of Class Level Methods
#This Program stores stno,sname, marks and course with OOPS by using methods
#[Link]
class Student: #This Program stores stno,sname, marks and
crs="PYTHON" # class Level data member course with OOPS by using methods
def getstudentdetails(self):#here self is called #[Link]
Impilcit object for current class object class Student:
print("-"*60) crs="PYTHON" # class Level data member
[Link]=int(input("Enter Student Number:")) def getstudentdetails(self):#here self is called
[Link]=input("Enter Student Name:") Impilcit object for current class object
[Link]=float(input("Enter Student Marks:")) print("-"*60)
print("-"*60) [Link]=int(input("Enter Student Number:"))
def dispstudentdetails(self): [Link]=input("Enter Student Name:")
print("-"*60) [Link]=float(input("Enter Student Marks:"))
print("Student Number:{}".format([Link])) print("-"*60)
print("Student Name:{}".format([Link])) def dispstudentdetails(self):
print("Student marks:{}".format([Link])) print("-"*60)
print("Student Course:{}".format([Link])) print("Student Number:{}".format([Link]))
print("-"*60) print("Student Name:{}".format([Link]))
#main program print("Student marks:{}".format([Link]))
s1=Student() # create an object print("Student Course:{}".format([Link]))
print("Enter First Student Object Information") print("-"*60)
[Link]() #main program
s2=Student() # create an object s1=Student() # create an object
print("Enter Second Student Object Information") print("Enter First Student Object Information")
[Link]() [Link]()
print("First Student Object Information") print("First Student Object Information")
[Link]() [Link]()
print("Second Student Object Information") s2=Student() # create an object
[Link]() print("Enter Second Student Object Information")
[Link]()
print("Second Student Object Information")
[Link]()
#This Program stores stno,sname, marks and course with OOPS by using methods
#[Link]
class Student:
crs="PYTHON" # class Level data member
def getstudentdetails(self):#here self is called Impilcit object for current class object
print("-"*60)
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
print("-"*60)
[Link]() # calling another instance method
Print by VIKASH Page no -133
def dispstudentdetails(self):
print("-"*60)
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student marks:{}".format([Link]))
print("Student Course:{}".format([Link]))
print("-"*60)
#main program
s1=Student() # create an object
print("Enter First Student Object Information")
[Link]()
s2=Student() # create an object
print("Enter Second Student Object Information")
[Link]()
=========================================
Types of Methods in class
=========================================
=>In a class of python, we can have 3 types of methods. They are
1. Instance Methods
2. Class Level Methods
3. Static Methods
1. Instance Methods :-
=>Instance Methods are used for performing specific Operations on objects and Intance methods are also
called Object Level Methods.
=>Programatically, Instance Methods always takes "self" as First Formal Parameter for storing address(id) /
reference of object.
Syntax:-
def instancemethodname(self , list of formal params if any ):
-------------------------------
Block of stattaments--specific Operations
Specify Instance Data members
--------------------------------
=>In Python Programming, all Instance Methods must be accessed w.r.t Object Name (or) self.
[Link] Method Name()
(OR)
[Link] Method Name()
EXAMPLE :-
#This program demonstrates the specification of Class Level Data Members
#[Link]
class Employee:
@classmethod
def getcompname(cls): # Class Level
Method [Link]="InfoSys"
@classmethod
def getcompaddr(cls): # Class Level Method
[Link]="HYD"
def getempdet(self): # Instance Method
print("-"*40)
[Link]=int(input("Enter Employee Number:"))
[Link]=input("Enter Employee Name:")
print("-"*40)
def dispempdet(self): # Instance Method
print("-"*40)
print("Employee Number:{}".format([Link]))
print("Employee Name:{}".format([Link]))
print("Emp Company Name:{}".format([Link]))
print("Emp Company address:{}".format([Link]))
print("-"*40)
#main program
[Link]() # calling class level method
[Link]() # calling class level method
eo1=Employee()
eo2=Employee()
[Link]() # calling Instance Method
[Link]() # calling Instance Method
[Link]() # calling Instance Method
[Link]() # calling Instance Method
#This program demonstrates the specification of Class [Link]() # calling Class Level Method
Level Data Members print("-"*40)
#[Link] print("Employee Number:{}".format([Link]))
class Employee: print("Employee Name:{}".format([Link]))
@classmethod print("Employee Company Name:{}".format
def getcompname(cls): # Class Level Method ([Link]))
[Link]="InfoSys" print("Employee Company address:{}".format
#A Class Level Method can call another Class Level ([Link]))
Method but not Instance Method print("-"*40)
@classmethod
def getcompaddr(cls): # Class Level Method #main program
[Link]="HYDERABAD" [Link]() # calling class level method
def getempdet(self): # Instance Method eo1=Employee()
print("-"*40) eo2=Employee()
[Link]=int(input("Enter Employee Number:")) [Link]() # calling Instance Method
[Link]=input("Enter Employee Name:") [Link]() # calling Instance Method
print("-"*40) [Link]() # calling Instance Method
def dispempdet(self): # Instance Method [Link]() # calling Instance Method
Print by VIKASH Page no -136
#This program demonstrates the specification of Class #This program demonstrates the specification of
Level Data Members Class Level Data Members
#[Link] #[Link]
class Employee: class Employee:
@classmethod @classmethod
def getcompname(cls): # Class Level Method def getcompname(cls): # Class Level Method
[Link]="InfoSys" [Link]="InfoSys"
#A Class Level Method can call another Class #A Class Level Method can call another
Level Method but not Instance Method Class Level Method but not Instance Method
@classmethod
@classmethod
def getcompaddr(cls): # Class Level Method
def getcompaddr(cls): # Class Level Method
[Link]="HYDERABAD"
[Link]="HYDERABAD" def getempdet(self): # Instance Method
def getempdet(self): # Instance Method print("-"*40)
print("-"*40) [Link]=int(input("Enter Employee Number:"))
[Link]=int(input("Enter Employee Number:")) [Link]=input("Enter Employee Name:")
[Link]=input("Enter Employee Name:") print("-"*40)
print("-"*40) def dispempdet(self): # Instance Method
def dispempdet(self): # Instance Method [Link]() # calling class
[Link]() # calling Class Level Method level method
print("-"*40) [Link]() # calling Class Level
print("Employee Number:{}".format([Link])) Method
print("Employee Name:{}".format([Link])) print("-"*40)
print("Employee Company Name:{}".format print("Employee Number:{}".format([Link]))
([Link])) print("Employee Name:{}".format([Link]))
print("Employee Company address:{}".format print("Employee Company Name:{}".format
([Link])) ([Link]))
print("-"*40) print("Employee Company address:{}".format
([Link]))
#main program print("-"*40)
[Link]() # calling class level method
eo1=Employee() #main program
eo2=Employee() eo1=Employee()
[Link]() # calling Instance Method eo2=Employee()
[Link]() # calling Instance Method [Link]() # calling Instance Method
[Link]() # calling Instance Method [Link]() # calling Instance Method
[Link]() # calling Instance Method
[Link]() # calling Instance Method
[Link]() # calling Instance Method
======================================
Objects in Python
======================================
Importance of Object :-
=>When we define a class , Memory space is not created for Data Members and Methods But whose Memory Space is created
when e create an object.
=>When we define a class and class name can be treated as Data Type but we can't store the data. To Store the data , we must
create an object w.r.t Class Name.
=>To do any data processing, we must create an object.
=>To create an object, there must exist a class definition otherwise we get error.
Definition of an object t :-
=>Instance of a class is called object.( Instance is nothing but allocating sufficient memory space for Data Members and Methods )
Syntax for creating an object:
objectname=ClassName()
#This Program reads two numerical values and arithmetic operator from KBD and find operation result.
#[Link]
class Values:
def getvalues(self):
self.a=float(input("Enter First Value:"))
self.b=float(input("Enter Second Value:"))
[Link]=input("Enter any arithmetic operator:")
class Calculator:
@staticmethod
def compute(obj):
try:
[Link]()
match([Link]):
case "+":print("sum({},{})={}".format(obj.a,obj.b,obj.a+obj.b))
case "-":print("sub({},{})={}".format(obj.a,obj.b,obj.a-obj.b))
case "*":print("mul({},{})={}".format(obj.a,obj.b,obj.a*obj.b))
case "/":print("div({},{})={}".format(obj.a,obj.b,obj.a/obj.b))
case "//":print("floor div({},{})={}".format(obj.a,obj.b,obj.a//obj.b))
case "%":print("mod({},{})={}".format(obj.a,obj.b,obj.a%obj.b))
case "**":print("pow({},{})={}".format(obj.a,obj.b,obj.a**obj.b))
case _: print("\n {} is not a Arithmetic Operator:".format([Link]))
except ValueError:
print("\tDon't Enter strs/alpha-numeric/special symbols for numerics")
#main program
vo=Values()
[Link](vo)
#main program
vo=Values()
[Link]()
[Link](vo)
Data Encapsulation :-
=>The Process of Hiding the confidential Information / Data / Methods fropm external Programmers / end
users is called Data Encapsulation
=>The Purpose of Encapsulation concept is that "To Hide Confidential Information / Features of Class (Data
Members and Methods ) ".
=>Data Encapsulation can be applied in three levels. They are
a) At Data Members Level
b) At Methods Level
c) At Constructor Level
=>To implement Data Encapsulation in python programming, The Data Members , Methods and
Constructors must be preceded with double under score ( _ _ )
Example1: Example2:
#[Link]----file name and treated as module name #[Link]----file name and treated as module
class Account: name
def getaccountdet(self): class Account1:
self.__acno=34567 def __getaccountdet(self): #here __getaccountdet()
[Link]="Rossum" is made is encapsulated
self.__bal=34.56 [Link]=34567
[Link]="SBI" [Link]="Rossum"
self.__pin=1234 [Link]=34.56
[Link]=4444444 [Link]="SBI"
#here acno,bal and pin are encapsulated [Link]=1234
[Link]=4444444
=>The Process of retrieving / extracting Essential Details without considering Hidden Details is called Data Abstraction.
Example1:
#[Link]---This Program access only cname,bname and Example2:
pincode only #[Link]--here we can't access method itself. so that
from account import Account we cant access Instance Data Members.
ao=Account() from account1 import Account1
[Link]() ao=Account1()
#print("Account Number={}".format([Link])) Not # [Link]()---can't access
Possible to access # print("Account Number={}".format([Link]))
print("Account Holder Name={}".format([Link])) # print("Account Holder Name={}".format([Link]))
#print("Account Bal={}".format([Link])) Not Possible to # print("Account Bal={}".format([Link]))
access # print("Account Branch Name={}".format([Link]))
print("Account Branch Name={}".format([Link])) # print("Account PIN={}".format([Link]))
#print("Account PIN={}".format([Link])) Not Possible to # print("Account Branch Pin Code={}".format([Link]))
access
print("Account Branch Pin Code={}".format([Link]))
Program A
Write a python program which can access multiple students details such as student number, student
name and marks and save those details in the file by using classes and object with pickling concept
Program B
Write a python program which will read all the student record of a file by using classes and object
with un-pickling.
Program A Program B
#[Link] #[Link]
from student import Student import pickle,sys
import pickle,sys try:
with open("[Link]","ab") as fp: with open("[Link]","rb") as fp:
while(True): print("-"*50)
try: print("\tS t u d e n t D e t a i l s")
so=Student() print("-"*50)
[Link]() while(True):
[Link](so,fp) try:
print("\nStudent Object data saved successfully in File:") obj=[Link](fp)# here obj is an
ch=input("Do u want to insert another student data:") object of type [Link]
if(ch=="no"): [Link]()
print("Thx for using program") except EOFError:
[Link]() print("-"*50)
except ValueError: [Link]()
print("Don't enter strs / symbols/ alpha- except FileNotFoundError:
numerics for Student Number and Marks:") print("File does not exists:")
=========================================
Constructors in Python
=========================================
=>The purpose of Constructors in Python is that "To Initlize the Object".
=>Initlizing the object is nothing but placing our own values without leaving the object empty.
Definition of Constructor :-
=>A constructor is one of the Special Method which is automatically / implicitly called by PVM during object
creation and it always Initlizes the object (Placing our own values).
NOTE:- In a class of python, we can't define both default and parametreised constructor bcoz PVM can
remember only latest constructor but not able to remember all types of constructor . To solve this issue, In a
class of Python, we can define One Constructor with default parameter mechanism.
#[Link] #[Link]
class Student: class Student:
def setstudentvalues(self): # Ordinary method- def __init__(self): #Constructor
-need to call explicitly print("I am from constructor")
[Link]=10 [Link]=10
[Link]="Rossum" [Link]="Rossum"
[Link]=44.44 [Link]=66.66
#main program
#main program so=Student() # object creation--i want place my
so=Student() # object creation--i want place my own values own values--Initlize the object
print("content of so defore setting values=", so.__dict__) print("content of so =", so.__dict__) # {..... }
# { } [Link]() # here we are calling explicitly
one function
print("content of so after setting values=", so.__dict__) # {----- }
#[Link]
class Account: #main program
def __init__(self): ao1=Account() # object creation
[Link]=int(input("Enter Account Number:")) print("content of ao1=", ao1.__dict__)
[Link]=input("Enter Customer Name:") print("--------------------------------------------")
[Link]=float(input("Enter Balanace:")) ao2=Account() # object creation
[Link]=input("Enter Branch Name:") print("content of ao2=", ao2.__dict__)
==============================================
Differences between Methods and Constructors
==============================================
=>Constructors are always used Initlizing the object. Where as Methods are used for Performing the
operations on the object.
=>The name of the constructor is always __init__(self, params list if any). where as name of the method
can be any valid variable name.
=>The Constructors are not recommended to return the values (They are suppose to initlize) where
methods are recommended to return the values ( They are doing operation).
=>Constructors are calling automatically when an object is created where as methods are calling explicitly.
Note:- In Python, Both Constructors and Methods can be Inherited and they can be Overridden.
Type of Destructors
=>By Default, Garbage Collector calls Destructor at end execution of Python Program.
=>Programatically , We can make the Garbage Collector to call Destructor FORCEFULLY by
nullifying the object ( Example: obj=None )
#[Link] #[Link]
class Employee: import time
def __init__(self,eno,ename): class Employee:
print("i am from Contructor:") def __init__(self,eno,ename):
[Link]=eno print("i am from Contructor:")
[Link]=ename [Link]=eno
print("\t{}\t{}".format([Link],[Link])) [Link]=ename
print("\t{}\t{}".format([Link],[Link]))
#main program def __del__(self): # Programmer-defined Destructor
print("Program Execution Started..") print("\nGC is calling Destructor Function")
eo1=Employee(10,"RS")
eo2=Employee(20,"DR") #main program
print("\nProgram Execution Completed..") print("Program Execution Started..")
#Since program execution completed, GC collects eo1=Employee(10,"RS")
Objects memory spaces and hand over to OS. So eo2=Employee(20,"DR")
internally to do this process, GC calls its Destructor eo3=Employee(30,"RR")
Program for de-allocating / destroying the memory print("\nProgram Execution Completed..")
space of objects. [Link](5)
#[Link] #[Link]
import time import time
class Employee: class Employee:
def __init__(self,eno,ename): def __init__(self,eno,ename):
print("\ni am from Contructor:") print("\ni am from Contructor:")
[Link]=eno [Link]=eno
[Link]=ename [Link]=ename
print("\t{}\t{}".format([Link],[Link])) print("\t{}\t{}".format([Link],[Link]))
def __del__(self):# Programmer-defined Destructor def __del__(self): # Programmer-defined Destructor
print("\nGC is calling Destructor Function") print("\nGC is calling Destructor Function")
#main program
#main program print("Program Execution Started..")
print("Program Execution Started..")
eo1=Employee(10,"RS")
eo1=Employee(10,"RS")
eo3=eo2=eo1 # Deep Copy
eo3=eo2=eo1 # Deep Copy
eo4=Employee(20,"SS")
print("No Longer Interested to maintain object eo1")
[Link](8)
print("\nProgram Execution Completed..") del(eo1) # here GC will not call __del__(self) , bcoz that
[Link](5) # Here by default , GC calls corresponding memory pointed by eo2 and eo3
__del__(self) one time only even though there exists print("No Longer Interested to maintain object eo2")
[Link](8)
two objects and both the objects points to same
eo2=None # here GC will not call __del__(self) , bcoz
memory space
that corresponding memory pointed by eo3
print("No Longer Interested to maintain object eo3")
[Link](8)
eo3=None # here GC will call __del__(self) , bcoz that
corresponding memory is not pointed by any objects
print("\nProgram Execution Completed..")
[Link](5) # Here by default , GC calls __del__(self)
one time only even though there exists two objects and
both the objects points to same memory space
Print by VIKASH Page no -147
#[Link] eo1=Employee(10,"RS")
import time,gc [Link]()
class Employee: print("No Longer Interested to maintain object eo1")
def __init__(self,eno,ename): [Link](8)
print("\ni am from Contructor:") del(eo1) # Here Forcefully , GC calls __del__(self)
[Link]=eno eo2=Employee(20,"DR")
[Link]=ename print("No Longer Interested to maintain object eo2")
print("\t{}\t{}".format([Link],[Link])) [Link](8)
def __del__(self): # Programmer-defined Destructor del eo2 # Here Forcefully , GC calls __del__(self)
print("\nGC is calling Destructor Function") eo3=Employee(30,"RR")
#main program print("\nProgram Execution Completed..")
print("Program Execution Started.. and status of [Link](5)
gc={}".format([Link]())) # Here by default , GC calls __del__(self) one times
#[Link]
import gc,time
print("Is GC Running={}".format([Link]()))
print("\ni am a python Programmer")
[Link](5)
[Link]()
print("Is GC Running after disable={}".format([Link]()))
print("From Igate MNC Global")
print("In Hyd")
=>Definition of Inheritance :-
=>The process of obtaining the Data Members , Methods and Constructors (Features) from One class into
another class is called Inheritance.
=>The class which is giving the Data Memebrs , Methods and Constructors (Features) is called "Base / Super / Parent Class."
=>The class which is Taking the Data Memebrs , Methods and Constructors (Features) is called "Derived / Sub / Child Class."
=>The Inheritance Priciple always Provides Logical Memory Management. This Memory management says
that Neither we write Physical Source Code Nor takes Physical Memory Space.
===================================================
Inheriting the features of Base Class into Derived Class
===================================================
=>The features of Base Class are nothing but Data Members , Methods and Constructors.
=>To Inherit the features of Base Class into Derived Class, we use the following Syntax:
Syntax:
class <class-name-1>: # Base Class
---------------------
---------------------
class <class-name-2>: # Base Class
---------------------
---------------------
class <class-name-n>: # Base Class
---------------------
---------------------
class <class-name-n+1>( Class-Name-1,Class-Name-2...Class-Name-n):
---------------------
---------------------
Explanation:
=>Here <class-name-1>, <class-name-2>....<class-name-n> are called Base Classes.
=><class-name-n+1> is called Derived Class.
=>When we develop any Inheritance Based Application, It is always recommended to create an object of
Bottom most Derived Class bcoz It contains all the features of Intermediate Base Classes and Top Most
Base Class.
=>For Every class in python, There exists an implicit pre-defined super class called "object" and It provdes
Garbage Collector Program"
#[Link] #[Link]
class Company: class Company:
def setcompdet(self): def setcompdet(self):
[Link]=input("Enter the company name:") [Link]=input("Enter the company name:")
[Link]=input("Enter the company location:") [Link]=input("Enter the company location:")
def dispcompdet(self): def dispcompdet(self):
print("-"*50) print("-"*50)
print("Company Name:{}".format([Link])) print("Company Name:{}".format([Link]))
print("Company Location:{}".format([Link])) print("Company Location:{}".format([Link]))
print("-"*50) print("-"*50)
class Employee(Company): class Employee(Company):
def setempdet(self): def setempdet(self):
[Link]=int(input("Enter Employee Number:")) [Link]=int(input("Enter Employee Number:"))
[Link]=input("Enter Employee Name:") [Link]=input("Enter Employee Name:")
[Link]=float(input("Enter Employee Salary:")) [Link]=float(input("Enter Employee Salary:"))
def dispempdet(self): [Link]() # calling Base class method
print("-"*50) def dispempdet(self):
print("Employee Number:{}".format([Link])) print("-"*50)
print("Employee Name:{}".format([Link])) print("Employee Number:{}".format([Link]))
print("Employee Salary:{}".format([Link])) print("Employee Name:{}".format([Link]))
print("-"*50) print("Employee Salary:{}".format([Link]))
print("-"*50)
#main program [Link]() # calling Base class method
eo=Employee() # create an object of Bottom most derived
class Employee #main program
[Link]() eo=Employee() # create an object of Bottom most
[Link]() derived class Employee
[Link]() [Link]()
[Link]() [Link]()
Example :-
#This Program is purely using Inheritance Principle #This Program is purely using Inheritance
#[Link] Principle with Method Overriding
class Circle: #[Link]
def draw1(self): class Circle:
print("Drawing Circle:") def draw(self): # Original Method
class Rect(Circle): print("Drawing Circle")
def draw2(self): class Rect(Circle):
print("Drawing Rect:") def draw(self): # Overridden Method
print("Drawing Rectangle")
#main program super(). draw()
ro=Rect()
ro.draw2() #main program
ro.draw1() ro=Rect()
[Link]()
#This Program is purely using Inheritance #Program cal area of different Figures such as
Principle with Method Overriding circle,rect and square by using method overriding
#[Link] #[Link]
class Circle: class Circle:
def draw(self): # Original Method def area(self): # Original Method--one Form
print("Drawing Circle") self.r=float(input("Enter Radious:"))
#super().draw()---AttributeError: 'super' object [Link]=3.14*self.r**2
has no attribute 'draw' print("Area of Circle={}".format([Link]))
class Rect(Circle): class Square(Circle):
def draw(self): # Overridden Method def area(self): # Overridden Method
print("Drawing Rectangle") self.s=float(input("Enter Side:"))
super().draw() # calling Base class method [Link]=self.s**2
name from derived class print("Area of Square={}".format([Link]))
class Square(Rect): print("-"*50)
def draw(self): # Overridden Method super().area()
print("Drawing Square") class Rect(Square):
super().draw() # calling Intermedaite Base def area(self): # Overridden Method
class method name from derived class self.l,self.b=float(input("Enter Length:")),
float(input("Enter Breadth:"))
#main program [Link]=self.l*self.b
so=Square() print("Area of Rect={}".format([Link]))
[Link]() print("-"*50)
super().area()
#main program
ro=Rect()
[Link]()
Def. of Polymorphism :-
=>The process of representing "One Form in Multiple Forms" is called Polymorphism.
=>In
In the definition of Polymorphism, One Form represents Original Method of Base Class and Multiple
Forms represents Overridden Methods of Derived Class.
=>To Implement Polymorphism Principle, we must use Method Overriding.
=========================
=================================================
========================
Number approaches to call Base class methods
from Derived Class Methods
=================================================
=>In Python Programming, we have two approaches to calle base class methods from derived class methods.
They are :-
a) By Using super()
b) By using ClassName
=>With super() we are able to call single base class method from derived class method but unable to call
multiple base class methods from derived class methods.
=>To Over this problem, we must use Class Name concept.
See MethodOverridingEx1-4
#Program cal area of different Figures such as circle,rect and square by using method overriding for
implementing polymorphism
#[Link] class Rect(Square):
class Circle: def area(self,l,b): # Overridden Method
def area(self, r): # Original Method--One Form [Link]=l*b
[Link]=3.14*r**2 print("Area of Rect={}".format([Link]))
print("Area of Circle={}".format([Link])) print("-"*50)
class Square(Circle): super().area(float(input("Enter Side:")))
def area(self, s): # Overridden Method
[Link]=s**2 #main program
print("Area of Square={}".format([Link])) l,b=float(input("Enter Length:")), float(input("Enter
print("-"*50) Breadth:"))
super().area(float(input("Enter Radious:"))) ro=Rect()
[Link](l,b)
b) By using ClassName:
=>By using Class Name concept we can call Multiple Base Class Orginal Methods (or) Original
Constructors from derived class Overridden Method / Constructor.
#This Program demonstrates Hybrid Inheritane by using method overriding for implementing
polymorphism
#[Link]
class C1:
def x(self): class C6(C4):
print("x()--C1") def x(self):
class C2(C1): print("x()--C6")
def x(self): class C7(C5,C6):
print("x()--C2") def x(self):
class C3(C1): print("x()--C7")
def x(self): C5.x(self)
print("x()--C3") C6.x(self)
class C4(C2,C3): C4.x(self)
def x(self): C3.x(self)
print("x()--C4") C2.x(self)
class C5(C4): C1.x(self)
def x(self):
print("x()--C5") #main program
O7=C7()
O7.x()