0% found this document useful (0 votes)
4 views156 pages

Python Programming: Features & Applications

The document outlines the real-time applications and features of Python programming, detailing its capabilities in various domains such as web development, AI, and data analysis. It also covers the history, versions, and data types of Python, emphasizing its simplicity, portability, and extensive library support. Additionally, it provides rules for using variables and identifiers in Python programming.

Uploaded by

pallipattumanoj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views156 pages

Python Programming: Features & Applications

The document outlines the real-time applications and features of Python programming, detailing its capabilities in various domains such as web development, AI, and data analysis. It also covers the history, versions, and data types of Python, emphasizing its simplicity, portability, and extensive library support. Additionally, it provides rules for using variables and identifiers in Python programming.

Uploaded by

pallipattumanoj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Print by VIKASH Page - 1

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

Print by VIKASH Page - 3


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

1) Web Applications Development.---->


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

===========================================
Getting started with Python
===========================================
=>History of Python
=>Versions of Python
=>Downloading Process of Python
==================================================================================
=>History of Python
=>Python Programming language foundation stone laid in the year 1980.
=>Python Programming language 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) "

Print by VIKASH Page - 4


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

1) Functional Programming from C 3) Scripting Programming from PERL


2) Object Oriented Programming from CPP 4) Modular Programming from Modulo3

Features of Python Programming


==========================================
=>Features of a language are nothing but services / Facilities provided language
developers and they are used by language programmers for developing real time
applications.
=>Python Programming Provides 11 features.
1. Simple
2. Freeware and Open Source
3. Platform Independent
4) Dynamically Typed
5) Portable
6) Interpreted
7) High Level
8) Robust(Strong)
9) Extensible
10) Embedded
11) Extensive Third Party Library / API support
( Numpy,Pandas, Matplotlib,scikit, scipy...etc)
12) Both Procedure oriented(Core Python) and Object Oriented (Adv
Python)

==========================
1. Simple
==========================
=>Python is one of the SIMPLE programming, bcoz of 3 Important Tech Factors.

a) Python Programming Provides "Rich Set of APIs". So that Python


Programmer can Re-Use the pre-defined Libraries / API for solving real time
requirements.

Definition of API ( Application Programming Interface):


=>An API is a collection Modules.
=>A Module is a collection of Functions, Variables and Classes
Examples:- math, cmath, random,calendar,
re, cx_Oracle, mysql-connector,
threading, gc....etc

b) Python Programming Provides Inbuilt "Garbage Collection " Facility. So that It


collects un-used memory space and improves performance of Python Based
Applications.

Def of Garbage Collector:


Garbage Collector is one of the In-built Program in Python Software, which is
running behind of every Regular Python Program and whose purpose is that to
Collect Un-Unsed / Un-referenced Memory space and Improves the Performance of
Python Based Applications.

c) Python Programming Provides User Friendly Syntaxes. So that Python Programmer


can develop Error-Free Program in a limited span of time.

Print by VIKASH Page - 5


========================================
2. Freeware and Open Source
========================================
=>Freeware:
-------------------
=>If any software is available Freely Downlodable then it called FreeWare.
Examples:- PYTHON and JAVA

=>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 :

1) JPYTHON (or) JYTHON---->Used To Run Java Based Applications.


2) Iron Python--------------------->Used To run C#.net Based Application
3) Micro Python----------->Used To develop Micro Controller Applications
4)Ruby Python------------>Used to run RUBY ON RAIL based Applications
5) Anakonda Python--->Used deal with BIGDATA / Haddop Based Appls........etc

======================================
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

1. Static Typed Programming Languages:


=>In This Programming Languages, Data type of values must specified by programmer
explicitly. Otherwise we get Errors
Examples:
C,CPP, JAVA, .NET...etc
Examples: int a=10;
int b=20;
int c=a+b;

Print by VIKASH Page - 6


2. Dynamically Typed Programming Languages:
=>In This Programming Languages, Data type of the values need not specify by the
programmer and more over data type of the value is implicitly decided by Python
Execution Environment.
=>In Python Programming , all values are stored in the form of Objects and to
cerate objects we need classes.
Examples: PYTHON
Examples:
>>> a=100
>>> b=200
>>> c=a+b
>>> print(a,b,c)
print(a,b,c)-------------------------100
100 200 300
>>> print(type(a),
print(type(a),type(b),type(c))-------<class
<class 'int'> <class
'int'> <class 'int'>
>>> print(a,type(a))
print(a,type(a))--------------100
100 <class 'int'>
>>> print(b,type(b))
print(b,type(b))------------200
200 <class 'int'>
>>> print(c,type(c))
print(c,type(c))-------------300
300 <class 'int'>
Python program execution environment

==========================================
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.

Print by VIKASH Page - 7


====================================
7) High Level
====================================
=>Even though we represent the data in the form Binary , Octal and Hexa Decimal
Format and at output stage we are getting the output in high level Understandable
Format.
=>Understanding python statements is Simple.

==========================================
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.

Print by VIKASH Page - 8


=============================================
Variables (or) Identifiers in Python
=============================================
=>All types of Literals are stored in Main memory in the created memory space. To
process the values stored in main memory, as programmer, we must give distinct
names to the cerated memory space. So that distinct names makes us to identify
the values and hence they are called Identifiers.
=>Identifier values are changing / Varying during the program execution ands hence
Identifier are called Variables.
=>In Python all types of Literals / Values are stored in Main Memory in the form
Variables / Identifiers and all types of Variables / Identifiers are called
objects.

=>Def. of Variable:-
=> A Variable is an Identifier whose values are changing during execution of
the program.

Rules for Using Variables in Python


==============================================
=>To use the Variables in Python Programming, we must follow the rules. They are
1) The Variable Name is a combination of Alphabets (Lower and upper
Case), Digits and Special Symbol Under Score ( _ )
2) The Variable Name must starts with Either with an alphabet or Under
Score ( _ )
Examples:
12abc=10-----invalid
-abc=20-------invalid
abc=123-----valid
a123=34----valid
_abc=34---valid
_sal_=2.3--valid
_123=2.3---valid
_=23----valid

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

6) All the Variable Names are recommended to Take User-Friendly Names.

Examples:-
>>> sal_of_an_employee=1.2--Valid--Not Recommended
>>> emp_sal=1.2--Valid--Recommended

---------------------------------------------------------------------------------

Data Types in Python


==========================================
=>The purpose of Data types in Python is that to allocate sufficient memory space
for input values and performs Various Operations on the data
=>In Python Programming, we have 14 Data Types. They are:-

I) Fundamental Catagery Data Types


i) int
ii) float
iii) bool
iv) complex
II) Sequence Catagery Data Types
i) str
ii) bytes
iii)bytearray
iv) range
III) List Catagery Data Types (Collection Data Types)
i) list
ii) tuple
IV) Set Catagery Data Types (Collection Data Types)
i) set
ii) frozenset
V) Dict Catagery Data Types (Collection Data Types)
i) dict
VI) None Catagery Data Type:
i) None
ii)

================================================
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

Print by VIKASH Page - 10


i) int
========
=>'int' is one of the pre-defined class and it treated as Fundamental Data Type.
=>The purpose of 'int' data type is that to store Integer / Integral / whole
Numbers (Data without decimal Places)
Example: Student Numbers, Adhar Card Numbers, Emp Numbers..etc

=>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

1) Decimal Number System :


=>It is one of default Number System
=>The digits present in this number System are
0,1,2,3,4,5,6,7,8,9----toal 10 digits
=>The base for Decimal Number System is 10

2) Binary Number System:


=>The Digits present in this number system are 0,1--total digits- 2
=>The base for Binary Number System is 2
=>To store Binary Number System data in python Programming, Binary Number
System data muststarts or preceded with 0b or 0B.

=>Syntax: varname=0b Binary Data


(OR)
varname=0B Binary Data
=>All types of Binary Values are implicitly converted into Decimal Number
System Value .
=>Examples:-
>>> a=0b100
>>> print(a,type(a))--------------------4 <class 'int'>
>>> b=0B1010
>>> print(b,type(b))-------------- 10 <class 'int'>
>>> c=0B1111
>>> print(c,type(c))-------------- 15 <class 'int'>
>>> d=0b101010101111000111
>>> print(d,type(d))--------- 175047 <class 'int'>
>>> a=0b10102-----SyntaxError: invalid digit '2' in binary literal

Print by VIKASH Page - 11


3) Octal Number System:
=>The
The Digits present in this number system are 0,1,2,3,4,5,6,7
0,1,2,3,4,5,6,7--total
digits- 8
=>The base for Octal Number System is 8
=>To store Octal Number System data in python Programming, Octal Number
System data must starts or preceded with 0o or 0O.
=>Syntax:
Syntax: varname=0o Octal Data
(OR)
varname=0O Octal Data
=>All types of Octal Values are implicitly converted into Decimal Number
System Value .
=>Examples:-
>>> a=0o14
>>> print(a, type(a))
type(a))--------------------------12
12 <class
<clas 'int'>
>>> b=0o34
>>> print(b, type(b))
type(b))------------------- 28 <class 'int'>
>>> c=0o23458----------------------
----------------------SyntaxError:
SyntaxError: invalid digit '8' in
octal literal

4) Hexa Decimal Number System:


=>The Digits present in this number system are
0,1,2,3,4,5,6,7,8,9,A(10)
0,1,2,3,4,5,6,7,8,9,A(10),B(11),C(12),D(13),E(14),F(15)
,F(15)----total digits-16
=>The base for Hexa Decimall Number System is 16
=>To store Hexa Decimal Number System data in python Programming, Hexa
Decimal Number System data must starts or preceded with 0x or 0X.

=>Syntax: varname=0x Hexa Decimal Data


(OR)
varname=0X Hexa Decimal Data
=>All types of Hexa Decimal Values are implicitly converted into Decimal
Number System Value
Value.
Examples:
>>> a=0XAC
>>> print(a,type(a))
print(a,type(a))---------------172
172 <class 'int'>
>>> a=0xAB
>>> print(a,type(a))
print(a,type(a))------------171
171 <class 'int'>
>>> c=0xBEE
>>> print(c,type(c))
print(c,type(c))-------------3054
3054 <class 'int'>
>>> a=0X9A
>>> print(a,type(a))
print(a,type(a))---------154 <class 'int'>
>>> a=0xACC
>>> print(a,type(a))
type(a))------------2764
2764 <class 'int'>
>>> a=0xACER----------
----------SyntaxError:
SyntaxError: invalid hexadecimal literal
Print by VIKASH Page - 12
================================================

Base Conversion Functions


================================================
=>The purpose of Base Conversion Functions is that to Convert One Base value into
another base value.
=>In Python , we have 3 Base Conversion Functions. They are
a) bin()
b) oct()
c) hex()

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)

Print by VIKASH Page - 13


Examples:
>>> a=12
>>> print(a,type(a))----------------12 <class 'int'>
>>> b=oct(12)
>>> print(b,type(b))--------------0o14 <class 'str'>
>>> a=0b1111
>>> print(a,type(a))-------------15 <class 'int'>
>>> b=oct(a)
>>> print(b,type(b))------------0o17 <class 'str'>
>>> a=0XACC
>>> print(a,type(a))-----------2764 <class 'int'>
>>> b=oct(a)
>>> print(b,type(b))------------0o5314 <class 'str'>

c) hex():
---------------
=>This Function is used for converting any type of base value into hexa Decimal
number system value.

Syntax:- varname=hex(decimal / binary / octal 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

a) Single Line String Data


----------------------------------
=>Single Line String Data must be enclosed within Single or Double Quotes or
tripple single / double Quotes.
Print by VIKASH Page - 16
Examples:-
>>> a="Python Programming"
>>> print(a,type(a))----------Python Programming <class 'str'>
>>> b='A'
>>> print(b,type(b))--------------A <class 'str'>
>>> c="A"
>>> print(c,type(c))------------A <class 'str'>
>>> d='Java Programming'
>>> print(d,type(d))-----------Java Programming <class 'str'>
>>> crs1="Python Programming"
>>> print(crs1,type(crs1))------------Python Programming <class 'str'>
>>> crs2='Python Programming'
>>> print(crs2,type(crs2))-----------Python Programming <class 'str'>
>>> crs3="1234567"
>>> print(crs3,type(crs3))-------------1234567 <class 'str'>
>>> crs3="Python3.10"
>>> print(crs3,type(crs3))------------Python3.10 <class 'str'>
>>> x="$%#@&abc&*()"
>>> print(x,type(x))------------$%#@&abc&*() <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'>

=>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.

b) Multi Line String Data


=>Multi Line String Data must be enclosed within tripple single (or tripple double
Quotes.
Examples:
>>> addr1="""Guido van Rossum
... HNO:3-4 Hill side
... CWI ,Python Soft Fund.
... Nether Lands--34567"""

>>> 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

Syntax2:- strobj [ Begin : ]


=>Here Begin Index is Specified and End Index is not specified. Here pvm takes end
index value as len(strobj)-1
=>This syntax takes the characters from Specified Begin Index to len(strobj)-1 bcoz
end index value is automatuically taken as len(strobj)-1.
Print by VIKASH Page - 18
Examples:
>>> s="PYTHON"
>>> print(s[2:])----------------THON
>>> print(s[0:])----------------PYTHON
>>> print(s[4:])---------------ON
>>> print(s[5:])--------------N
>>> print(s[-1:])------------N
>>> print(s[-6:])-----------PYTHON
>>> print(s[-3:])-----------HON
>>> print(s[-4:])-----------THON
>>> print(s[-2:])------------ON

=>Syntax3:- strobj [ :End ]


=>Here Begin Index is not Specified and End Index is specified. Here pvm takes
Begin index value as Intial Index.
=>This syntax takes the characters from Intial Index to End Index-1 bcoz Begin
index value is automatuically taken as Intial Index.
Examples:
>>> s="PYTHON"
>>> print(s)------------------PYTHON
>>> print(s[:4])------------PYTH
>>> print(s[:5])------------PYTHO
>>> print(s[:6])------------PYTHON
>>> print(s[:-3])---------PYT
>>> print(s[:-1])----------PYTHO
>>> print(s[:-5])-----------P
>>> print(s[:-4])---------PY

=>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

=>Syntax5:- strobj [ Begin : End : Step ]


Rule-1: Here the Index values of Begin, End and Step can be Possitive and
Negative .
Rule-2: If the value of STEP is POSITIVE then PVM Takes the characters from
Begin Index to End Index-1 by Step Interval values in Forward
Direction provided Begin Index<End Index
Rule-3: If the value of STEP is NEGATIVE then PVM Takes the characters from
Begin Index to End Index+1 by Step Interval values in Backward
Direction provided Begin Index>End Index
Rule-4: In Forward Direction if the end Index is 0 then we never get any output.
Rule-5: In Back Direction if the end Index is -1 then we never get any output.

Print by VIKASH Page - 19


Examples:----------RULE-2 >>> s="PYTHON"------------------RULE-3
--------------------- >>> print(s)-------------PYTHON
>>> s="PYTHON" >>> print(s[6:0:-2])---------NHY
>>> print(s)-----------PYTHON >>> print(s[::-2])-----------NHY
>>> print(s[0:6:2])----PTO >>> print(s[5:0:-3])--------NT
>>> print(s[0:6:3])----PH >>> print(s[5:0:-3])---------NT
>>> print(s[-6:-1:2])--PTO >>> print(s[5:0:-2])----------NHY
>>> print(s[-6::2])----PTO >>> print(s[::-4])---------NY
>>> print(s[0:4:3])----PH >>> print(s[-1:-6:-2])----------NHY
>>> print(s[::3])------PH >>> print(s[-1:-6:-1])-----------NOHTY
>>> print(s[::4])------PO >>> print(s[::-1])------------NOHTYP
>>> print(s[::1])------PYTHON >>> print(s[::1])-----------PYTHON
>>> print(s[::])-------PYTHON >>> print(s[::])-------------PYTHON
>>> print(s[::-1])-----------NOHTYP
>>> s="LIRIL"
>>> print(s[::])-----------LIRIL
>>> print(s[::-1])----------LIRIL
>>> "JAVA"[::-1]-----------'AVAJ'
>>> "MADAM"[::-1]=="MADAM"[::1]-----True
>>> "JAVA"[::-1]=="JAVA"[::1]------False

>>> 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

Syntax:- varname=bytes( list / tuple / set /frozenset/ bytearray )


Examples:
>>> l1=[10,20,30,255]
>>> b=bytes(l1) >>> print(b[0])-------------10
>>> type(b) >>> print(b[1])----------20
<class 'bytes'> >>> print(b[2])------------30
>>> for x in b: >>> print(b[3])----------255
... print(x) >>> print(b[4])--------IndexError: index
... out of range
10 >>> for x in b[0:3]:
20 ... print(x)
30 ...
255 10
>>> print(id(b)------2225802328416 20
>>> b[0]=100-----TypeError: 30
'bytes' object does not support
item assignment

Print by VIKASH Page - 20


3. bytearray
=>'bytearray' is one of the pre-defiend data type and treated as Sequence data
type.
=>The purpose of bytearray data type is that "To organize sequece of Possitive
Numerical Integer values ranges from (0,256). It Stores the values from 0 to
255(256-1) only ".
=>To store the values in the object of bytearray data type, we don't have any
Symbolic Notation but we can convert Other type of values into bytearray type by
using bytearray()
=>The object of bytearray belongs to mutable bcoz bytearray allows us to perform
updations.
=>On the object of bytearray , we can perform Both Indexing and Slicing Operations.
=>An object of bytearray maintains Insertion Order.

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'>

>>> for v in b: >>> b[0]=100 # updations


... print(v) >>> for v in b:
... ... print(v)
10 ...
20 100
30 20
40 30
255 40
255

>>> print(id(b),type(b))----1723585740720 <class 'bytearray'>


>>> print(b[-1])------255
>>> print(b[2])-----30
>>> print(b[::-1])----bytearray(b'\xff(\x1e\x14d')
>>> for v in b[::-1]:
... print(v)
...
255
40
30
20
100

[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

Print by VIKASH Page - 21


Examples:
>>> r=range(6) =>Syntax2: varname= range(start,stop)
>>> print(r,type(r))---range(0, 6) <class =>This syntax creates an object of range
'range'> from start value to stop value-1 .
>>> for v in r: =>Examples:
... print(v)
... >>> r=range(10,16)
0 >>> print(r,type(r))--range(10, 16)
1 <class 'range'>
2 >>> for v in r:
3 ... print(v)
4 ...
5 10
>>> for v in range(6): 11
... print(v) 12
... 13
0 14
1 15
2 >>> for v in range(20,26):
3 ... print(v)
4 ...
5 20
21
22
23
24
25

=>In Syntax1 and Syntax2, the default interval value is 1


Syntax3: varname=range(start,stop,step)
=>This syntax creates an object of range from start value to stop value-1 by
maintaining specified step value( Step value is nothing equal interval of
value)
Examples:
Q1) Generate 1 2 3 4 5 6 7 8 9 -------range(1,10)
>>> for v in range(1,11,1):
... print(v)
...
1
2
3
4
5
6
7
8
9
Q2) generate 10 20 30 40 50 60 70 80 90 100----range(10,101,10)
>>> for v in range(10,101,10):
... print(v)
...
10
20
30
40
50
60
70
80
90
100
Print by VIKASH Page - 22
Q3) Generate 100 105 110 115 120-----range(100,121,5)
>>> for v in range(100,121,5):
... print(v)
...
100
105
110
115
120

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


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

Q5) generate -100 -110 -120 -130 -140 -150--range(-100,-151,-10)


>>> for v in range(-100,-151,-10):
... print(v)
...
-100
-110
-120
-130
-140
-150
Q6) generate 10 9 8 7 6 5 4 3 2 1----range(10,0,-1)
>>> for k in range(10,0,-1):
... print(k)
...
10
9
8
7
6
5
4
3
2
1
Q7) Generate 100 90 80 70 60 50 ----range(100,49,-10)
>>> for k in range(100,49,-10):
... print(k)
...
100
90
80
70
60
50

Print by VIKASH Page - 23


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

Q9) Generate -5 -4 -3 -2 -1 0 1 2 3 4 5---range(-5,6,1)


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

Q10) generate a multiplication table for number 9


>>> n=9
>>> for i in range(1,11):
... print(n,"x",i,"=",n*i)
...
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
Examples----range
-----------------
1 2 3 4 5 6 7 8 9 10-------range(1,11)

10 20 30 40 50 60 70 80 90 100----range(10,101,10)

100 105 110 115 120-----range(100,121,5)


---------------------------------------------------------
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 ---range(-1,-11,-1)
-100 -110 -120 -130 -140 -150--range(-100,-151,-10)
---------------------------------------------------------
10 9 8 7 6 5 4 3 2 1----range(10,0,-1)

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 )

Examples: --Converting float value into int value--->Possible


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

Examples: --Converting bool value into int value--->Possible


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

Examples: --Converting compex value into int value--->Not Possible


>>> a=2+3j
>>> print(a,type(a))-------------(2+3j) <class 'complex'>
>>> b=int(a)----TypeError: int() argument not 'complex'--Invalid

Examples: -- Attempting to Convert Str value into int type


>>> a="123" # int string into int Possible
>>> print(a,type(a))-------------123 <class 'str'>
>>> b=int(a)
>>> print(b, type(b))-----------123 <class 'int'>
>>> a="12.23" # float String into int Not Possible
>>> print(a,type(a))-----12.23 <class 'str'>
>>> b=int(a)----ValueError: invalid literal for int() with base 10: '12.23'
>>> a="True" # bool string into int Not Possible
>>> print(a,type(a))--------True <class 'str'>
>>> b=int(a)-----ValueError: invalid literal for int() with base 10: 'True'

Print by VIKASH Page - 25


>>> a="2+3.5j" # complex String into int Not Possible
>>> print(a,type(a))------------2+3.5j <class 'str'>
>>> b=int(a)-----------ValueError: invalid literal for int() with base 10:
'2+3.5j'
>>> a="PYTHON" # pure string into int Not Possible
>>> print(a,type(a))-----------PYTHON <class 'str'>
>>> b=int(a)---------ValueError: invalid literal for int() with base 10:
'PYTHON'

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'>

Example: bool value into float--->Possible


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

Example: complex value into float--->Not Possible


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

Example: Attempting to Convert Str value into float type


>>> a="12" # int str into float--Possible
>>> print(a,type(a))--------------12 <class 'str'>
>>> b=float(a)
>>> print(b, type(b))---------12.0 <class 'float'>
>>> a="12.34" # float str into float--Possible
>>> print(a,type(a))-------12.34 <class 'str'>
>>> b=float(a)
>>> print(b, type(b))----------12.34 <class 'float'>
>>> a="True" # bool str into float--Not Possible
>>> print(a,type(a))--------True <class 'str'>
>>> b=float(a)----ValueError: could not convert string to float: 'True'
>>> a="2.3+3.4j"----#complex str into float----Not Possible
>>> print(a,type(a))-----2.3+3.4j <class 'str'>
>>> b=float(a)--------ValueError: could not convert string to float:
'2.3+3.4j'
>>> a="[Link]" # Pure Str into float--Not Possible
>>> print(a,type(a))---------[Link] <class 'str'>
>>> b=float(a)----------ValueError: could not convert string to float:
'[Link]'
Print by VIKASH Page - 26
3) bool()
=>bool() is used for converting "one possible type of value into bool type value."
=>Syntax:
varname=bool( int / floay / complex / str value )
=>ALL NON-ZERO Values are TRUE
=>ALL ZERO Values are FALSE
Examples: int value into bool--->Possible
>>> a=120
>>> print(a,type(a))------------120 <class 'int'>
>>> b=bool(a)
>>> print(b, type(b))------------True <class 'bool'>
>>> a=-123
>>> print(a,type(a))------------123 <class 'int'>
>>> b=bool(a)
>>> print(b, type(b))-----------True <class 'bool'>
>>> a=0
>>> print(a,type(a))-------------0 <class 'int'>
>>> b=bool(a)
>>> print(b, type(b))-----------False <class 'bool'>

Examples: float value into bool--->Possible


>>> a=1.2
>>> print(a,type(a))---------1.2 <class 'float'>
>>> b=bool(a)
>>> print(b, type(b))--------True <class 'bool'>
>>> a=0.00000000000000000000000000000000000000001
>>> print(a,type(a))-----1e-41 <class 'float'>
>>> b=bool(a)
>>> print(b, type(b))-------True <class 'bool'>
>>> b=0.0
>>> print(b, type(b))--------0.0 <class 'float'>
>>> a=bool(b)
>>> print(a,type(a))---------False <class 'bool'>

Examples: comnplex value into bool--->Possible


>>> a=2+3.5j
>>> print(a,type(a))-------------(2+3.5j) <class 'complex'>
>>> b=bool(a)
>>> print(b, type(b))------------True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))------------0j <class 'complex'>
>>> b=bool(a)
>>> print(b, type(b))----------False <class 'bool'>
Examples:str values into bool------Possible
>>> a="123" #int str
>>> print(a,type(a))--------123 <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))-------True <class 'bool'>
>>> a="0" # int str
>>> print(a,type(a))--------0 <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))-------True <class 'bool'>
>>> a="0000"
>>> print(a,type(a))--------0000 <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))-------True <class 'bool'>
>>> a="KVR"
>>> print(a,type(a))--------KVR <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))--------True <class 'bool'>
Print by VIKASH Page - 27
>>> a=" "
>>> print(a,type(a))--------- <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))----------True <class 'bool'>
>>> len(a)---------------------1
>>> a=""
>>> print(a,type(a))----------- <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))-----------False <class 'bool'>
>>> len(a)----------------------0
>>> a="False"
>>> print(a,type(a))-----------False <class 'str'>
>>> b=bool(a)
>>> print(b, type(b))----------True <class 'bool'>
>>> a=False
>>> b=bool(a)
>>> print(b, type(b))----------False <class 'bool'>
>>> a=0e0
>>> print(a,type(a))----------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b, type(b))---------False <class 'bool'>

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

Print by VIKASH Page - 28


5. str()
=>This Function is used for converting all types of values into str type.
Syntax: varname=str(int/ float/ bool / complex)
Examples:
---------------------

>>> 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)'

Print by VIKASH Page - 29


==========================================================
3. List Catagery Data Types (Collection Data Types)
==========================================================
=>List Catagery Data Types are used for storing Multiple Values either of same type
or different type or both types with Unique and Duplicate Values in a single
variable.
=>List Catagery Data Types are classified into 2 types. They are
a) list
b) tuple
=============================
(A). LIst (Collection type)
=============================
Index:
=>Purpose
=>Organization of elements
=>Operations on List
=>Pre-defined Functions in list
=>Inner / Nested List
=>Pre-defined Functions in inner / nested list

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]

Print by VIKASH Page - 30


>>> print(l1[::-1])----[True, (2+3j), 'NL', 'CWI', 11.11, 'Rossum', 10]
>>> print(l1,type(l1))----[10, 'Rossum', 11.11, 'CWI', 'NL', (2+3j),
True] <class 'list'>
>>> print(id(l1))--------2261150743872
>>> l1[-1]=False
>>> print(l1,type(l1),id(l1))----[10, 'Rossum', 11.11, 'CWI', 'NL',
(2+3j), False] <class 'list'> 2261150743872

[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

Slicing Based Copy:


---------------------------
=>The this copy process is also Shallow Copy implementation only.
Examples:
>>> lst1=[10,"Python","Rossum",34.56]
>>> print(lst1,id(lst1))----[10, 'Python', 'Rossum', 34.56] 2955419255872
>>> lst2=lst1[::] # slice based copy
>>> print(lst2,id(lst2))----[10, 'Python', 'Rossum', 34.56] 2955419270720
>>> [Link](34.56)
>>> print(lst1,id(lst1))----[10, 'Python', 'Rossum'] 2955419255872
>>> print(lst2,id(lst2))----[10, 'Python', 'Rossum', 34.56] 2955419270720
>>> lst3=lst1[0:3] # slice based copy
>>> print(lst3,id(lst3))---[10, 'Python', 'Rossum'] 2955419266624
>>> lst4=lst1[::-1] # slice based copy
>>> print(lst4,id(lst4))---['Rossum', 'Python', 10] 2955419517312

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 ]

=> [ val11,val12,...] is called one inner list


=> [val22,val23....] is ccalled another inner list
=> [ val1,val2.... ....val
....val-n ] is called outer list
=>On the list and inner list we can apply all operation regarding Indexing, Slicing
and all pre-defined
defined functions.
Examples:
My Requirement -->To store
stno----------
----------10
name -----Mahesh
Mahesh
Internal Marks of three subs
subs---18,19,17
External Marks of three subs
subs---73 71,65
College name---
---OUCET

Print by VIKASH Page - 36


stlist=[10,"Mahesh",18,19,17,73,71,65,"OUCET"]
(OR)
stlst1=[ 10,"Mahesh", [18,19,17],[73,71,65], "OUCET" ]
Examples:
>>> l1=[10,"Rossum",[16,19,15],[78,65,79],"NLU"]
>>> print(l1,type(l1))
print(l1,type(l1))------[10,
[10, 'Rossum', [16, 19, 15], [78, 65, 79],
'NLU'] <class 'list'>
>>> print(l1[0])
print(l1[0])------------10
>>> print(l1[1])
print(l1[1])------------Rossum
>>> print(l1[2])
print(l1[2])------------[16, 19, 15]
>>> print(l1[2][1]
print(l1[2][1]----------19
>>> print(l1[2][
print(l1[2][-1])--------15
>>> print(l1[3])
print(l1[3])------------[78, 65, 79]
>>> print(l1[3][
print(l1[3][-3])--------78
>>> print(l1[3][0])
print(l1[3][0])---------78
>>> print(l1[4])
print(l1[4])------------NLU
>>> print(l1[3][0:3])
print(l1[3][0:3])-------[78, 65, 79]
>>> print(l1[3
print(l1[3][::-1])------[79, 65, 78]
>>> l1[3].append(80)
>>> print(l1[3])
print(l1[3])------------[78, 65, 79, 80]
>>> l1[-3].insert(
3].insert(-2,16)
>>> l1[-3]------------------
------------------[16, 16, 19, 15]
>>> l1[-3].sort()
3].sort()
>>> l1[-3]------------------
------------------[15, 16, 16, 19]
>>> l1[-2].sort(reverse=True)
2].sort(reverse=True)
>>> l1[-2]-----
------------------[80, 79, 78, 65]

===================================
========
(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'>

Print by VIKASH Page - 38


========================================
Pre-defined Functions in tuple
========================================
=>Tuple object contains two Functions. They are
a) count()
b) index()

=>Tuple does not contain the following Functions


a)append() b)insert() c)clear()
d)copy() e)pop() f)pop(index)
g)remove() h)sort() i)reverse()
j) extend()

==================================================
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 )

1. set (mutable and immutable)


======================================
=>’set’ of one of the pre-defined class treated as Set category data type.
=>The purpose of set data type is that “To Store Multiple Values either of same
type or different type or both types with Unique Values in a single variable”.
=>The 39lements of set must organized with curly braces { } and elements bmust be
separated by comma.
=>The elements of set never maintains insertion Order bcoz it displays its elements
in any of the possibilities.
=>On the object of set, we can’t perform indexing and Slicing Operations bcoz it
can’t maintain insertion order.
=>An object of set belongs to both mutable ( in the case of add() ) and immutable
in the case item assignment (set’ object does not support item assignment).
=>To convert one type value into set type values , we use set().
=>We have two types of set objects.
a) empty set
b) non-empty set

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

Print by VIKASH Page - 39


>>> [Link](“PYTHON”)
>>> print(s1,type(s1),id(s1))---{‘KVR’, 33.33, True, ‘PYTHON’, ‘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

Pre-defined Functions in Frozenset


---------------------------------------------
a)isdisjoint() b)issuperset() c)issubset()
d)union() e)intersection() f)differnce()
g)symmetric_difference()

Pre-defined Functions does not contain in Frozenset


---------------------------------------------
add() remove() discard() pop() update()

Print by VIKASH Page - 44


========================================================
Dict Category Data Type(Collection data type)
========================================================

=>'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"}

Print by VIKASH Page - 45


>>> print(d1,id(d1))
{10: 'Rossum', 20: 'Ritche', 30: 'Gosling', 40: 'Travis'} 6832
>>> d1[50]="Tim"
>>> print(d1,id(d1))
{10:'Rossum',20:'Ritche',30:'Gosling',40:'Travis',50:'Tim'} 6832
------------------------------------------------------------------------
>>> d1=dict()
>>> d1["Apple"]=25.67
>>> d1["Kiwi"]=30
>>> d1["Sberry"]=100.34
>>> d1["Mango"]=80
>>> print(d1)
{'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34, 'Mango': 80}
-----------------------------------------------------------------------
>>> d1={}
>>> d1[10]="Praveen"
>>> d1["RS"]=20
>>> print(d1)
{10: 'Praveen', 'RS': 20}
-----------------------------------------------------------------------------------
Special Cases:
>>> d1={10:[100,200,300,400],20:(500,600,700)}
>>> print(d1)---{10: [100, 200, 300, 400], 20: (500, 600, 700)}
>>> for k,v in [Link]():
... print(k,"--->",v)
...
10 ---> [100, 200, 300, 400]
20 ---> (500, 600, 700)

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

pre-defined functions in dict


=============================================
1) clear():
=>This is used for removing all the entires of dict objct.
Syntax:- [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]()
>>> print(d1)-------{}

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'

Print by VIKASH Page - 46


3) popitem():
=>This Function is used for removing the last (Key,Value ) from dict object
=>When we call popitem() upon empty dict object then we get KeyError
=>Syntax: [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]()---('Mango', 80)
>>> print(d1)---{'Apple': 25.67, 'Kiwi': 30, 'Sberry': 100.34}
>>> [Link]()----('Sberry', 100.34)
>>> print(d1)----{'Apple': 25.67, 'Kiwi': 30}
>>> [Link]()---('Kiwi', 30)
>>> print(d1)---{'Apple': 25.67}
>>> [Link]()---('Apple', 25.67)
>>> print(d1)---{}
>>> [Link]()---KeyError: 'popitem(): dictionary is empty'

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]()

Print by VIKASH Page - 48


Examples:
>>> d1={'Apple': 25.67, 'Kiwi': 30}
>>> print(d1,id(d1))----------{'Apple': 25.67, 'Kiwi': 30} 18976
>>> d2=[Link]()
>>> print(d2,id(d2))----{'Apple': 25.67, 'Kiwi': 30} 18656
>>> d2["Sberry"]=23.45
>>> d1["Guava"]=60
>>> print(d1,id(d1))---{'Apple': 25.67, 'Kiwi': 30, 'Guava': 60} 18976
>>> print(d2,id(d2))--{'Apple':25.67,'Kiwi':30,'Sberry':23.45} 18656

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.

Example Software:- Python Interactive Command Prompt


Python IDLE Shell
Print by VIKASH Page - 49
Example Code:
>>> a=100
>>> b=200
>>> c=a+b
>>> print(a,b,c)----100 200 300

=> 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

Example Software:- Python IDLE Shell


Edit Plus
PyCharm
Jupiter Note Book
Spider
VS CODE
atom-------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

=>Syntax-2---------->Displaying Messages with Values


print(Message cum Values)
Examples:
>>> a=100
>>> print("Val of a=",a)----Value of a=100
>>> a=100
>>> print(a," is the value of a")----100 is the value of a
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum=",c)-----sum= 30
>>> print(c," is the sum")---30 is the sum
>>> print("sum of ",a," and ",b,"=",c)---sum of 10 and 20 = 30
>>> a=10
>>> b=20
>>> c=30
>>> d=a+b+c
Print by VIKASH Page - 50
>>> print("sum of ",a,",",b," and ",c,"=",d)---sum of 10 , 20 and 30
= 60

=>Syntax-3: Displaying Messages with Values by using format()


>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum of {} and {}={}".format(a,b,c) )---Sum of 10 and 20=30
>>> sno=10
>>> name="Rossum"
>>> print("My Roll no:{} and Name:{}".format(sno,name))
My Roll no:10 and Name:Rossum

=>Syntax-4:----Displaying Messages with Values by using format specifiers


print("Messages with Format specifiers " %(var1,var2...var-n))
Examples:
>> 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=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.

Print by VIKASH Page - 51


b) input(Message)
=> This function is used for reading any type of data / value dynamically
from keyboard in the form of str always and additionally it gives User-Prompting
Message.
Syntax:- varname=input(Message)
=> 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(Message) is a pre-defined function and it reads at a time only one value
in the form of str and Message represents "User-Prompting Message".

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))

#Program for accepting two values and find their sum


#[Link]
print("Enter Two Values for a and b:")
#convert a and b values into int type
n=float( input() )
m=float( input() )
res=n+m
print("sum of {} and {}={}".format(n,m,res))

#Program for accepting two values and find their sum


#[Link]
print("Enter Two Values for a and b:")
#convert a and b values into int type
n=float( input() )
m=float( input() )
print("sum of {} and {}={}".format(n,m,n+m))

#Program for accepting two values and find their mul--input(message)


#[Link]
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
#convert s1 and s2 and into float type values
v1=float(s1)
v2=float(s2)
v3=v1*v2
print("------------------------------------")
print("Val of v1={}".format(v1))
Print by VIKASH Page - 52
print("Val of v2={}".format(v2))
print("Mul={}".format(v3))
print("------------------------------------")
#Program for accepting two values and find their mul--input(message)
#[Link]
v1=float(input("Enter First Value:"))
v2=float(input("Enter Second Value:"))
v3=v1*v2
print("------------------------------------")
print("Val of v1={}".format(v1))
print("Val of v2={}".format(v2))
print("Mul={}".format(v3))
print("------------------------------------")

==========================================
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 6) Membership Operators


2) Assignment Operator a) in
3) Relational Operators b) not in
4) Logical Operators 7) Identity Operators
5) Bitwise Operators (Most Imp) a) is
b) is not

=========================================
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

5. // Floor Divison print(a//b)--->3


(Integer Quotient) print(10.0//3.0)--->3.0

6 % Modulo Division print(a%b)----1

7. ** Exponentiation print(a**b)
===================================================================================

Print by VIKASH Page - 53


=========================================
2) Assignment Operator
=========================================
=>The purpose of Assigment operator is that to transfer Right hand Side (RHS) value
to Left Hand Side (LHS) Variable .
=>We can use Assignment Operator in two ways. They are
a) Single Line Assigment
b) Multi Line Assigment

a) Single Line Assigment:


Syntax: LSHVarname=RHS Var name/Value / Expression
Examples:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)

b) Multi Line Assigment:


Syntax: LHS var1, LHS var2...LHS var-n=RHS var1 , RHS var2, ...RHS var-n
(OR)
LHS var1, LHS var2...LHS var-n=RHS Expr1 , RHS Expr2, ...RHS Expr-n
Examples:
>>> a,b=10,20
>>> c,d,e=a+b,a-b,a*b
>>> print("c=",c)--------c= 30
>>> print("d=",d)-------d= -10
>>> print("e=",e)-------e= 200
-----------------------------------------------------------------------------------
Write a program in python and do some operation.
#[Link]
a=float(input("Enter Value of a:"))
b=float(input("Enter Value of b:"))
print("="*50)
print("\tArithmetic Operations")
print("="*50)
print("\tSum({},{})={}".format(a,b,a+b))
print("\tSub({},{})={}".format(a,b,a-b))
print("\tMul({},{})={}".format(a,b,a*b))
print("\tDiv({},{})={}".format(a,b,a/b))
print("\tInetger Div({},{})={}".format(a,b,a//b))
print("\tMod({},{})={}".format(a,b,a%b))
print("\texpo({},{})={}".format(a,b,a**b))
print("="*50)
#[Link]
n=float(input("Ente a number:"))
res=n**(1/2)
print("sqrt({})={}".format(n,res))
Write a python program to swap to number.
#[Link]
a,b=input("Enter Value of a:"),input("Enter Value of b:")
print("="*50)
print("Original value of a={}".format(a))
print("Original value of b={}".format(b))
print("="*50)
#swapping logic
a,b=b,a # multi line assigment
print("Swapped value of a={}".format(a))
print("Swapped value of b={}".format(b))
print("="*50)
===================================================================================
Print by VIKASH Page - 54
================================================
3. Relational Operators in Python
================================================
=>The purpose of Relational Operators is that "To compare two or more number of
values".
=> If two or more number of values / variables connected with Relational Operators
then it is called Relational Expression.
=>The result of relational expression is either True or False
=>Always relational Expressions called Conditions.
=>The Relational Operators are given following table

===================================================================================
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

5. >= greater than print(a>=c)-----True


or equal to print(a>=b)-----False
6. <= Less Than
or equal to print(a<=b)------True
print(100<=b)---False
----------------------------------------------------------------------------------
Write a program to do some relation operations.
#[Link]
#program for demonstrating Relation Operators.
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*50)
print("Results of Relational Operators:")
print("-"*50)
print("\t{}>{}={}".format(a,b,a>b))
print("\t{}<{}={}".format(a,b,a<b))
print("\t{}=={}={}".format(a,b,a==b))
print("\t{}!={}={}".format(a,b,a!=b))
print("\t{}>={}={}".format(a,b,a>=b))
print("\t{}<={}={}".format(a,b,a<=b))
print("-"*50)

================================================
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

2) and (Physical ANDing)


=>The Functionality of 'and' operator is shown in the following truth table
 Syntax:- RelExpr1 and RelExpr2
================================================================
RelExpr1 RelExpr2 RelExpr1 and Relexpr2
================================================================
True False False
False True False
False False False
True True True
=================================================================
Examples:
>>> 100>=200 and 10<5-------------False
>>> 100>=20 and 10!=5-----------True
>>> 100>=20 and 10!=5 or 10!=20---True
>>> 100<=20 and 10<=5 or 10!=20----True
>>> 100!=-100 and 100==20 and 20!=4 or 4!=5----True
3. not :
=>The Functionality of 'not' operator is shown in the following truth table
 Syntax:- not repexr1
not(RelExpr1 or RelExpr2)
not (RelExpr1 and RelExpr2)
=================================
RelExpr1 not RelExpr1
=================================
True False
False True
=================================
Examples:-
>>> 10>5 and 10!=2-----------True
>>> not (10>5 and 10!=2)---------False
>>> 10<5 or 10!=10------False
>>> not (10<5 or 10!=10)--------True
>>> not 10>20-------True
>>> not 10==10---------False
>>> not True----False
>>> not False--------True
>>> not 100------------False
>>> not 0---------True
>>> not not 0-----------False
>>> not not---------SyntaxError: invalid syntax
>>> not not ""------------False
Print by VIKASH Page - 56
>>> not "Python"-----False
>>> "True"=="False"----------False
>>> True==False------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 ( ^ )

1) Bitwise Left shift Operator ( << ):


Syntax:- resultantvar = GivenData << [Link] bits
=>This operators shifts Specfied No. of Bits toward left side by adding no. Zeros
which are equal to [Link] bits at right side.
Examples:
>>> print(10<<3)-----------80
>>> a=10
>>> b=3
>>> c=a<<b
>>> print(c)--------80
>>> print(12<<2)-----48

2) Bitwise Right shift Operator ( >> ):


Syntax:- resultantvar = GivenData >> [Link] bits
=>This operators shifts Specfied No. of Bits toward right side by adding no. Zeros
which are equal to [Link] bits at Left side.
Examples:
>>> a=10
>>> b=3
>>> c=a>>b
>>> print(c)----------1
>>> print(12>>2)----3
>>> print(16>>3)----2

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 by VIKASH Page - 57


Examples:
>>>a=4--------------- 0100
>>>b=5----------------0101
---------------------------
>>>c=a|b------------>0101--------------Result is 5

>>>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'>

4) Bitwise AND Operator ( & ):


=> Syntax: resultantvar= value1 & value2
=>The Functionality of Bitwise AND Operator ( & ) is shown in the following table.
-----------------------------------------------------
Value1 Value2 Value1 & Value2
-----------------------------------------------------
0 0 0
0 1 0
1 0 0
1 1 1
-----------------------------------------------------

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

5) Bitwise complement Operator ( ~ )


Syntax:- resultantvar= ~Value
Examples:
>>>a=10---------------------> 1010
>>>b=~a---------------------> ~(1010+0001)
-----------> - (1010
0001)
------------
-( 1011 )------------->result is -11
-------------
Formula:- >>> ~varval -----------> -(varval+1)
>>>print(~20)------------> -21
>>> a=98
>>> c=~a
>>> print(c)-----------99
>>> print(~20)---------21
>>> print(~(-101))------100

Print by VIKASH Page - 58


6) Bitwise XOR Operator ( ^ ):
=>Syntax: resultantvar= value1 ^ value2
=>The Functionality of Bitwise XOR Operator (^) is shown in the following table.
----------------------------------------------------
Value1 Value2 Value1 ^ Value2
----------------------------------------------------
0 0 0
0 1 1
1 0 1
1 1 0
----------------------------------------------------
Examples:
>>>a=10----------- 1010
>>>b=4------------ 0100
------------------------
>>>c=a^b----------1110------------>Result is 14

>>> 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

=>"value" represents the value to check in Sequence or Collection object


=>Here sequence objects represents (str,bytes, bytearray and range) and collect
objects represents (list, tuple,set,frozenset,dict)
Print by VIKASH Page - 59
=>Here "in" operator returns True provided Value present / exists in Sequence /
Collection objects"
=>Here "in" operator returns False provided Value not present / exists in Sequence
/ Collection objects".
Examples:
>>> l1=[10,20,30,40,50,-34]
>>> 20 in l1--------True
>>> -34 in l1----True
>>> 34 in l1-----False
>>> "KVR" in l1-------False
>>> -43 in l1-----False
b) not in:
Syntax:- Value not in Sequence / Collection object

=>"value" represents the value to check in Sequence or Collection object


=>Here sequence objects represents (str,bytes, bytearray and range) and collect
objects represents (list, tuple,set,frozenset,dict)
=>Here "not in" operator returns True provided Value not present / exists in
Sequence / Collection objects"
=>Here "not in" operator returns False provided Value present / exists in Sequence
/ Collection objects".
Examples:
>>> l1=[10,20,30,40,50,-34]
>>> 100 not in l1----------True
>>> 10 not in l1--------False
>>> "KVR" not in l1--------True
>>> 30 not in l1-----------False
Some other example:-
>>> s="PYTHON"
>>> print(s,type(s))------------PYTHON <class 'str'>
>>> "p" in s-------False
>>> "P" in s--------True
>>> "ON" in s-----True
>>> "HON" in s----True
>>> "HON" not in s-------False
>>> "NO" in s-----False
>>> "HNO" not in s----True
>>> "HNO" in s-----False
>>> print(s,type(s))-----PYTHON <class 'str'>
>>> s[0] not in s----------False
>>> s[0:2:-1] not in s---------False
>>> s[::] not in s[::-1]--------True
>>> s[::]!=s[::-1]--------True
>>> s[::]==s[::-1]------False

=====================================
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

Print by VIKASH Page - 60


b) is not:
Syntax:- obj1 is not obj2
=>"is not " operator returns True provided both obj1 and obj2 contains different
memory address otherwise it returns False
Examples:
>>> v1=None
>>> v2=None
>>> print(v1,id(v1))---------None 140703467931640
>>> print(v2,id(v2))---------None 140703467931640
>>> v1 is v2-----------------True
>>> v1 is not v2-------------False
-----------------------------------------------------------------------------------
>>> d1={10:"Apple",20:"Mango"}
>>> d2={10:"Apple",20:"Mango"}
>>> print(d1,id(d1))--{10: 'Apple', 20: 'Mango'} 1772239617856
>>> print(d2,id(d2))--{10: 'Apple', 20: 'Mango'} 1772239667328
>>> d1 is d2---------------False
>>> d1 is not d2-----------True
-----------------------------------------------------------------------------------
>>> s1={10,20,30}
>>> s2={10,20,30}
>>> print(s1,id(s1))--------{10, 20, 30} 1772239875520
>>> print(s2,id(s2))--------{10, 20, 30} 1772239874176
>>> s1 is s2----------------False
>>> s1 is not s2-----------True
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1,id(fs1))------frozenset({10, 20, 30}) 1772239874400
>>> print(fs2,id(fs2))------frozenset({10, 20, 30}) 1772239875968
>>> fs1 is fs2--------------False
>>> fs1 is not fs2----------True
-----------------------------------------------------------------------------------
>>> l1=[10,20,30,40]
>>> l2=[10,20,30,40]
>>> print(l1,id(l1))---------[10, 20, 30, 40] 1772239681536
>>> print(l2,id(l2))---------[10, 20, 30, 40] 1772239728128
>>> l1 is l2-----------------False
>>> l1 is not l2-------------True
>>> t1=tuple(l1)
>>> t2=tuple(l2)
>>> print(t1,id(t1))---------(10, 20, 30, 40) 1772239704032
>>> print(t2,id(t2))---------(10, 20, 30, 40) 1772239581520
>>> t1 is t2-----------------False
>>> t1 is not t2-------------True
-----------------------------------------------------------------------------------
>>> s1="PYTHON"
>>> s2="PYTHON"
>>> print(s1, id(s1))----------PYTHON 1772239928944
>>> print(s2, id(s2))----------PYTHON 1772239928944
>>> s1 is s2-------------------True
>>> s1 is not s2---------------False
>>> s1="kvr"
>>> s2="kvr"
>>> s1 is s2-------------------True
>>> s1 is not s2---------------False
>>> print(s1,id(s1))-----------kvr 1772239979184
>>> print(s2,id(s2))-----------kvr 1772239979184
-----------------------------------------------------------------------------------
>>> l1=[10,20,30]
>>> b1=bytes(l1)
>>> b2=bytes(l1)
Print by VIKASH Page - 61
>>> print(b1,type(b1))---------b'\n\x14\x1e' <class 'bytes'>
>>> print(b1,id(b1))-----------b'\n\x14\x1e' 1772239838192
>>> print(b2,id(b2))-----------b'\n\x14\x1e' 1772239837472
>>> b1 is b2-------------------False
>>> b1 is not b2---------------True
>>> ba=bytearray(l1)
>>> bb=bytearray(l1)
>>> print(ba, id(ba))----------bytearray(b'\n\x14\x1e') 1772239979696
>>> print(bb, id(bb))----------bytearray(b'\n\x14\x1e') 1772239979312
>>> ba is bb-------------------False
>>> ba is not bb---------------True
-----------------------------------------------------------------------------------
>>> r1=range(10,20)
>>> r2=range(10,20)
>>> print(r1,id(r1))-----------range(10, 20) 1772239837424
>>> print(r2,id(r2))-----------range(10, 20) 1772239837760
>>> r1 is r2-------------------False
>>> r1 is not r2---------------True
-----------------------------------------------------------------------------------
>>> a=2+3j
>>> b=2+3j
>>> print(a, id(a))------------(2+3j) 1772239378832
>>> print(b, id(b))------------(2+3j) 1772239378576
>>> a is b---------------------False
>>> a is not b-----------------True
-----------------------------------------------------------------------------------

>>> 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

>>> a is not b------------------False


>>> b=257
>>> a=257
>>> print(a, id(a))--------------------257 1772239378416
>>> print(b, id(b))--------------------257 1772239378832
>>> a is b-----------------------------False
>>> a is not b-------------------------True
>>> a=101
Print by VIKASH Page - 62
>>> b=101
>>> a is b-----------------------------True
>>> a is not b-------------------------False
>>> a=-3
>>> b=-3
>>> print(a, id(a))---------------------3 1772238340208
>>> print(b, id(b))----------------------3 1772238340208
>>> a is b-------------------------------True
>>> a is not b---------------------------False
>>> a=-5
>>> b=-5
>>> print(a, id(a))-----------------------5 1772238340144
>>> print(b, id(b))------------------------5 1772238340144
>>> a is b---------------------------------True
>>> a is not b-----------------------------False
>>> a=-6
>>> b=-6
>>> print(a, id(a))-------------------------6 1772239378608
>>> print(b, id(b))--------------------------6 1772239378416
>>> a is b----------------------------------False
>>> a is not b------------------------------True
-----------------------------------------------------------------------------------
>>> a,b=300,300
>>> print(a,id(a))-------------------------300 1772239378832
>>> print(b,id(b))-------------------------300 1772239378832
>>> a is b---------------------------------True
>>> a is not b-----------------------------False
>>> a,b=-10,-10
>>> print(a,id(a))--------------------------10 1772239378768
>>> print(b,id(b))---------------------------10 1772239378768
>>> a is b-----------------------------------True
>>> b is a-----------------------------------True
-----------------------------------------------------------------------------------
>>> a,b=[10,20],[10,20]
>>> print(a,id(a))--------------------------[10, 20] 1772239681536
>>> print(b,id(b))--------------------------[10, 20] 1772239928704
>>> a is b----------------------------------False
>>> a is not b------------------------------True
>>> a,b={10:"App",20:"Mango"},{10:"App",20:"Mango"}
>>> print(a,id(a))-----------{10: 'App', 20: 'Mango'} 772239722496
>>> print(b,id(b))-----------{10: 'App', 20: 'Mango'} 1772239617920
======================================X============================================

===========================================
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.

Print by VIKASH Page - 63


====================
==================================================================
=====================================
1) Conditional (or) Selection (or) Branching Statements
===========================================================
=>The purpose of Conditional statements is that "To perform Certain
Operation i.e X-operation
operation in the case of True or Y Y-Operation
Operation in the
case of False only Once."
=>In Python Programming, we have 4 Conditional statements. They are
a) Simple if statement
b) if..else statement
c) if..elif..else statement
d) match...case
h...case statement(Python 3.10 version)

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")

Print by VIKASH Page - 64


EXAMPLE 3:- write a program to find a
ZERO, Positive & Negative number and
print them.
#[Link] EXAMPLE 4:-
n=float(input("Enter a value:")) #[Link]
if(n==0): tkt=input("Do u have a ticket
print("{} is ZERO".format(n)) (yes/no):")
if(n>0): if(tkt=="yes"):
print("{} is +VE".format(n)) print("Enter into theater")
print("watch the moviee")
if(n<0): print("Eat the snacks!")
print("{} is -VE".format(n))
VE".format(n)) print("\nGoto
nGoto Home:")
print("Program execution over")

# Write a program to input a digit and print them a digit letter.


#[Link]
d=int(input("Enter a Digit:")) # d=123
if(d==0):
print("{} is ZERO".format(d))
elif(d==1):
print("{} is ONE".format(d))
elif(d==2):
print("{} is TWO".format(d))
elif(d==3):
print("{} is THREE".format(d))
elif(d==4):
Print by VIKASH Page - 65
print("{} is FOUR".format(d))
elif(d==6):
print("{} is SIX".format(d))
elif(d==7):
print("{} is SEVEN".format(d))
elif(d==5):
print("{} is FIVE".format(d))
elif(d==8):
print("{} is EIGHT".format(d))
elif(d==5):
print("{} is NINE".format(d))
else:
print("It is a number:")

print("\nProgram execution over")

#Write a program in python to payslip and print them.


#[Link]
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
basicsal=float(input("Enter Basic Salary of employee:"))
if(basicsal<=0):
print("Invalid salary:")
else:
if(basicsal>=10000):
da=basicsal*(20/100)
ta=basicsal*(15/100)
hra=basicsal*(15/100)
ma=basicsal*(5/100)
gpf=basicsal*(2/100)
lic=basicsal*(2/100)
else:
da=basicsal*(30/100)
ta=basicsal*(25/100)
hra=basicsal*(20/100)
ma=basicsal*(10/100)
gpf=basicsal*(1/100)
lic=basicsal*(1/100)
netsal=(basicsal+da+ta+hra+ma)-(gpf+lic)
print("*"*50)
print("Employee Number:{}".format(eno))
print("Employee Name:{}".format(ename))
print("Employee Basic Salary:{}".format(basicsal))
print("Employee DA:{}".format(da))
print("Employee TA:{}".format(ta))
print("Employee HRA:{}".format(hra))
print("Employee MA:{}".format(ma))
print("Employee GPF:{}".format(gpf))
print("Employee LIC:{}".format(lic))
print("-"*50)
print("Net Salary:{}".format(netsal))
print("*"*50)

Print by VIKASH Page - 66


========================================
for loop (or) for...else
========================================

(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

Print by VIKASH Page - 67


Explanation:
=================
=>here 'for' and 'in' are the keywords
=>The execution process of for loop is that " Each element of Iterable-object kept
in varname and executes Indentation Block of statements until all elements in
iterable object are completed"
=>here writing 'else' block is optional.
=>After for loop excution, condition becomes false and PVM executes else block of
statements(if we write else) and later executes 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
--------------------- ----------------
----------------

Print by VIKASH Page - 68


Q) write a python program to using a break function

#[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 python program to print “PYTHN PRG” using


break statements. Q) write a program to print except -40
#[Link] #[Link]
s="PYTHON PROG" lst=[10,20,30,40,50,60,-40,70,80]
for val in s: for val in lst:
print("\t{}".format(val)) print("\t{}".format(val))
else: else:
print("Line-6 i am from else") # here it is print("line-6-i am from else part") #executed
executed print("----------------")#print the elements 10
print("--------------------------------------") 20 30 40 50 60 only
for val in lst:
for val in s: if(val == -40):
if(val=="O"): break
break else:
print("\t{}".format(val)) print("\t{}".format(val))
else: else:
print("Line-14:-i am from else block") # here print("line-15-i am from else part") # executed
it is not executed print("--------------------------------------")
print("---------------------------------------")

Q) write a program to print a number PRIME OR NOT PRIME.


#[Link]
n=int(input("Enter a number:")) # n=5
if(n<=1):
print("{} is invalid input:".format(n))
else:
result="PRIME"
for i in range(2,n):
if(n%i==0):
result="NOT RIME"
break
if(result=="PRIME"):
print("{} is a Prime Number:".format(n))
else:
print("{} is a not Prime Number:".format(n))

Print by VIKASH Page - 69


======================================
continue statement
======================================
=>continue is a keyword
=>continue statement is used for making the PVM to go to the top of the loop
without executing the following statements which are written after continue
statement for that current Iteration only.
=>continue statement to be used always inside of loops.
=>when we use continue statement else part of corresponding loop also executes
provided loop condition becomes false.
=>Syntax:-
for varname in Iterable-object:
------------------------------------------
if ( Test Cond):
continue
statement-1 # written after continue statement
statement-2
statement-n
-----------------------------------------
-----------------------------------------

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)))

Print by VIKASH Page - 70


[Link](value)
else:
print("Content of list={}".format(lst))# [12.3, 34.5, -3.4, -5.6, 12.0]
#get only Possitive Elements
pslist=[]
for val in lst:
if(val<=0):
continue
[Link](val)
else:
print("Possitive Values:{}".format(pslist))
print("--------------------------------")
nslist=[]
for val in lst:
if(val>=0):
continue
[Link](val)
else:
print("Negatuve Values:{}".format(nslist))
print("--------------------------------")

=======================================
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:
----------------------------

Print by VIKASH Page - 71


Inner loop example :-

#[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("-------------------------------")

Print by VIKASH Page - 72


#[Link]
#accept list of values
n=int(input("Enter How Many Values u have:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
lst=list()
for i in range(1,n+1):
val=int(input("Enter {} value:".format(i)))
[Link](val)
else:
print("--------------------------------------")
print("Content of List=",lst) # [1, 14, 12, 13, 17]
print("--------------------------------------")
pnlst=[]
i=0
while(i<len(lst)):
n=lst[i]
if(n<=1):
print("{} is invalid Input:".format(n))
else:
result="Prime"
for j in range(2,n):
if(n%j==0):
result="Not Prime"
break
if(result=="Prime"):
[Link](n)
i=i+1
else:
print("Prime Numbers List={}".format(pnlst))

Print by VIKASH Page no -73


Introduction to Functions
----------------------------------------------
=>The Purpose of Function Concept in any Programming language is that "To Perform Certain Operation and
Provides Code Re-Usability".
Def. of Function : A part of main program is called Function.
(OR)
Sub Program of main program is called Function.

=>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

a) Un-Structured Programming Languages:


=>In Un-Structured Programming Languages, we don't have the concept of Functions.
Example:- GW-BASIC
=>Since Un- Un-Structured Programming Languages does not contain Functions concept and It has the
following Limitations.

1. Application development time is More


2. Application Takes More Memory Space.
3. Application Excution time is more
4. Application Performnace is degraded.
5. Redundency (Duplication) of the the code.

b) Structured Programming Languages:


=>In Structured Programming Languages, we have the concept of Functions.
Example:- C,CPP,JAVA,PYTHON,.NET....etc
=>Since Structured Programming Languages contains Functions concept and It has the following Adavantages.

1. Application development time is Less


2. Application Takes Less Memory Space.
3. Application Excution time is Less.
4. Application Performnace is Enhanced(Improved).
5. Redundency (Duplication) of the the Minimized.

Print by VIKASH Page no -74


Print by VIKASH Page no -75
Print by VIKASH Page no -76
Phases in Functions
------------------------------------
a) Every Function takes INPUT
b) Every Function PROCESS the input
c) Every Function gives OUTPUT / RESULT

Approaches to develop a function for problem solving

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

Print by VIKASH Page no -77


#[Link]
def sumop(): #[Link]
a=float(input("Enter First Value:")) def sumop(a,b):
b=float(input("Enter Second Value:")) c=a+b
c=a+b print("sum({},{})={}".format(a,b,c))
return a,b,c # In python, return can return one or more
number of values. #main program
a=float(input("Enter First Value:"))
#main program b=float(input("Enter Second Value:"))
x,y,z=sumop() # Multi Line assignment statement. sumop(a,b)
print("sum of {} and {}={}".format(x,y,z))
print("==============OR===============") #[Link]
res=sumop() # here res is variable of type <class, 'tuple'> and it #Approach-1
can hold many values returned by return statement. def sqroot(n):
print("sum of {} and {}={}".format(res[0],res[1],res[2] ) ) res=n**0.5
print("sum of {} and {}={}".format(a,b,c ) ) return res

#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()

Print by VIKASH Page no -78


===================================
Arguments and Parameters
===================================
=>Arguments and Parameters are representing Variable Names.
=>Arguments are the variables which are used in Function Calls. Arguments are also called Actual Parameters /
arguments.
=>Parameters are the variables, which are used two places in Function Definition. The Parameters used in
Function Heading are called Formal Parameters and the Parameters used in Function Body are called Local
Parameters / Variables.
=>All the values Arguments are passing Parameters and it known as arguments / Parameter Passing
Mechanisms.

#[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

1) Positional Arguments (or) Parameters :-


=>The Concept of Positional Parameters (or) arguments says that "The Number of Arguments (Actual
Parameters) must be equal to the number of formal paraemeters ".
=>This Parameter mechanism also recommends Order of Parameters for Higher accuracy.
=>Python Programming Environment follows by default Positional Parameters.

Syntax for Function Definition :


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

Syntax for Function Call:


functionname(arg1,arg2....arg-n)
=>Here the values of arg1,arg2...arg-n are passing to param-1,param-2..param-n respectively.

#[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("---------------------------------------")

2) Default Parameters (or) arguments :-


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

Syntax: for Function Definition with Default Parameters


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

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


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

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).

Print by VIKASH Page no -80


#[Link]
def dispstuddet(stno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{} \t{}\t{}\t{}\t{}".format(stno,sname,marks,crs,cnt))
#main program
print("--------------------------------------------------------------------")
print("\tStudent Information:")
print("-------------------------------------------------------------------")
print("\tstno\tName\t\tMarks\tCourse\tCountry")
print("--------------------------------------------------------------------")
dispstuddet(10,"Chaitanya",34.56)
dispstuddet(20,"Manasa ",24.56)
dispstuddet(30,"Minakshi",84.56)
dispstuddet(40,"Adarsh ",14.56,"Java")
dispstuddet(50,"Rossum ",11.56)
dispstuddet(60,"Ritche ",14.56,"C","USA")
dispstuddet(70,"Travis ",17.56,"DS")
print("-------------------------------------------------------------------")

#[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()

3) Keyword Parameters (or) arguments


=>In some of the circumstances, we know the function name and formal parameter names and we don't know
the order of formal Parameter names and to pass the data / values accurately we must use the concept of
Keyword Parameters (or) arguments.
=>The implementation of Keyword Parameters (or) arguments says that all the formal parameter names used as
arguments in Function call(s) as keys.
Syntax for function definition:-
def functionname(param1,param2...param-n):
---------------------------------------------
---------------------------------------------
Syntax for function call:-
functionname(param-n=val-n,param1=val1,param-n-1=val-n-1,......)
Here param-n=val-n,param1=val1,param-n-1=val-n-1,...... are called Keywords arguments

4) Variables Length Parameters (or) arguments


=>When we have familiy of multiple function calls with Variable number of values / arguments then with normal
python programming, we must define mutiple function defintions. This process leads to more development
time. To overcome this process, we must use the concept of Variable length Parameters .
=>To Impelement, Variable length Parameters concept, we must define single Function Definition and takes a
formal Parameter preceded with a symbol called astrik ( * param) and the formal parameter with astrik symbol
is called Variable length Parameters and whose purpose is to hold / store any number of values coming from
similar function calls and whose type is <class, 'tuple'>.
Syntax for function definition with Variables Length Parameters:
def functionname(list of formal params, *param) :
--------------------------------------------------
--------------------------------------------------
Print by VIKASH Page no -81
=>Here *param is called Variable Length parameter and it can hold any number of argument values (or) variable
number of argument values and *param type is <class,'tuple'>

=>Rule:- The *param must always written at last part of Function Heading and it must be only one (but not multiple)
=>Rule:- When we use Variable length and default parameters in function Heading, we use default parameter
as last and before we use variable length parameter and in function calls, we should not use default
parameter as Key word argument bcoz Variable number of values are treated as Posstional Argument
Value(s)

==================================================
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("--------------------------------------------")

Print by VIKASH Page no -83


EXAMPLE 2
#[Link]
posop = lambda n : n>0 # anonymous function
negop=lambda n:n<0 # anonymous function
#main program
lst=(10,20,-40,-56,0,23,-67,89,-25,45)
filtobj=filter(posop,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(negop,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("--------------------------------------------")

EXAMPLE 5 #Program for obtaining even and odd from list


#[Link] of values by using filter()
#read the elements dynamically
# program filtering Postive and Negative
numbers by using filter() #[Link]
print("Enter the values separated by comma:") print("------------------------------------------------")
lst=[int (val) for val in input().split(",")] print("Enter List of Values separated by
print("--------------------------------------------") space:")
print("Original Elements=",lst) lst=[int (val ) for val in input().split()]
print("--------------------------------------------") #filter even elements
pslst=list(filter(lambda n : n>0, lst)) evenlst=list(filter(lambda n: n%2==0, lst))
nslst=tuple(filter(lambda n : n<0, lst)) oddlst=list(filter(lambda n: n%2!=0, lst))
print("Possitive elements=",pslst) print("------------------------------------------------")
print("--------------------------------------------") print("Original List={}".format(lst))
print("Negative elements=",nslst) print("Even numbers List={}".format(evenlst))
print("--------------------------------------------") print("Odd numbers List={}".format(oddlst))
print("------------------------------------------------")
Print by VIKASH Page no -84
2) map()
=>The purpose of map() is that " To get new list from old list by applying to the function "
=>Syntax:- varname=map(Function_name, Iterable_object)
Explanation:
=>'varname' is an object of <class, 'map'> and we can convert into any
iterable_object type.
=>"Function_name" is either normal function and anonymous function and it must
perform some operation based on logic
=>"Iterable_object " can be any Sequence type or collection types.
=>Execution Process of map() is that "map() applies each value of iterable object to the function
and gets new iterable object. "
-----------------------------------------------------------------------------------------------------
My Requirement: oldsals=[10,20,10,30,40]---from old list
decided to give 10% hike

newsals=[11,22,11,33,44]----new list

#[Link]
def hike(esal):
esal=esal+esal*0.1
return esal

#main program #[Link]


print("Enter Old Salaries of employees:") hikesal=lambda esal : esal+esal*0.1
oldsal=[ int(sal) for sal in input().split()]
mapobj=map(hike,oldsal) #main program
print("Type of map obj=",type(mapobj))# Type print("Enter Old Salaries of employees:")
of map obj= <class 'map'> oldsal=[ int(sal) for sal in input().split()]
print("content of map=",mapobj) # content of newsal=tuple(map(hikesal,oldsal))
map= <map object at 0x000002102AF0F0D0> print("---------------------------------------")
newsal=list(mapobj) print("Old Salaries=",oldsal)
print("---------------------------------------") print("New Salaries=",newsal)
print("Old Salaries=",oldsal) print("---------------------------------------")
print("New Salaries=",newsal)
print("---------------------------------------")

#[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)

Print by VIKASH Page no -85


#[Link]
print("Enter Salaries of employees:")
sallist=[ int(sal) for sal in input().split()]
newsallist1=list(map(lambda sal:sal*1.1,list(filter(lambda sal : sal>10000,sallist)) ))
newsallist2=list(map(lambda sal:sal*1.2,tuple(filter(lambda sal:sal<=10000,sallist)) ))
print("Old Salaries :{}".format(sallist))
print("New Salaries having >10000:{}".format(newsallist1))
print("New Salaries having <=10000:{}".format(newsallist2))

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.

Internal flow of reduce()


Step-1) reduce() selects First two element of any iterable object and place them First variable and Second Variable( say K and V )
Step-2) reduce() applies the First and Second Variable values to the function and computed and Resultant Value placed in First Variable
(say K).
Step-3) reduce() select next succeding element from Iterable object and place it into second Variable (say V)
Step-4) Repeate Step-(2) and Step-(3) until all elements of iterable object completed
Step-5) reduce() automatically Returns Result of First Variable ( Say K)

#[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("---------------------------------------------")

Print by VIKASH Page no -86


============================================
global and local variables and globals()
============================================

=>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)

#cal si Example 2:-


si=(p*t*r)/100 #[Link]---file name and acts as module name
totamt=p+si PI=3.14
print("-"*50) E=2.71 # here PI and E are called Global Variables
print("Simple Interest Details:")
print("-"*50)
print("Principle Amount:{} ".format(p))
Print by VIKASH Page no -88
Example 3:- Example 4:-
#[Link] #[Link]
from formula import simpleint,hello from mathsinfo import PI,E
simpleint() # function call print("Val of PI={}".format(PI))
hello("kVR") print("Val of E={}".format(E))

==========================================
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.

1) by using import statement.


=>here 'import' is a keyword
=>import statement is used for referring the Variables Names, Function names and class names of a
module .

Syntax1:- import module name


=>This syntax imports single module name
Examples: import formula
import mathsinfo

Syntax2:- import modulename1, modulename2,...modulename-n


=>This syntax imports multiple module names
Examples: import formula, mathsinfo

Syntax-3:- import modulename as alias name


=>This syntax imports single module name with ailas name
Examples: import formula as f
import mathsinfo as m

Syntax4:- import modulename1 as alias name1, modulename2 as alias name-2


,...modulename-n as alias name-n
=>This syntax imports multiple module names with alias names.
Examples: import formula as f, mathsinfo as m

=>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

2) by using from.... import statement:


=>here 'form' , 'import' are the keywords
=>This approach also used for re-using the variable names, function names and class names of a
particular modules in the current python program
Syntax1:
=> import module name as variable names,function names, class names
=>This syntax imports the variables names, function names and class names from a specified module name.
Examples:- from hyd import stateinfo,capinfo,hello,show
Print by VIKASH Page no -89
Syntax2:-
=> import module name as variable names as alias names, function names as alias names , class
names as alias names.
=>This syntax imports the variables names, function names and class names from a specified module
name with alias names.
Examples:-
from hyd import stateinfo as sf1,capinfo as cf1,hello as h1,show as s1
from bang import stateinfo as sf2,capinfo as cf2,hello as h2,show as s2

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()

Print by VIKASH Page no -90


#[Link] #[Link]
import formula import formula, mathsinfo
import mathsinfo [Link]()
[Link]() print("subject =",formula.sub1)
print("val of pi=",[Link]) print("val of pi=",[Link])
print("val of e=",mathsinfo.E) print("val of e=",mathsinfo.E)
print("subject =",mathsinfo.sub1)

#[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

#[Link]-----------main program #[Link]--------------file name and treated as module name


from menuop import menu def addop():
import sys a=float(input("Enter First Value for Addition:"))
from arithop import * b=float(input("Enter Second Value for Addition:"))
while(True): print("\tsum({},{})={}".format(a,b,a+b))
menu()
ch=int(input("Enter Ur Choice:")) def subop():
match ch: a=float(input("Enter First Value for Substraction:"))
case 1: b=float(input("Enter Second Value for Substraction:"))
addop() print("\tsub({},{})={}".format(a,b,a-b))
case 2: main program
subop() def mulop():
case 3: p=float(input("Enter First Value for Multiplication:"))
mulop() q=float(input("Enter Second Value for Multiplication:"))
case 4: print("\tmul({},{})={}".format(p,q,p*q))
divop()
case 5: def divop():
modop() p=float(input("Enter First Value for Division:"))
case 6: q=float(input("Enter Second Value for Division:"))
expoop() print("\tDiv({},{})={}".format(p,q,p/q))
case 7: print("\tFloor Div({},{})={}".format(p,q,p//q))
print("Thanks for Using this App!")
[Link]() def modop():
case _ : a=float(input("Enter First Value for Modulas :"))
print("Ur Selection of Operation is b=float(input("Enter Second Value for Modulas:"))
wrong-try again") print("\tmod({},{})={}".format(a,b,a%b))

def expoop():
a=float(input("Enter Value for Base:"))
b=float(input("Enter Value for power:"))
print("\texp({},{})={}".format(a,b,a**b))

Print by VIKASH Page no -91


#[Link]----file name and treated as module name
def menu():
print("-"*50)
print("\tArithmetic Operations")
print("-"*50)
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\t4. Division")
print("\t5. Modulo Division")
print("\t6. Exponentiation")
print("\t7. Exit")
print("-"*50)

==========================================
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().

#[Link]---file and treated as module name


def sharesinfo():
d={"Tech":19,"Pharma":11,"Auto":1,"Finance":00}
return d

#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)

Number of approaches to re-use the modules of Packages


=>We have two approaches re-use the modules of Packages. They are
1) By using [Link]()
2) By using PYTHONPATH Environmental Variable.

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()

2) By using PYTHONPATH Environmental Variable.


=>PYTHONPATH is one of the keyword for OS and hence it is called Environmental Variable.
=>To set PYTHONPATH, do th the follwing steps
a) Goto start button
b) choose Settings
c) Choose System
d) Search for "environmental Variables"
e) choose "new"
f) Type PYTHONPATH for Variable Name
g) Place Absolute path of package as Variable Value
h) Choose OK and OK
----------------------------------
Later Execute the program freshly.

====================================
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

a) Compile Time Errors:


=> Compile Time Errors are those, which are occurring at Compile Time (.py--->.pyc)
(.py
=> Compile Time Errors are occuring due to Syntaxes are not folowed by the Programmer.
=>These erros solved by Programmers at development Level.

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

3) Definition of exception:- Every Runtime error is called Exception


(Invalid Input--->Runtime Error--->Exception)
4) Every exception by default gives Technical Error Message.

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.

1. Pre-defined / Built-in exceptions:


=>Pre-defined / Built-in exceptions are developed By Python Language Developers and they are
available in Python API(Library)and whose role is to deal with Universal Problems.
=>Some of the Universal Problems are
a) Division by Zero Problems ( ZeroDivisionError)
b) Invalid number formats ( ValueError)
c) Invalid arguments / Operations (TypeError)
d) searching the value of value in in dict
by passing invalid key (KeyError)
e) Invalid Variable Names (NameError)......etc

2. Programmer / User / Custom-defined Exceptions.


=>These exceptions developed by Programmer and they are avalible in Python Project and they used
used for dealing with Common Problems.
=>Some of the Common Problems are
a) Attempting to enter invalid PIN in atm applicatioins.
b) Attempting to Wrong User Name and Password.
c) Attempting to withdraw Invalid amount from existing account
..........................etc
=>Every Valid Input gives successful output
=>Every Invalid Input gives Exceptions.

Print by VIKASH Page no -95


===========================================
Handling the exceptions in Python
===========================================
=>Handling the exceptions in Python are nothing but converting Technical error messages into User-Friendly
Error Messages.
=>To convert Technical error messages into User-Friendly Error Messages, we have 5 keywords. They are
1) try
2) except
3) else
4) finally
5) raise

=>Syntax for handling the exceptions:


try:
Block of statements
Generating Exceptions
except <exception-class-name-1>:
Block of statements
generating User-Friendly Error Messages
except <exception-class-name-2>:
Block of statements
generating User-Friendly Error Messages
-------------------------------------------
except <exception-class-name-n>:
Block of statements
generating User-Friendly Error Messages
else:
Block of statements
generating Result of the Program
finally:
Block of statements
executed by PVM Compulsorily

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

#This Program demonstartes how to cal division of


two numbers
#by accepting two integer values from KBD #by accepting two integer values from KBD
#[Link] #[Link]
try: try:
s1=input("Enter First Value:") s1=input("Enter First Value:")
s2=input("Enter Second Value:") s2=input("Enter Second Value:")
a=int(s1),b=int(s2) a=int(s1),b=int(s2)
c=a/b c=a/b
except ZeroDivisionError: except (ZeroDivisionError,ValueError):
print("\nDON'T ENTER ZERO FOR DEN...") print("\nDON'T ENTER ZERO FOR DEN...")
except ValueError: print("\nDON'T ENTER strs/symbols/alpha-numeric values:")
print("\nDON'T ENTER strs/symbols/alpha numeric values:") else:
else: print("\nResult---else block")
print("\nResult---else block") print("-"*50)
print("-"*50) print("Val of a={}".format(a))
print("Val of a={}".format(a)) print("Val of b={}".format(b))
print("Val of b={}".format(b)) print("Div={}".format(c))
print("Div={}".format(c)) print("-"*50)
print("-"*50)
finally: finally:
print("\ni am from finally block") #This Program print("\ni am from finally block") #This Program
demonstartes how to cal division of two numbers demonstartes how to cal division of two number

Print by VIKASH Page no -98


#by accepting two integer values from KBD #by accepting two integer values from KBD
#[Link] #[Link]
try: try:
s1=input("Enter First Value:") s1=input("Enter First Value:")
s2=input("Enter Second Value:") s2=input("Enter Second Value:")
a=int(s1) a=int(s1),b=int(s2)
b=int(s2) c=a/b
c=a/b s="PYTHON"
except ZeroDivisionError as k: print(s[10])
print(k) # division by zero except ZeroDivisionError: # specific except block
except ValueError as v: print("\nDON'T ENTER ZERO FOR DEN...")
print(v) # invalid literal for int() with base 10: except ValueError: # specific except block
'abc' print("\nDON'T ENTER strs/symbols/alpha-
else: numeric values:")
print("\nResult---else block") except IndexError: # specific except block
print("-"*50) print("Plz check the index :")
print("Val of a={}".format(a)) except : # default except block
print("Val of b={}".format(b)) print("exception occurs---Some went wrong!")
print("Div={}".format(c)) else:
print("-"*50) print("\nResult---else block")
finally: print("-"*50)
print("\ni am from finally block")#This Program print("Val of a={}".format(a))
demonstartes how to cal division of two numbers print("Val of b={}".format(b))
print("Div={}".format(c))
finally:
print("\ni am from finally block")#This Program
demonstartes how to cal division of two numbers

#by accepting two integer values from KBD


#[Link]
try: print("\nDON'T ENTER strs/symbols/alpha-
s1=input("Enter First Value:") numeric values:")
s2=input("Enter Second Value:")
a=int(s1) except IndexError: # specific except block
b=int(s2) print("Plz check the index :")
c=a/b except BaseException: # default except block
s="PYTHON" print("exception occurs---Some went wrong!")
print(s[10]) else:
except ZeroDivisionError: # specific except block print("\nResult---else block")
print("\nDON'T ENTER ZERO FOR DEN...") print("-"*50)
except ValueError: # specific except block print("Val of a={}".format(a))
print("Val of b={}".format(b))
print("Div={}".format(c))
print("-"*50)
finally:
print("\ni am from finally block")

Print by VIKASH Page no -99


=============================================
Various forms of except blocks
=============================================

Form-1 (Handling One Exception at a time):


try:
blcok of statements
generating exceptions
except <Exception-Class-Name>
Block of statements
generating user frinedly error Messages

Form-2 (Handling Multiple Exception at a time--multi exception handling block):


try:
blcok of statements
generating exceptions
except (exception class name-1, exception class name-2.. exception class name-n)
Block of statements
generating user frinedly error Messages

Form-3: (Handling Multiple Exception with alias name)


=>With this Syntax, we are obtaining messages causing due to exception occurence
try:
blcok of statements
generating exceptions
except <Exception-Class-Name-1> as <alias-name-1>
Block of statements
generating user frinedly error Messages
except <Exception-Class-Name-2> as <alias-name-2>
Block of statements
generating user frinedly error Messages
---------------------------------------------------
---------------------------------------------------
except <Exception-Class-Name-n> as <alias-name-n>
Block of statements
generating user frinedly error Messages

Form-4: (Handling Multiple Exceptions with deafult except block)


try:
blcok of statements
generating exceptions
except :
Block of statements
generating user frinedly error Messages
NOTE:- Industry is always recommended to write default except block after specific except blocks but
before spefic except blocks.

Form-5: (Handling Multiple Exceptions with Base class exception)


try:
blcok of statements
generating exceptions
except Exception :
Block of statements
generating user frinedly error Messages

Print by VIKASH Page no -100


===================================================
Development
of
Programmer / User / Custom-defined Exceptions.
===================================================
=>These exceptions developed by Programmer and they are avalible in Python Project and they used used for
dealing with Common Problems.
=>Some of the Common Problems are
a) Attempting to enter invalid PIN in atm applicatioins.
b) Attempting to enter Wrong User Name and Password.
c) Attempting to withdraw Invalid amount from existing account
..........................etc
=>Every Valid Input gives successful output
=>Every Invalid Input gives Exceptions.

Steps for developing Programmer-defined Exceptions:


1) Choose the Programmer-Defined Class Name
2) The Programmer-Defined Class Name must inherit Either from "Exception" or
BaseException for obtaining exception handling features.
3) Save the above development on some filename with an extension .py ( treated as module name)

Examples: Examples:
# [Link]----------(3) #[Link]--------(3)
(1) (2) (1) (2)
class PinError(Exception):pass class LoginError(BaseException):pass

We follow 3 phases for development of Programmer-defined exception. They are


a) Develop Programmer-defined Exception classes
b) Hit / Generate the Programmer-defined Exceptions (raise )
c) Handle the Programmer-defined exceptions(try,except, else, finally)

a) Develop Programmer-defined Exception classes


Example:
#Phase-I--Development Programmer-defined Exception
#[Link]---file name and treated as module name
class KvrDivisionError(Exception):pass

b) Hit / Generate the Programer-defined Exceptions (raise )


Example:
#Phase-II: Hitting the exception by using raise keyword.
#program cal of division of two numbers
#[Link]---file name and treated as module name
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError # hitting / generating Programmer-defined exception
else:
c=a/b
return c
c) Handle the Programmer-defined exceptions(try,except, else, finally)

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

Print by VIKASH Page no -102


=========================================
Introduction to Files
=========================================
=>The purpose of Files in any programming Language is that "To Store the data Permanently (Data Persistency )".
=>Def. of File:
:- A File is a collection of Records.
=>Def. of Stream:
:- The flow of Data between Main memory and secondary memory is called Stream.
=>All the objects data of main memory can be stored permanently in the form of Files of Secondary memory
and Records of file of Secondary Memory will become objects in Main Memory.

======================================
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

Print by VIKASH Page no -103


=========================================
Types of Files in Python
=========================================
=>In Python, we have two types of Files. They are
1) Text Files
2) Binary Files

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.

2) By using " with open() as "


Syntax:-
with open("File Name", "File Mode") as <varname>:
-------------------------------------------------
-------------------------------------------------
Block of Statements--Operation
------------------------------------------------
------------------------------------------------

Other Statements in Python Program


-----------------------------------------------------------
Explanation:
=>"with" and " as " are keywords
=>open() is a function used to open the file in specified 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>.
=>The main advatange of this syntax is that It provides auto-closable of files. In otherwords, we need not
to close any files explicitly.

#This program demonstrates opening the file in


read mode
#[Link]
try:
fp=open("[Link]", "r") #This program demonstrates opening the file in
print("type of fp=",type(fp)) # type of fp= <class write mode
'_io.TextIOWrapper'> #[Link]
print("File Opened in read mode successfully") kvr=open("[Link]", "x")
except FileNotFoundError: print("File Opened in write mode successfully--verify")
print("File does not exists:")
Print by VIKASH Page no -105
#[Link]
with open("[Link]","a") as fp: #[Link]
[Link]("Dennis Ritche\n") lst=[10,"Rutuja",88.88,"OU"]
[Link]("FNO:130,,Fort Side\n") with open("[Link]","a") as fp:
[Link]("Bell Labds \n") [Link](str(lst)+"\n")
[Link]("USA\n") print("Data written to the file")
print("\nData Written to the File:")

#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]))

Print by VIKASH Page no -106


#This program demonstrates for obtaining the print("Line--10: is file
information about files. closed={}".format([Link]))
#[Link]----- with open() as print("-"*40)
try: print("\nLine--14: is file closed after out of 'with
with open("[Link]","r+") as fp: open()' ={}".format([Link]))
print("-"*40) except FileNotFoundError:
print("File opened Successfully in read mode") print("File does not exists:")
print("-"*40) finally:
print("Mode used={}".format([Link])) print("\nI am finally block:")
print("Is readable={}".format([Link]())) print("Line--19: is file closed
print("Is writable={}".format([Link]())) ={}".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")

Print by VIKASH Page no -107


========================================
Reading the Data from the Files
========================================
=>To read the data from the files , we have 4 pre-defined Functions which are present in an object of
TextIoWrapper . They are
1) read()
2) read([Link] chars)
3) readline()
4) readlines()

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:")

Print by VIKASH Page no -109


=======================================
Random Access Files
=======================================
=>Random Access Files are those which allows us to read the data randomly accoding to programmer choice.
=>To read the data randomly, we have two pre-defined functions present in TextIoWrapper. They are
a) tell()
b) seek()

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]

Print by VIKASH Page no -110


==================================================
Pickling and Un-Pickling
(OR)
Object Serialization and Deserialization
==================================================

Pickling ( Object Serialization ):


=>Let us assume, there exist an object in mamin memory and it contains multiple values. To save / write the
object data into the file of secondary memory by using write() and writelines() , internally these functions will
write Value by Value and it is considered as Time Consuming Process . To overcome this problem, we must
another concept called "PICKLING"
=>The Advantage of Pickling concept is that with single write operation, we can write / save the entire object
data into the file of secondary memory.

=>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.

=>Steps for implementing Pickling Concept:


Step-1: import pickle module
step-2: Create an object with data
Step-3: use dump() of pickle module for writing entire object content into the file of secondary memory.
Syntax: [Link](object, filepointer)

Un-Pickling(( Object De-Serialization ):


=>Let us assume there exist a record in the file of secondary Memory. To read the record data from the file by using read(),
read([Link] chars), readline() and realines(), Internally these functions reads value by value and it is considered as Time
Consuming [Link] overcome this process, we must use the concept of UN-PICKLING".
=>The advantage of un-pickling concept is that with single read operation, we can read entire record data from
the file of secondary memory.

=>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.

Steps for implementing Un-Pickling Concept:


Step-1: import pickle module
Step-2: use load() of pickle module , for reading entire object content into the object of main memory
Syntax: objectdata=[Link]()
Step-3: Display object data (De-serialized data)
=>hence Pickling and Un-pickling concepts Enhaces the performnace of Normal File Programming of Python.
=>To deal with Pickling and Un-pickling concepts , we use a pre-defined module "pickle".

#This Program copy the image ([Link]) into another image.


#[Link]
def saveimage():
try:
with open("D:\KVR-PY\[Link]","rb") as rp: print("File does not exists:")
with open("C:\PIC\\[Link]","wb") as wp:
fileimg=[Link]()
[Link](fileimg) #main program
print("\nImage Copied---Verify:") saveimage()
except FileNotFoundError:

Print by VIKASH Page no -111


#[Link]-----Program-(A)
#This Program reads employee data from KBD and
Save employee data into the file
import pickle
noe=int(input("Enter How Many Employee Data u have:"))
if(noe<=0): #[Link]-------------Program-(B)
print("{} is invalid Input".format(noe)) #This program reads the employee records from
else: the file
with open("[Link]","ab") as fp: import pickle
for i in range(1,noe+1): try:
print("-"*40) with open("[Link]","rb") as fp:
print("Enter {} Employee Information:".format(i)) print("-"*40)
print("-"*40) print("\tE m p l o y e e D e t a i l s")
#accept employee from KBD print("-"*40)
eno=int(input("Enter Employee Number:")) while(True):
ename=input("Entyer Employee Name:") try:
sal=float(input("Enter Employee Salary:")) record=[Link](fp)
#create an empty list and append data for val in record:
print("\t{}".format(val),end="")
lst=list()
print()
[Link](eno)
except EOFError:
[Link](ename)
print("-"*40)
[Link](sal)
break
#save lst data into the file
except FileNotFoundError:
[Link](lst,fp)
print("File does not exists:")
print("-"*40)
print("{} employee record saved successfuly in
file:".format(i))

#[Link]-----Program-(A) print("Thanks for using this Application:")


#This Program reads student data from KBD and break
Save student data into the file except ValueError:
import pickle print("\nDon't Enter strs/alpha-numeric vals /
def savestuddata(): symbols for stno and marks:")
with open("[Link]","ab") as fp: #main program
#accepting student data from KBD savestuddata()
while(True):
print("-"*50) #[Link]-------------Program-(B)
try: #This program reads the student records from the
sno=int(input("Enter Student Number:")) file
sname=input("Enter Student Name:") import pickle
marks=float(input("Enter Student Marks:")) def readstudrecord():
print("-"*50) try:
#create an empty list and append with open("[Link]","rb") as fp:
lst=[] print("-"*40)
[Link](sno) print("\tS t u d e n t I n f o r m a t i o n:")
[Link](sname) print("-"*40)
[Link](marks) while(True):
#save lst data into the file try:
[Link](lst,fp) rec=[Link](fp)
print("-"*50) for val in rec:
print("\nStudent Data Saved Successfully in a file:") print("\t{}".format(val), end="")
print("-"*50) print()
usrchoice=input("\nDo u want to Insert except EOFError:
another record(yes/no):") print("-"*40)
if(usrchoice=="no"): break
print("Thans for using this Application:") except FileNotFoundError:
break print("File does not exists")
if(usrchoice!="yes"):
print("\nU Please Learn Typing!") #main program
readstudrecord()
Print by VIKASH Page no -112
=====================================
OS Module in Python
=====================================
=>"os" is one of the pre-defined module in python
=>The Purpose of "os" module is that "To interact with Operating System and Performs Some Operations with OS".
=>Some of the Operation , we do on Operating System are
a) obtaining Current Working Folder
b) Creating a Folder
c) Creating Root Folder, Sub Folder, sub-sub folder..etc
d) Removing Folder
e) Removing Root Folder, Sub Folder, sub-sub folder..etc
f) list the files of Folders.
g) renaming the folder.

a) obtaining Current Working Folder/ Directory:


=>To get Current Working Folder, we use a pre-defined Function called getcwd(), which is present in os module.
Syntax:- varname=[Link]()
Examples:
#[Link]
import os
cwdname=[Link]()
print("\nCurrent Working Folder=", cwdname)

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")

c) Creating Root Folder, Sub Folder, sub-sub folder..etc


=>To create Root Folder, Sub Folder, sub-sub folder..etc(Folders Hierarchy) , we use a pre-defined function
makedir() of os module.
=>Folders Hierarchy represents Root Folder, Sub Folder, sub-sub folder..etc
=>This Function gives FileExistsError when folders Hierarchy already exists.
Syntax:- [Link]("Folders Hierarchy")
Example:
#[Link]
import os
try:
[Link]("C:\India\Hyd\Ampt\Python")
print("Folders Hierarchy Created--verify")
except FileExistsError:
print("\nFolders Hierarchy already Created:")

Print by VIKASH Page no -113


d) Removing Folder:
=>To remove a folder, we use rmdir() of os module.
=>This Function remove at a time only one folder but it can't remove folders hierarchy.
=>If we try to remove a folder and if it does not exists then we get FileNotFoundError.
=>rmdir() can't remove a folder when that folder contains some files and we get OSError.
Syntax:- [Link]("Folder Name")
Examples:
#[Link]
import os
try:
[Link]("G:\KVR-PYTHON-7AM\FILES")
print("Folder removed / deleted:")
except FileNotFoundError:
print("Folder Does not exists:")
except OSError:
print("Folder contains some files-u can't remove")

e) Removing Root Folder, Sub Folder, sub-sub folder..etc


=>To remove Root Folder, Sub Folder, sub-sub folder..etc( Folders Hierarchy) , we use removedirs() of os module.
=>Folders Hierarchy represents Root Folder, Sub Folder, sub-sub folder..etc
=>If Folders Hierarchy does not exists then we get FileNotFoundError
=>If any folder in Folders Hierarchy contains some file then we get OSError.
Syntax:- [Link]("Folders Hierarchy")
Examples:
#[Link]
import os
try:
[Link]("C:\India\Hyd\Ampt\Python\KVR")
print("Folders Hierarchy removed--verify")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folder in Folder Hierachy conatins some file--so we can't remove")

f) list the files of Folders.:


=>To list the files of the folders, we use listdir() of os module and all files are available in the form of list object
=>if the folder name does not exists then we get FileNotFoundError
Syntax:- varname=[Link]("FolderName")
Examples:
#[Link]
import os print("\t{}".format(name))
try:
lst=[Link]("G:\KVR- except FileNotFoundError:
PYTHON-8PM\MODULES") print("File does not exists")
for name in lst:

g) renaming the folder.


=>To rename a folder, we use rename() of os module.
=>If the Existing Folder Name is not present then we get FileNotFoundError.
Syntax: [Link]("Existing Folder Name", "New Folder Name")
Examples:
#[Link]
import os
try:
[Link]("C:\Dev","C:\INDIA")
print("Folder Re-named--verify")
except FileNotFoundError:
print("File does not exists")

Print by VIKASH Page no -114


Python Database Communication(PDBC)

Index :-

=> Limitation Of Files.


=> Why We Need Python Database Communication.
=> Installing Modules Of PDBC.
=> Step For Developing PDBC Application.
=> What Is Query.
=> Type Of Queries
DDL
DML
DRL
=> Programming Examples.

==========================================
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

=>The advantages of RDBMS Database softwares are


1) Database softwares are fully secured bcoz RDBMS Database softwares provides User Names and Password.
2) The Database is oranizing the Data in the form of tables with Column Names. So that it is very eazy to
process the data. In otherwords, Database softwares provides eazy the Process the data
3) The database softwares stores large volume of Data.
4) The architecture of Data never differ from One OS to another OS.
Print by VIKASH Page no -115
=>Any Python Program to communicate with any Database softwares, we need a pre pre-defined module and the
module related database are not inbuilt modules in Python Softwares and They are available iin GitHub and
we must install those database relatated modules explicitly by using a tool called "pip", which is present
python software.
=>In otherwords, pip is a tool used for installing the modules explicitly .
=>Syntax:- pip install M Module Name.
Example:-
=>If a Python Program want to communicate with Oracle Database softwares then we must install
cx_Oracle module( from Dos / Windows command prompt)
pip install cx_Oracle
=>If
If a Python Program want to communicate with MYSQL Database softwares then we must install
mysql-connector
connector module( from Dos / Windows command prompt)
pip install mysql-connector
connector

Print by VIKASH Page no -116


==========================================================================
Steps for developing Python Database Communication Application with Oracle
==========================================================================

=>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

2) Every Python must establish the connection from Oracle databse


=>If a Python Programmer want to perform different database operations then first we must get a connection
from Oracle database.
=>To get the connection from Oracle Database, we must use a pre-defined function called "connect()" , which is
present in cx_Oracle module and it returns an object of <class, 'cx_Oracle.Connection'>
Syntax:- varname= cx_Oracle.connect("username/password@DNS/serviceid")
=> Here "username/password@DNS/serviceid" is called Connection URL
=> here "username" repersents user name of Database
=> here password represents of Database
=> Here "DNS"(Domain Naming Service) represents Name of the machine where the Data base software installed.
=> The default DNS of every computer is "localhost"
=> Here In Place of DNS, we can also use IP Address( Internet Protocal Address) and it always Address
of the machine where Database software installed.
=> The default IP address of every computer is [Link](loop back address)
=> "serviceid" represents on which name Oracle database is available in current working machine.
=> here "varname" represents an object of <class, 'cx_Oracle.Connection'>

Note:- To find serviceid of Oracle database, we must use the following.


SQL> select * from global_name;
GLOBAL_NAME
---------------------------- NOTE
ORCL <------Service id
----------------------------

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)

Print by VIKASH Page no -117


#This
This Program demonstartes how to get the connection from Oracle DB
#[Link]
import cx_Oracle # Step--1
try:
con=cx_Oracle.connect("scott/tiger@[Link]/orcl") # step-2
print("\nPython
nPython Program obtained Connection from Oracle DB")
print("Type of con=",type(con)) # Type of con= <class
class 'cx_Oracle.Connection'>
except cx_Oracle.DatabaseError as db:
print("Connection Problem:",db)

3) Create an object of Cursor:


=>"Cursor" is a pre-defined
defined class present in cx_Oracle Module.
=>The
The purpose of Cursor class object is that "It Carry the Query from Python Program and brings the result from
Oracle Database and Hand Over to Python Program. Hence an object of Cursor acts as a driver / mediator /
middleware layer between Python program and Database Software.
=>Programatically, To create an object of Cursor class, we use cursor(), which is present in a class <class,
'cx_Oracle.Connection'>.
Syntax:- varname=[Link]()
here "varname" is an object of class <clas
<class,"cx_Oracle.Cursor">
Examples:: kvrcur=[Link]()
print("Cursor object Created")
print("type of kvrcur=",type(kvrcur))
kvrcur=",type(kvrcur))---<class,"cx_Oracle.Cursor">
<class,"cx_Oracle.Cursor">

#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.

Print by VIKASH Page no -118


=======================================
Types of Queries in Database Softwares
=======================================
=>A Query is a request / Question to the database from Python Program to perform Certain database operation.
=>In Database Softwares, we 3 types of Queries. They are
1. DDL (Data Definition Language) Queries
a) create b) alter ( add , modify)
c) drop
2. DML (Data Manipulation Language) Queries
a) insert b) delete
c) update
3. DRL(Data Retrieval Language) Queries
a) select

1. DDL (Data Definition Language) Queries:


=>The purpose of DDL Queries is that "To deal with designing of Tables (or) Structure of the Tables."
=>We have 3 types of DDL Queries. They are
a) create
b) al
alter
c) drop
a) create:-
=>"create" command is used for creating a table
Syntax(Oracle )
SQL> create table <table
<table-name>(col1
name>(col1 datatype, col2 data type.....col-n
type.....col data type)
Example(Oracle):
SQL> create table student(stno number(2) primary key, name varchar2(15) not null, marks number(5,2) not null );

=>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)

Print by VIKASH Page no -119


b) alter :-
=>This command is used for altering / Changing (or) adding the new column names or modifying the
column sizes of the table
Syntax:(Oracle):
SQL> alter table <table-name> modify ( existing col name data type...)
and
SQL> alter table <table-name> add ( new col name data type...)
Examples(Oracle):
SQL> alter table student modify(stno number(3));
SQL> alter table student add(cname varchar2(10));

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;

#This program demonstartes how to drop the table


#[Link]
import cx_Oracle
try:
con=cx_Oracle.connect("scott/tiger@[Link]/orcl")
cur=[Link]()
[Link]("drop table employee")
print("Employee Table droped--verify")
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)

2. DML (Data Manipulation Language) Queries


=>The purpose of DML Operations is that "To maniplate the records of the table such as inserting the records,
deleting the records and updating the records".
=>We have 3 types of DML Operations. They are
a) insert
b) delete
c) update
=>After executing any DML Query , we must commit (Permanent Changes) by using a pre-defined function
called commit() which is present in class,'cx_Oracle.connection'>

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)

#This program inserts an employee record in employee table--with Dynamic data


#[Link]
import cx_Oracle #step-1
def empinsert():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") #step-2
cur=[Link]() #step-3
#accept employee data from KBD
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
#design the query and execute --step-4
iq="insert into employee values(%d,'%s',%f) "
[Link](iq %(eno,ename,sal))
[Link]()
# (OR) [Link]("insert into employee values(%d,'%s',%f)" %(eno,ename,sal) )
print("{} employee record Inserted Sucessfully".format([Link]))
except cx_Oracle.DatabaseError as db:
print("Prob in inserting the data..",db)

#main program
empinsert()

#This program inserts an employee record in employee table--with Dynamic data


#[Link]
import cx_Oracle #step-1
def empinsert():
while(True):
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") #step-2
cur=[Link]() #step-3
#accept employee data from KBD
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
#design the query and execute --step-4
iq="insert into employee values(%d,'%s',%f) "
[Link](iq %(eno,ename,sal))
[Link]()
# (OR)[Link]("insert into employee values(%d,'%s',%f)" %(eno,ename,sal) )
print("{} employee record Inserted Sucessfully".format([Link]))
except cx_Oracle.DatabaseError as db:
print("Prob in inserting the data..",db)
except ValueError:
print("Don't enter strs / symbols/ alpha-numerics for emp numbers / salaries")
Print by VIKASH Page no -121
ch=input("Do U want to Insert another record:(yes/no):")
if(ch=="no"):
break
#main program
empinsert()

b) delete:-
=>This command is used for deleting a record from a table.
=>Syntax(Oracle):-
Syntax1:- delete from <table-name> ;

Syntax2:- delete from <table-name> where condition;

#this program accept employee number and remove the record


#[Link]
import cx_Oracle,sys
def empdelete():
while(True):
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
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 cx_Oracle.DatabaseError as db:
print("Problem in deleting the record:",db)
except ValueError:
print("Don't enter strs / symbols/ alpha-numerics for emp numbers")
ch=input("Do u want to delete another record(yes/no):")
if(ch=="no"):
print("\nThanks for using program:")
[Link]()

#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;

=>Syntax2: update <table-name>


set col1=val1,col2=val2.....col-n=val-n
where cond-list;

Print by VIKASH Page no -122


#this program accept employee number and update the salary Verify".format([Link]))
#[Link] else:
import cx_Oracle,sys print("Record Does not exists:")
def empupdate(): except cx_Oracle.DatabaseError as db:
while(True): print("Problem in updating the record:",db)
try: except ValueError:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") print("Don't enter strs / symbols/ alpha-
cur=[Link]() numerics for emp number and Sal")
accept employee number and emp sal ch=input("Do u want to update another
empno=int(input("Enter Employee Number:")) record(yes/no):")
empsal=float(input("Enter Employee Salary for update:")) if(ch=="no"):
#design the query and execute print("\nThanks for using program:")
[Link]("update employee set sal=%f where [Link]()
eno=%d" %(empsal,empno))
[Link]() #main program
if([Link]>0): # here rowcount is an pre-defined empupdate()
attribute in cursor object
print("{} Record Updated

3. DRL(Data Retrieval Language) Queries


=>The purpose of DRL Query is that "To Read the records from the table."
=>To read the records from the table , we use select command.

=>Syntax1(Oracle):- select col1, col2...col-n =>Syntax2(Oracle) :- select col1, col2...col-n


from tablename; from tablename where cond list

=>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()

Print by VIKASH Page no -123


#Program for reading all the records from employee #Program for reading all the records from
table- fetchmany employee table---fetchall()
#[Link] #[Link]
import cx_Oracle Import cx_Oracle
def readrecords(): def readrecords():
try: try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]() cur=[Link]()
sq="select * from employee" sq="select * from employee"
[Link](sq) [Link](sq)
print("-"*40) print("-"*40)
print("\tEmployee Records") print("\tEmployee Records")
print("-"*40) print("-"*40)
records=[Link](3) records=[Link]()
for record in records: for record in records:
for val in record: for val in record:
print("\t{}".format(val),end="") print("\t{}".format(val),end="")
print() print()
except cx_Oracle.DatabaseError as db: except cx_Oracle.DatabaseError as db:
print("Problem in reading the records:",db) print("Problem in reading the records:",db)
#main program #main program
readrecords() readrecords()

#Program for reading all the records from employee


table with column names---fetchall() #Program for reading all the records from employee table
#[Link] where salary is less than 7.0 with column names---fetchall()
import cx_Oracle #[Link]
def readrecords(): import cx_Oracle
try: def readrecords():
con=cx_Oracle.connect("scott/tiger@localhost/orcl") try:
cur=[Link]() con=cx_Oracle.connect("scott/tiger@localhost/orcl")
sq="select * from employee" cur=[Link]()
[Link](sq) sq="select * from employee where sal>7.0"
print("-"*40) [Link](sq)
print("\tEmployee Records") print("-"*40)
print("-"*40) print("\tEmployee Records")
#display the column names print("-"*40)
kvr=[Link] #display the column names
colnames=[str(var[0]) for var in [Link]] #colnames=[str(var[0]) for var in [Link]]
for colname in colnames: for colname in [str(var[0]) for var in [Link]]:
print("\t{}".format(colname),end="") print("\t{}".format(colname),end="")
print() print()
print("-"*40) print("-"*40)
#display the records #display the records
records=[Link]() records=[Link]()
for record in records: for record in records:
for val in record: for val in record:
print("\t{}".format(val),end="") print("\t{}".format(val),end="")
print() print()
print("-"*40) print("-"*40)
except cx_Oracle.DatabaseError as db: except cx_Oracle.DatabaseError as db:
print("Problem in reading the records:",db) print("Problem in reading the records:",db)
#main program
#main program readrecords()
readrecords()

Print by VIKASH Page no -124


========================================================================
Steps for developing Python Database Communication Application with MYSQL
========================================================================
=>To develop any Python database communication Applications, we must use the following steps.
1) import [Link]
2) Every Python must establish the connection from mysql 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.

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]

2) Every Python must establish the connection from mysql databse :-


=>If a Python Programmer want to perform different database operations then first we must get a connection
from mysql database.
=>To get the connection from mysql Database, we must use a pre-defined function called "connect()" , which is
present in [Link] module and it returns an object of <class, '[Link]'>
Syntax:- varname= [Link](host="DNS / IP Address",
user="User Name of MySQL",passwd="password of MYSQL")
=>here "username" repersents user name of Database
=>here password represents of Database
=>Here "DNS"(Domain Naming Service) represents Name of the machine where the Data base software installed.
=>The default DNS of every computer is "localhost"
=>Here In Place of DNS, we can also use IP Address( Internet Protocal Address) and it always Address
of the machine where Database software installed.
=>The default IP address of every computer is [Link](loop back address)
=>here "varname" represents an object of <class, '[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]".

3) Create an object of Cursor :-


=>"Cursor" is a pre-defined class present in [Link] Module.
=>The purpose of Cursor class object is that "It Carry the Query from Python Program and brings the result from
MySQL Database and Hand Over to Python Program. Hence an object of Cursor acts as a driver / mediator /
middleware layer between Python program and Database Software.
=>Programatically, To create an object of Cursor class, we use cursor(), which is present in a class <class,
'[Link]'>.
Syntax:- varname=[Link]()
here "varname" is an object of class <class,"[Link]">
Examples:
kvrcur=[Link]()
print("Cursor object Created")
print("type of kvrcur=",type(kvrcur))---<class,"[Link]">

Print by VIKASH Page no -125


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,"[Link]">
Syntax:- [Link](query)
=>here the query can be either DDL, DML and DRL.

#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()

#This program inserts an employee record in employee table--with Dynamic data


#[Link]
import [Link]
def empinsert():
while(True):
try:
con=[Link](host="localhost",user="root",passwd="root" ,database="batch7am")
cur=[Link]() #step-3
#accept employee data from KBD
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
#design the query and execute --step-4
iq="insert into employee values(%d,'%s',%f) "
[Link](iq %(eno,ename,sal))
[Link]()
# (OR)[Link]("insert into employee values(%d,'%s',%f)" %(eno,ename,sal) )
print("{} employee record Inserted Sucessfully".format([Link]))
except [Link] as db:
print("Prob in inserting the data..",db)
except ValueError:
print("Don't enter strs / symbols/ alpha-numerics for emp numbers / salaries")
ch=input("\nDo U want to Insert another record:(yes/no):")
Print by VIKASH Page no -126
if(ch=="no"):
print("Thanks for using This Program")
break

#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()

#this program accept employee number and update the salary


#[Link]
import [Link],sys
def empupdate():
while(True):
try:
con=[Link](host="localhost",user="root",passwd="root" ,database="batch7am")
cur=[Link]()
#accept employee number and emp sal
empno=int(input("Enter Employee Number:"))
empsal=float(input("Enter Employee Salary for update:"))
#design the query and execute
[Link]("update employee set sal=%f where eno=%d" %(empsal,empno))
[Link]()
if([Link]>0): # here rowcount is an pre-defined attribute in cursor object
print("{} Record Updated-Verify".format([Link]))
else:
print("Record Does not exists:")
except [Link] as db:
print("Problem in updating the record:",db)
except ValueError:
print("Don't enter strs / symbols/ alpha-numerics for emp number and Sal")
ch=input("\nDo u want to update another record(yes/no):")
Print by VIKASH Page no -127
if(ch=="no"):
print("\nThanks for using program:")
[Link]()
#main program
empupdate()

#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()

#Program for Demonstrates how to create a table in a data base


#[Link]
import [Link]
try:
con=[Link](host="[Link]",user="root",passwd="root" ,database="batch7am")
cur=[Link]()
#design the query and execute
tc="create table employee(eno int primary key, name varchar(15) not null, sal real not null)"
[Link](tc)
# (OR) [Link]("create table student(stno int primary key, name varchar2(15) not null, marks real not null)")
print("Table Created--verify")
except [Link] as db:
print("Problem in MySQL: ",db)

Print by VIKASH Page no -128


============================================================
Advantages of Object Oriented Principles / Features / Concetps
============================================================
=>In Rea Time, To develop any project we need a language and it can satisfy two types of Principles. They
Are :-
1) Procedure Oriended Principles
2) Object Oriended Principles

=>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

Print by VIKASH Page no -129


==============
1. classes
==============
=>The purpose of classes concept is that "To develop Programmer Defined Datatype and Real Time
Application with Customized Requirements".
=>The
The main purpose of developing Programmer Defined Datatype is that to store mutiple values and
performs Customized Operations by using Programmer
Programmer-defined
defined Functions ( called Methods).
=>To develop Programmer Defined Datatype and Real Time Applicat
Applications
ions with Customized Requirements with
classes , we must use a keyword called "class".
=>In Object Oriented Programming, Every Program must starts with a concept called class. Without classes
concept we can't develop a single program.
=>Every
very Class Name is considered as "programmer
"programmer-defined data type".

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

Print by VIKASH Page no -130


=========================================
Types of Data Members in class
=========================================
=>In a class of Python, we have two types of Data Members. They are
1) Instance Data Members
2) Class Level Data Members

1) Instance Data Members:-


=>Instance Data Members are those whose memory space is created each and every time when an object is created.
=>Instance Data Members are used for storing Specfic Values / Perticular Values, which are suitable for one programmer.
=>Instance Data Members must be ACCESSED / PROCESSED w.r.t Object Name (Or) self.
Object [Link] Data Member Name
=>Instance Data Members MUST SPECIFIED in two places. They are
a) through object name
b) though Instance Methods

2) Class Level Data Members:-


=>Class Level
vel Data Members are those whose memory space is created only once .
=>Class Level Data Members are used for storing Common Values which are suitable for all objects
=>Class Level Data Members must be ACCESSED / PROCESSED w.r.t Class Name Object Name ((Or) self (OR) cls
=>Syntax:-
Class [Link] Level Data Member Name
(OR)
Object [Link] Level Data Member Name
(OR)
[Link] Level Data Member Name
(OR)
[Link] Level Data Member Name

=>Class
Class Level Data Members MUST SPECIFIED in two places. They are
a) through Inside class definition
b) though Inside of Class Level Methods

Print by VIKASH Page no -131


#This Program stores stno,sname, marks and course with OOPS
#[Link] #[Link]
class Student:pass # Here Student is called Class class Student:
Name and treated as Prog-def Data type. crs="PYTHON" #Here crs is called Class Level Data Member
#main program addr="HYD" # Here addr is called Class Level
s1=Student() Data Member
print("Id of s1=",id(s1)) #main program
print("content of s1 before adding Data s1=Student()
members=",s1.__dict__) # { } s2=Student()
print("Number of Values in s1=", len(s1.__dict__))# 0 #add the Instance Data Members to s1
print("-"*40) [Link]=100
#adding Instance Data memebers through an object [Link]="RS"
[Link]=10 [Link]=23.45
[Link]="RS" #add the Instance Data Members to s2
[Link]=88.88 [Link]=200
print("Id of s1=",id(s1)) [Link]="JG"
print("content of s1 after adding Data [Link]=11.11
members=",s1.__dict__) # { ------- } print("-"*40)
print("Number of Values in s1=", len(s1.__dict__))# 3 print("Content of s1:")
print("-------------OR-------------------") print("-"*40)
print("Student Number=",[Link]) print("Student Number:{}".format([Link]))
print("Student Name=", [Link]) print("Student Name:{}".format([Link]))
print("Student Marks=", [Link]) print("Student Marks:{}".format([Link]))
#This Program stores stno,sname, marks and course with print("Student Course:{}".format([Link]))
OOPS print("Student Lives in: {}".format([Link]))
print("-"*40)
print("Content of s2:")
print("-"*40)
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print("Student Course:{}".format([Link]))
print("Student Lives in: {}".format([Link]))
print("-"*40)#This Program stores stno,sname,
marks and course with OOPS

#[Link] [Link]=input("Enter Student Name for Second


class Student: Student object:")
crs="PYTHON" # Here crs is called Class [Link]=float(input("Enter Student Marks for
Level Data Member Second Student object:"))
addr="HYD" # Here addr is called Class print("-"*40)
Level Data Member print("Content of s1:")
#main program print("-"*40)
s1=Student() print("Student Number:{}".format([Link]))
s2=Student() print("Student Name:{}".format([Link]))
#add the Instance Data Members to s1 by print("Student Marks:{}".format([Link]))
reading the data from key board print("Student Course:{}".format([Link]))
[Link]=int(input("Enter Student Number for First print("Student Lives in: {}".format([Link]))
Student object:")) print("-"*40)
[Link]=input("Enter Student Name for First print("Content of s2:")
Student object:") print("-"*40)
[Link]=float(input("Enter Student Marks for First print("Student Number:{}".format([Link]))
Student object:")) print("Student Name:{}".format([Link]))
print("-"*60) print("Student Marks:{}".format([Link]))
#add the Instance Data Members to s2 by print("Student Course:{}".format([Link]))
reading the data from key board print("Student Lives in: {}".format([Link]))
[Link]=int(input("Enter Student Number for Second print("-"*40)#This Program stores stno,sname,
Student object:")) marks and course with OOPS by using methods
Print by VIKASH Page no -132
#[Link]
class Student:
def getstudentdetails(self): #here self is called Impilcit object for current class object
print("Id of self in getstudentdetails()=",id(self))
#main program
s1=Student()
print("Id of s1 in main=",id(s1))
[Link]()
print("-------------------------------------------------")
s2=Student()
print("Id of s2 in main=",id(s2))
[Link]()

#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()

2. Class Level Methods :-


=>Class Level Methods are used for performing Common Operations on Class Level Data Members and they
named as Class Level Methods and we can specify / define Class Level Data Members.
=>The Class Level Method Definition must preceded with a pre-defined decorator
called @classmethod and it must take the First Formal parameter as "cls".
Syntax:-
@classmethod
def classlevelmethodname(cls,list of formal params if any ):
--------------------------------
Block of statements--class level operations
Specify Class Level Data Members
--------------------------------
=>In Python Programming, all Class Level Methods must be accessed w.r.t Class Name (or) cls (or) Object
Name (or) self.
Class Name. Class Level Method Name()
(OR)
[Link] Level Method Name()
(OR)
[Link] Level Method Name()
(OR)
[Link] Level Method Name()
Print by VIKASH Page no -134
3. Static Methods :-
=>Static Methods are used for performing Universal / Utility Operations.
=>The Static Methods Definition must preceded with a pre-defined decorator called @staticmethod and it
never takes the First Formal parameter as "cls or self".
Syntax:-
@staticmethod
def staticmethodname(list of formal params if any ):
--------------------------------
Block of statements--Utility / Universal operations
--------------------------------
--------------------------------
=>In Python Programming, all Static Methods must be accessed w.r.t Class Name (or) cls (or) Object Name
(or) self.
Class Name. Static Method Name()
(OR)
[Link] Method Name()
(OR)
[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

Print by VIKASH Page no -135


#This program demonstrates the specification of Class #This program demonstrates the specification of Class
Level Data Members 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"
[Link]() # calling class level method [Link]() # calling class level method
#A Class Level Method can call another Class #A Class Level Method can call another Class Level
Level Method but not Instance Method Method but not Instance Method
@classmethod @classmethod
def getcompaddr(cls): # Class Level Method def getcompaddr(cls): # Class Level Method
[Link]="HYD" [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
print("-"*40) print("-"*40)
print("Employee Number:{}".format([Link])) print("Employee Number:{}".format([Link]))
print("Employee Name:{}".format([Link])) print("Employee Name:{}".format([Link]))
print("Employee Company Name:{}".format print("Employee Company Name:{}".format
([Link])) ([Link]))
print("Employee Company address:{}".format print("Employee Company address:{}".format
([Link])) ([Link]))
print("-"*40) print("-"*40)

#main program #main program


[Link]() # calling class level method [Link]() # calling class level method
eo1=Employee() eo1=Employee()
eo2=Employee() 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
[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

#This Program demonstrates the static methods usage @staticmethod


#[Link] def displaydata(obj):
class Employee: print("-"*40)
def getempdet(self): for k,v in obj.__dict__.items():
[Link]=int(input("Enter Employee Number:")) print("\t{}-->{}".format(k,v))
[Link]=input("Enter Employee Name:") print("-"*40)
#main program
class Student: eo=Employee()
def getstuddet(self): [Link]()
[Link]=int(input("Enter Student Number:")) so=Student()
[Link]=input("Enter Student Name:") [Link]()
[Link]=input("Enter Std College Name:") #calling static method of ObjectDisplay class name
# I decided to develop a class name with a Method to print("Employee Details")
display the content of any object (Utility Method / Universal [Link](eo) # calling static method
Operation) w.r.t Correspondiong class name
class ObjectDisplay: print("Student Details")
[Link](so)
Print by VIKASH Page no -137
#This Program demonstrates the static methods usage
#[Link]
class Employee:
def getempdet(self):
[Link]=int(input("Enter Employee Number:")) #This Program cal area and perimeter of Circle
[Link]=input("Enter Employee Name:") #[Link]
class Student: class Circle:
def getstuddet(self): @classmethod
[Link]=int(input("Enter Student Number:")) def getPI(cls):
[Link]=input("Enter Student Name:") [Link]=3.14
[Link]=input("Enter Student College Name:") return [Link]
# I decided to develop a class name with a Method to def readrad(self):
display the content of any object (Utility Method / Universal self.r=float(input("Enter Radious:"))
Operation) def area(self):
class ObjectDisplay: [Link]=[Link]()*self.r**2
@staticmethod print("Area of Circle={}".format([Link]))
def displaydata(obj): def peri(self):
print("-"*40) [Link]=2*[Link]()*self.r
for k,v in obj.__dict__.items(): print("Peri of Circle={}".format([Link]))
print("\t{}-->{}".format(k,v))
print("-"*40) #main program
#main program co=Circle()
eo=Employee() [Link]()
[Link]() [Link]()
so=Student() [Link]()
[Link]()
#calling static method of object of ObjectDisplay class name
od=ObjectDisplay()
print("Employee Details")
[Link](eo) # calling static method w.r.t
Correspondiong class objct name
print("Student Details")
[Link](so)

======================================
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()

Example: create an object of Employee Example: create an object of Student


eo=Employee() so=Student()

Example: create an object of Book


bo=Book()

Print by VIKASH Page no -138


Example :-
#This program computes sum of two numbers by using #This program computes sum of two numbers by using
classes and objects. classes and objects.
#[Link] #[Link]
class Sum: class Sum:
def getvalues(self): def getvalues(self):
self.a=float(input("Enter First Value:")) self.a=float(input("Enter First Value:"))
self.b=float(input("Enter Second Value:")) self.b=float(input("Enter Second Value:"))
def findsum(self): [Link]() # calling Instance Method
self.c=self.a+self.b def findsum(self):
def dispvalues(self): self.c=self.a+self.b
print("sum({},{})={}".format(self.a,self.b,self.c)) [Link]() # calling Instance Method
def dispvalues(self):
#main program print("sum({},{})={}".format(self.a,self.b,self.c))
so=Sum()
[Link]() #main program
[Link]() so=Sum()
[Link]() [Link]()

#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)

Print by VIKASH Page no -139


#This Program reads two numerical values and arithmetic #this program reads all the records from employee table of
operator from KBD and find operation result. oracle data base
#[Link] #[Link]
class Values: import cx_Oracle
def getvalues(self): class Employee:
try: def gettablename(self):
self.a=float(input("Enter First Value:")) [Link]=input("Enter table name:")
self.b=float(input("Enter Second Value:")) def getrecords(self):
[Link]=input("Enter any arithmetic operator:") [Link]() # calling instance method
except ValueError: try:
print("\nDon't Enter strs/alpha-numeric/special con=cx_Oracle.connect("scott/tiger
symbols for numerics") @localhost/orcl")
class Calculator: cur=[Link]()
@staticmethod [Link]("select * from %s" %[Link])
def compute(obj): #print col names
try: print("-"*60)
match([Link]): for colname in [ colnames[0] for colnames
case "+":print("sum({},{})={}".format(obj.a,obj.b, in [Link]]:
obj.a+obj.b)) print("{}".format(colname),end=" ")
case "-":print("sub({},{})={}".format(obj.a,obj.b, print()
obj.a-obj.b)) print("-"*60)
case "*":print("mul({},{})={}".format(obj.a,obj.b, #display records
obj.a*obj.b)) records=[Link]()
case "/":print("div({},{})={}".format(obj.a,obj.b, for record in records:
obj.a/obj.b)) for val in record:
case "//":print("floor div({},{})={}".format(obj.a,obj.b, print("{}".format(val),end=" ")
obj.a//obj.b)) print()
case "%":print("mod({},{})={}".format(obj.a,obj.b, print("-"*60)
obj.a%obj.b)) except cx_Oracle.DatabaseError as db:
case "**":print("pow({},{})={}".format(obj.a,obj.b, print("Problem in database :",db)
obj.a**obj.b))
case _: print("\n {} is not a Arithmetic Operator:" #main program
.format([Link])) eo=Employee()
except AttributeError: [Link]()
print("U have Missed Operator in ur typing:")
except ZeroDivisionError:
print("\nDon't enter zero for Den...")

#main program
vo=Values()
[Link]()
[Link](vo)

Print by VIKASH Page no -140


=============================================
Data Encapsulation and Data Abstraction
=============================================

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 ( _ _ )

Syntax1:- class <ClassName>:


def methodname(self):
self.__Data MemberName1=Value1
self.__Data MemberName2=Value2
--------------------------------------------------
self.__Data MemberName-n=Value-n

Syntax2:- class <ClassName>:


def __methodname(self):
[Link] MemberName1=Value1
[Link] MemberName2=Value2
--------------------------------------------------
[Link] MemberName-n=Value-n

Syntax3:- class <ClassName>:


def ____init__(self):
[Link] MemberName1=Value1
[Link] MemberName2=Value2
--------------------------------------------------
[Link] MemberName-n=Value-n

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

Print by VIKASH Page no -141


Data Abstraction :-

=>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.

#[Link]---file name and treated as module name


class Student:
def getstudentdetails(self):
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
def dispstuddetails(self):
print("\t{}\t{}\t{}".format([Link],[Link],[Link]))

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:")

Print by VIKASH Page no -142


Constructors in Python
INDEX :-
 purpose of Constructor
 definition of Constructor
 syntax for defining Constructor in class
 Type of Constructor
a) Default Constructor
b) Parameterized Constructor
 Programming examples

=========================================
Constructors in Python
=========================================
=>The purpose of Constructors in Python is that "To Initlize the Object".
=>Initlizing the object is nothing but placing our own values without leaving 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).

Rules for using Constructor in Python :-


=>The Constructor called by PVM during Object Creation automatically / Implicitly.
=>The Name of the constructor is def __init__(self,......):pass
=>The constructors in python can be inherited.
=>The constructors in python can be Overridden

Syntax for constructor :


def __init__(self, list of formal params if any):
--------------------------------------------
--------------------------------------------
Block of statements--Initlization
--------------------------------------------
--------------------------------------------
Types of Constructors:
=>In Python Programming, we have two types of Constructors. They are
a) Default / Parameter Less Constructors
b) Parameterized Constructors

a) Default / Parameter Less Constructors:


=>Default / Parameter Less Constructor is one, which is not taking any Parameters / Values.
=>The purpose of Default / Parameter Less Constructors is that "To Initlize multiple objects of same
class with Same Values "
Syntax:-
def __init__(self):
--------------------------------
Block of statements--Initlizatioin
--------------------------------
b) Parameterized Constructors:
=> A Parameterized Constructor is one, which is taking Parameters / Values.
=>The purpose of Parameterized Constructors is that "To Initlize multiple objects of same class
With Different Values "

Print by VIKASH Page no -143


Syntax:-
def __init__(self,list of formal params):
--------------------------------
Block of statements--Initlizatioin
--------------------------------

Examples :- Default constructors Exmaples:- Parameterized constructors


#[Link] #[Link]
class Test: class Test:
def __init__(self): def __init__(self,a,b):
print("i am from default constructor:") print("i am from Parameterized constructor:")
self.a=10 self.a=a
self.b=20 self.b=b
print("Val of a={}".format(self.a)) print("Val of a={}".format(self.a))
print("Val of b={}".format(self.b)) print("Val of b={}".format(self.b))

#main program #main program


print("Content of t1 object:") print("Content of t1 object:")
t1=Test() t1=Test(10,20)
print("-"*50) print("-"*50)
print("Content of t2 object:") print("Content of t2 object:")
t2=Test() t2=Test(100,200)
print("-"*50) print("-"*50)
print("Content of t3 object:") print("Content of t3 object:")
t3=Test() t3=Test(1000,2000)
print("-"*50)

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.

Some Example of constructors :-

#[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__)

Print by VIKASH Page no -144


#[Link] print("-"*50)
class Test: print("Content of t2 object---with parameterized ")
def __init__(self,a=10,b=20): t2=Test(100,200) # calls Parameteized constructor
self.a=a print("-"*50)
self.b=b print("Content of t3 object--with default constructor:")
print("Val of a={}".format(self.a)) t3=Test() # calls default constructor
print("Val of b={}".format(self.b)) print("-"*50)
print("Content of t4 object---with parameterized ")
#main program
t2=Test(1000,2000) # calls Parameteized constructor
print("Content of t1 object--with default
print("-"*50)
constructor:")
t1=Test() # calls default constructor

==============================================
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.

Print by VIKASH Page no -145


============================
Destructors in Python
============================
=>The Name of Destructor is
def __del__(self):
------------------------
------------------------
=>Destructors are called by Garbage Collector
=>A Garbage Collector is one of the Python In-built program, which is executing Internally behind of every Program
for collecting / de-allocating the memory space of all objects which are used in the python program.
=>In Python Programming Every Garbage Collector contains its own detsructor.
=>In the destructor , we write code for destorying the memory space of Objects used in python program
and every destructor called by Garbage Collector.

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 )

Some Example of destructors :-

#[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] #main program


import time print("Program Execution Started..")
class Employee: eo1=Employee(10,"RS")
def __init__(self,eno,ename): print("No Longer Interested to maintain object eo1")
print("\ni am from Contructor:") [Link](8)
[Link]=eno eo1=None # Here Forcefully , GC calls __def__(self)
[Link]=ename eo2=Employee(20,"DR")
print("\t{}\t{}".format([Link],[Link])) eo3=Employee(30,"RR")
def __del__(self): # Programmer-defined Destructor print("\nProgram Execution Completed..")
print("\nGC is calling Destructor Function") [Link](5)
# Here by default , GC calls __def__(self) two times

Print by VIKASH Page no -146


#[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")
print("No Longer Interested to maintain object eo1") print("No Longer Interested to maintain object eo1")
[Link](8) [Link](8)
eo1=None # Here Forcefully , GC calls __del__(self) del(eo1) # Here Forcefully , GC calls __del__(self)
eo2=Employee(20,"DR") eo2=Employee(20,"DR")
print("No Longer Interested to maintain object eo2") print("No Longer Interested to maintain object eo2")
[Link](8) [Link](8)
eo2=None # Here Forcefully , GC calls __del__(self) del eo2 # Here Forcefully , GC calls __del__(self)
eo3=Employee(30,"RR") eo3=Employee(30,"RR")
print("\nProgram Execution Completed..") print("\nProgram Execution Completed..")
[Link](5) [Link](5)
# Here by default , GC calls __del__(self) one time # Here by default , GC calls __del__(self) one
times

#[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")

Print by VIKASH Page no -148


===============================================
Introduction to Inheritance
===============================================
=>Inheritance is one of the distinct principle of OOPs
=>The purpose of Inheritance is that "To Build / Develop Re-Usable Applications."
=>The advantages of Inheritance concept is that
1) Application Development time Less
2) Application Memory Space is Very Less
3) Application Execution Time is Very Less
4) Application Performnace is Enhanced (Improved)
5) Redundency ( Duplication ) of the code is minimized.

=>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"

Print by VIKASH Page no -149


======================================
Types of Inheritances
======================================
=>Type
Type of Inheritance is one of the diagram / model always makes us to understand How the features are
Inherited from Base class into derived class.
=>In Python Programming, we have 5 types of Inheritances. They are :-
1. Single Inheritance.
2. Multi Level Inheritance.
3. Hierarchical Inheritance.
4. Multiple Inheritance.
5. Hybrid Inheritance.

Print by VIKASH Page no -150


Some Example of Inheritance :-
#This program demonstrates the concept of #This program demonstrates the concept of
Inheritance Inheritance
#[Link] #[Link]
class C1: class C1:
def setC1Values(self): def setC1Values(self):
[Link]=10 [Link]=10
[Link]="Python" [Link]="Python"
class C2(C1): # Following Single Inheritance class C2(C1) : # Following Single Inheritance
def setC2Values(self): def setC2Values(self):
[Link]="Rossum" self.setC1Values() # w.r.t Derived Class, we
[Link]="OUCET" are calling Base Class Method
[Link]="Rossum"
#main program [Link]="OUCET"
o2=C2() def dispvalues(self):
print("Content of o2=",o2.__dict__) for k,v in self.__dict__.items():
o2. setC1Values() # w.r.t Derived Class, we are calling print("\t{}\t{}".format(k,v))
Base Class Method #main program
o2.setC2Values() o2=C2()
print("Content of o2=",o2.__dict__) o2.setC2Values()
print("Student Details")
print("-"*50)
[Link]()
print("-"*50)

#[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]()

Print by VIKASH Page no -151


=============================
Method Overrding
=============================
=>To use Method Overriding in the python Program, we need to apply Inheritance Principle.

=>Def. of Method Overriding:


=>Method Overriding=Method Heading is Same + Method Body is different
(OR)
=>The Process of re-defining the original method of base class into various derived classes for performing
different operations is called Method Overriding.
=>Method Overrding concept is used for implementing Polymorphism Principle.

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]()

Print by VIKASH Page no -152


==============================
Polymorphism
==============================
=>Polymorphism is one of the distinct principle of OOPs
=>The
The purpose of Polymorphism principle is that " To build the Object oriented Applications with effective
Memory space(less memory space) ".

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

Print by VIKASH Page no -153


a) By Using super():
=>super() is used for calling Base Class Orginal Method (or) Original Constructor from derived class
Overridden Method / Constructor.
=>Syntax1:- super().MethodName()
super().MethodName(list of values)
=>Syntax2:- super().__init__()
super().__init__(list of values)

=>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.

=>Syntax1:- Class [Link](self)


Class [Link](self , list of values)
=>Syntax2:- Class Name.__init__(self)
Class Name.__init__(self , list of values)

#Program cal area of different Figures such as class Rect(Circle,Square):


circle,rect and square by using method overriding def area(self,l,b): # Overridden Method
for implementing polymorphism [Link]=l*b
#[Link] print("Area of Rect={}".format([Link]))
class Circle: print("-"*50)
def area(self, r): # Original Method--One Form [Link](self,5)
[Link]=3.14*r**2 [Link](self, 10)
print("Area of Circle={}".format([Link]))
class Square: #main program
def area(self, s): # Overridden Method l,b=float(input("Enter Length:")), float(input("Enter
[Link]=s**2 Breadth:"))
print("Area of Square={}".format([Link])) ro=Rect()
print("-"*50) [Link](l,b)
Print by VIKASH Page no -154
#Program cal area of different Figures such as #Program cal area of different Figures such as
circle,rect and square by using method overriding circle,rect and square by using method overriding
for implementing polymorphism for implementing polymorphism
#[Link] #[Link]
class Circle: class Circle:
def area(self, r): # Original Method--One Form def __init__(self, r): # Original Constructor--One Form
[Link]=3.14*r**2 [Link]=3.14*r**2
print("Area of Circle={}".format([Link]))
class Square:
print("Area of Circle={}".format([Link]))
def area(self, s): # Overridden Method class Square:
[Link]=s**2 def __init__(self, s): # Overridden Constructor
print("Area of Square={}".format([Link])) [Link]=s**2
print("-"*50) print("Area of Square={}".format([Link]))
class Rect(Circle,Square): print("-"*50)
def area(self,l,b): # Overridden Method
[Link]=l*b
print("Area of Rect={}".format([Link]))
print("-"*50) class Rect(Circle,Square):
[Link](self,float(input("Enter Radiuos:")) ) def __init__(self,l,b): # Overridden Constructor
[Link](self, float(input("Enter Side:")) ) [Link]=l*b
print("Area of Rect={}".format([Link]))
#main program print("-"*50)
l,b=float(input("Enter Length:")), float(input("Enter Circle.__init__(self,float(input("Enter Radiuos:")) )
Breadth:"))
Square.__init__(self,float(input("Enter Side:")) )
ro=Rect()
[Link](l,b)
#main program
l,b=float(input("Enter Length:")), float(input("Enter
Breadth:"))
ro=Rect(l,b)

#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()

Print by VIKASH Page no -155


Print by VIKASH Page no -156

You might also like