Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
168 views

Complete Python Course

Python can be used to develop over 22 real-time applications due to its features. Some key applications include web development, gaming, AI/machine learning, desktop GUIs, image processing, and data analysis. Python is an interpreted, high-level, dynamically typed programming language that is simple, free/open source, and platform independent. It supports both procedural and object-oriented programming, is extensible, and integrates well with third-party APIs.

Uploaded by

14prisingh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views

Complete Python Course

Python can be used to develop over 22 real-time applications due to its features. Some key applications include web development, gaming, AI/machine learning, desktop GUIs, image processing, and data analysis. Python is an interpreted, high-level, dynamically typed programming language that is simple, free/open source, and platform independent. It supports both procedural and object-oriented programming, is extensible, and integrates well with third-party APIs.

Uploaded by

14prisingh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 419

Real time Applications of Python

With Python Programming, we can develop 22+ Real Time Application.

1. Web Application Development:


Python---Django, Flask, Bottle…etc.
2. Gaming Application Development.
3. Artificial Intelligence ------ Machine Learning & Deep Learn-
ing.
4. Desktop GUI Application.
5. Image Processing Application.
6. Text Processing Application.
7. Business Application.
8. Audio and Video Based Application.
9. Web Scrapping Application/Web Harvesting Application.
10. Data Visualization.
11. Complex Math Calculations.
12. Scientific Applications.
13. Software Development.
14. Operating System.
15. CAD and CAM based Application.
16. Embedded Applications.
17. IOT based Applications.
18. Language Applications.
19. Automation Applications.
20. Animation Application.
21. Data Analysis and Data Analytics.
22. Education Sector.
23. Computer Vision.
Getting Started with Python

History of Python  Versions of Python  Downloading of Python.

History of Python:
a) Python Programming Language foundation conceived in the year 1980.
b) Python Programming Language implementation starts in the year 1989.
c) Python Programming Language officially released on 20 Feb 1991.
d) Python Programming Language developed by “Guido Van Rossum”.
e) Python Programming Language developed at Centrum Wiskunde &
Informatica (CWI) in Neither-Land.
d) The Predecessor of Python language is called ABC Programming Language
And successor of ABC language is called Python language.
Versions of Python language: (Details information available on Wikipedia)
a) Python programing contains three versions:-
1. Python 1.x--- Here x---> 1, 2, 3…...6. Only. (1 is called major version & x is
Called minor version)
2. Python 2.x--- Here x---> 1, 2, 3…..7. Only. (Abolished in 2020)
3. Python 3.x--- Here x---> 1, 2, 3….12. Only.
b) Python 3.x does not contain backward compatibility with python 2.x
c) Python software and its updates and maintained by a Non-Commercial
Organization called “Python Software Foundation” (PSF).
d) To download Python 3.x software  www.python.org

Python Programming Inspired from 4 programming languages:

1. Functional Programming from “C” language.


2. Object oriented programming from “CPP” language.
3. Scripting Programming from “PERL”.
4. Modular Programming from “Modulo3”.
Features of Python
Features of language are nothing but Services or Facilities provided by
language developers which are used by language programmers for
developing real time applications.
Python Programming provides 11 features. They are:
1. Simple.
2. Freeware and Open Source.
3. Platform Independent.
4. Dynamically Typed Programming language.
5. Interpreted Programming.
6. High Level Programming.
7. Robust (Strong).
8. Both Procedural and Object Oriented Programming.
9. Extensible.
10. Embedded.
11. Supports 3rd Party API’s—Numpy, Pandas, Scipy, Scikit, Matplotlib.

1. Simple: Python is one of the Simple programming language because of


three technical factors. They are:

a) Python provides rich set of API’s (Libraries). So that Python programmers


Can re-use the pre-defined code without writing our own code.
Application Programming Interface: An API is a collection of modules.
A Modules is a collection of functions, variables & classes.
Examples: math, cmath, calendar, random, datetime…etc.

b) Python Programming provides in-built Garbage Collection facility. So that


Garbage collector collects un-used memory space and improves
Performance of Python based applications.

Garbage collector is one of the in-built Python background process which is


running behind of regular Python program and whose role is to collect un-
used heap memory and improve the performance of Python Based
Applications.
Hence Garbage Collector takes about Automatic Memory Management.
Features of Python
c) Python provides user- friendly Syntaxes. So that Python programmer can
develop error–free program in limited span of time.

2. Freeware and open Source: If we download any software freely from


original source then is called Freeware. Since we download Python
software freely from www.python.org
Hence python is one of the Freeware.

3. Platform Independent: Platform is nothing but OS being use to run the


Program/application.
“A language is said to be Platform Independent if and only if whose
application or program runs on every OS.”
Python is one of the Platform Independent because of Python
Programming Execution Environment “All values stored in the form of
Object and Objects are Independent from OS”.
4. Dynamically Typed Programming: In General we have two types of
Programing Languages They
are:

a) Statics Typed Programming Language.


b) Dynamically Typed Programming Language.
Features of Python
a) Statics Typed Programming Language: In this Programing Language, we
must “Declare the variables” by using Data types otherwise we get
Compile time errors. Examples: C, CPP, JAVA, .NET…etc.

b) Dynamically Typed Programming Language: In this Programming


Language, we need not to declare the variables explicitly by using data
types. So Python Execution Environment decides the data type depends
on type value we are using in Python Program. Examples: Python.
Hence in Python Programming, all values are stored in the form of
OBJECTS and behind of OBJECT, there exist CLASSES.

5. Interpreted Programming: when we develop any Python Program, we


must give some file name with an extension .py (file name.py). When
we execute Python program, two Process taken place internally:
a) Compilation Process b) Execution Process

In Compilation Process, the Python source Code submitted to


the Python compiler and its read line by line source code, check for
ERROR by the verifying syntax and if no error found then Python
compiler CONVERT into Intermediate code called “BYTE CODE” with an
extension .pyc (file name.pyc). If error found in source code then error
display on the console.

In Execution Process, the PVM reads the Python intermediate


code (BYTE CODE) LINE BY LINE and converts into MACHINE
understandable code (“Executable or BINARY CODE”) and it is read by
the OS and after processing display the final result.

Hence in Python Program execution, compilation process and


Execution process is taking place “LINE BY LINE” conversion and it is
one of the interpreted based programming language.

Definition of PVM (Python Virtual Environment): PVM is one of Program in


Python software and whose role is to read BYTE CODE LINE -BY- LINE and
convert it into machine understandable code (Executable or Binary Code).
Features of Python

6. High level Programming: In General, we have two types of Programming


languages. They are:
a) Low Level Programming Language.
b) High Level Programming Language.
a) Low Level Programming Language: In these Programming Language,
we represent the data in lower level date like Binary, Octal and Hexa
Decimal. These types of data is not by default understandable by
programmer and End Users.
Examples: a=0b1111110000111101010---binary data
b=0o23--------------------octal data
c=0xface------------------Hexadecimal data

b) High Level Programming Language: In these Programing Language,


Even we represent the data in Lower Level data like Binary, Octal,
Hexa-Decimal, the high level programming language automatically
converts into Decimal Number System Data, which is understandable by
the Programmer and End User.

Hence Python is a High Level programming Language.


Features of Python
7. Robust (Strong): Python is one of the Robust Programming language
because of Python Provides “Exception Handling Facility”.

Exception: Every Runtime Error is called Exception.


All Exceptions by- default gives Technical Messages.

Exception Handling: The Process of Converting Technical Error Message


into User-Friendly Error Messages is known as Exception Handling.
In Real Time Project, the above process we use Exception
handling to make real project as Robust.

Note: In Real Time Application development, to develop any project,


choose certain program language.

Using that programming language, we develop, compile and execute


during process, we get various types of errors:

a) Compile Time Error: Due to Syntaxes are not followed (.py to .pyc).
b) Logical Error: Due to wrong representation of logical (at Execution time).
c) Run time Error: Run time error are those error which are occurring
during implementation level. And also due to invalid “INPUT” entered by
the End-User/Application User.

Examples: ATM Project ---Inserting card in reverse order---


---Invalid Pin---
---Invalid Amount--- etc.
9. Extensible: The Python gives/provides its programming facilities to other
programming language and hence Python is one of the
extensible programming language.

10. Embedded: Python Programming can call other programming languages


code segment for fastest execution.

Example: Python code can call C programming code.


Features of Python
11. Support Third Party APIs: The traditional Python Programming Projects
efficiency increased by third party APIs like numpy, pandas, matplotlib,
scipy, scikit … etc.

To use Third Party APIs, we must install them by using tool called
“PIP, PIP3, and PIP3.10”.

Data representation in Python

Data representation in Python Programming language is nothing but storing


the data in main memory (RAM) of Computer.
To store the data in main memory of computer, we need three things.
They are:
a) Literals or Values.
b) Identifiers or Variables.
c) Data types.

a) Literals or Values: Literals are the values, entered by the programmer,


end - user or application user to real time applications.

They are classified into:


1) Integral Literals (Ex: Adhar number, Emp no, HTNO…etc.)
2) Float Literals (Ex: Marks, Percentage, GDP of India …etc.)
3) String Literals (Ex: Name, Place, Description…etc.)
4) Boolean Literals (Ex: True and False)
5) Date Literals …etc.

b) Identifiers or Variables: Once Application user enters the data from Key
board to program, it is the responsible of programmer to store data in the
form of Identifiers or Variables.

Hence all Literals or values or data must store in main memory in the
form of Identifiers or variables otherwise we can’t process the data.
Data representation in python
Examples: >>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)--------10 20 30

Def. of Variable: A variable is and Identifier, whose values are changing or


varying during the execution of program.

Rules for Using variable in Python

To use Variable name in Python Programming, we have the following these


rules:

a) The variable name is Combination of Alphabets, Digits and Special


Symbol ( _ ).

b) The variable name must starts with either Alphabet or Special Symbol
(Underscore _ ).

Examples: 123sal=4.5--------invalid
-sal=56.56--------invalid
sal=5.6-----------valid
_sal=67.89--------valid
sal123=6.7--------valid
sal12_=7.8--------valid
__name="Rossum"---valid

c) Within Variable name, Special Symbol are not allowed except underscore ( _ ).
Examples:
emp$sal=5.6-------invalid
emp-sal=5.6-------invalid
emp sal=6.7-----invalid
empsal=6.7-------valid

sal=34------------valid
sal#emp=56--------valid because the symbol # is used in
python as commenting Symbol.
Data representation in python
d) No Keywords to be used as variable name (Keywords are reserved words which
will have some special meaning to the language compiler).
Examples:
if=34------------inavlid
else=5.6-----inavlid
if1=34-----------valid
_else=5.6---------valid
int=23---------valid bcoz all the class
names are not keywords.
e) All the variables in python are Case Sensitive.
Examples:
>>> age=99----valid
>>> AGE=98---valid
>>> Age=97---valid
>>> aGe=96--valid
>>> print(age,AGE,Age,aGe)----99 98 97 96
Data Types in Python

Data Types in Python

The Purpose of Data Types in Python is that “To allocate memory space for
the input Literals to store in main memory of computer”.

In Python Programming 14 Data types, which are classified into 6 types:


1) Fundamental Category Data Types:
a) int b) float c) bool d) complex

2) Sequence Category Data Types:


a) str b) bytes c) bytearray d) range

3) List Category Data Types:


a) list b) tuple

4) Set Category Data Types:


a) set b) frozen set

5) Dict Category Data Types:


a) dict

6) None Category Data Types:


a) NoneType

1) Fundamental Category Data Types:

The purpose of Fundamental Category Data Types is that


“To store Single Value”. We have 4 Data types under this category:

a) int b) float c) bool d) complex

a) int: “int” is one of the pre-defined class treated as Fundamental


Category Data Type. The purpose of int datatype is that “To store
Integral Values or whole Numbers or Integers Values (Numbers
without decimal values)”.
Examples: empno, adhar cardno, stno, htno..etc
Data Types in Python
Python Instruction Output
>>> a=100
>>> print(a)------------------------100
>>> print(type(a))--------------<class 'int'>
>>> print(id(a))----------------2601493466448

The “ int ” data can also store various number system values.
In Python Programming, we have 4 Types of number system. They are:

Ⅰ. Decimal Number System Ⅱ. Binary Number System


Ⅲ. Octal Number System Ⅳ. Hexa Decimal Number System

Ⅰ. Decimal Number System:

It is the default number.


The digits in the Decimal number system are: 0,1,2,3,4,5,6,7,8,9 total 10 digits.
The base of Decimal Number System is 10.
Python Programming by default follows Decimal Number System.

Ⅱ. Binary Number System:

The Digits in Binary Number systems are: 0, 1. Total 2 Digits.


The base of Binary Number system is 2.
In Python Programming, To Store Binary system data, Binary value must be
preceded with 0b or 0B.

Syntax: varname=0b Binary Data


Or
varname=0B Binary Data

Even we store binary data, The Python programming converts binary


data into Decimal Number system Value, which is understandable by
end-user/programmer.
Data Types in Python

Examples:
>>> a=0b1010
>>> print(a, type(a))-----10 <class 'int'>
>>> a=0B1111
>>> print(a)--------------------15
>>> a=0b10102------SyntaxError: invalid digit '2' in
binary literal
Ⅲ. Octal Number System:

The digits in octal Number system are: 0,1,2,3,4,5,6,7. Total 8 Digits.


Base of Octal Number System is 8.
In Python Programming, to store Octal Number System Data, Octal
Number Value must be preceded with either 0o or 0O.

Syntax: varname=0o Octal Data


Or
varname=0O Octal Data
Even we store octal data, the Python Programming converts it into
Decimal number system data, which is understandable by end-
user/programmer.
Examples:
>>> a=0o27
>>> print(a,type(a))------------23 <class 'int'>
>>> a=0O34
>>> print(a)--------------------28
>>> a=0O123
>>> print(a,type(a))------------83 <class 'int'>
>>> a=0O2348-----------SyntaxError: invalid digit
'8' in octal literal.

Ⅳ. Hexa Decimal Number System:

The Hexa Decimal Number Systems are:


0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A(10), B(11), C(12), D(13), E(14), F(15). Total 16 Digits.
Base of Hexa Decimal Number System is 16.
In Python Programming, to store Hexa Decimal Number system data, Hexa
Decimal Number System Value must be preceded with 0x or 0X.
Data Types in Python
Syntax: varname=0x Hexa Decimal data
Or
varname=0X Hexa Decimal Data

Even we store Hexa Decimal Data, The Python Programming converts it


into Decimal number system Data. Which is understandable by end-
user/programmer.
Examples:
>>> a=0xAC
>>> print(a, type(a))-----------72 <class 'int'>
>>> a=0XBEE
>>> print(a,type(a))---------- 3054 <class 'int'>
>>> a=0xFACE
>>> print(a,type(a))----------- 206 <class 'int'>
>>> a=0xACC
>>> print(a,type(a))------------764 <class 'int'>
>>> a=0xFACER-----------SyntaxError: invalid
hexadecimal literal
>>> a=0XBEER-----SyntaxError: invalid hexadecimal
literal

Number System Conversion

======================================================================
Data Types in Python

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

b) float: “float” is one of the pre-defined class and treated as fundamental


data type.

The Purpose of float data type is “To store Real Constant Values or floating
point values (Number with Decimal places)”.
Examples: 3.14, 98.46, 0.9999 ... etc.
float data type does not supports Binary, Octal and Hexa Decimal Number
System. float data type supports Scientific Notation(Mantissa-e-Exponent)
and whose advantage is to taking less memory space for Larger Number
Floating Point Values.
Data Types in Python

Examples:
>>> a=12.34
>>> print(a)--------------------12.34
>>> print(type(a))----------<class 'float'>
>>> print(id(a))-------------1671845431216
Or
>>> print(a,type(a), id(a))----12.34 <class
'float'> 1671845431216
---------------------------------------------------
>>> b=0.3
>>> print(b,type(b),id(b))----0.3 <class 'float'>
1671845435856
---------------------------------------------------
>>> a=0b1111.0b1010-------------SyntaxError:
invalid decimal literal
>>> b=0o23.0b1111----------SyntaxError: invalid
decimal literal
>>> c=0xAC.0xBEE--------SyntaxError: invalid
decimal literal
---------------------------------------------------
Examples:
>>> a=4e2
>>> print(a,type(a))-------400.0 <class 'float'>
>>> a=10e-2
>>> print(a)------------0.1
>>> a=0.000000000000000000005
>>> print(a)------------5e-21
>>> a=0.00000000000000000000000008
>>> print(a,type(a))-------8e-26 <class 'float'>
>>> a=2.3e3
>>> print(a)---------------2300.0

Note: x=03456----SyntaxError: leading zeros is decimal integer literals are


not permitted.

c) bool: “ bool ” is one of the pre-defined class and treated as Fundamental


Data Type.
The Purpose of bool data is “To store True or False (Logical Values)”.
Internally the value of true and false is considered as 1 and 0. Respectively.

Here True and False are the Keywords and Values for bool data type.
So that we can’t assign values to True and False.
Data Types in Python

Examples:
>>> a=True
>>> print(a,type(a))---------True <class 'bool'>
>>> b=False
>>> print(b,type(b))---------False <class 'bool'>
>>> c=true--------------NameError: name 'true' is not
defined. Did you mean: 'True'?
>>> d=false-------------NameError: name 'false' is not
defined. Did you mean: 'False'?
------------------------------------------------------
>>> True=10--------SyntaxError: cannot assign to True
>>> False=45-------SyntaxError: cannot assign to False
------------------------------------------------------
>>> print(True+True)---------------2
>>> print(True+False)--------------1
>>> print(True-False)--------------1
>>> print(2*True+3*False)----------2
>>> print(True+0b1010)-------------11
>>> print(False+True*0b1010)-------10
>>> print(True+0b1111)-------------16
>>> print(True+0o23)---------------20
>>> print(True+0xBEE)--------------3055
>>> print(True+1.1)----------------2.1
------------------------------------------------------
>>> print(True/False)-----ZeroDivisionError: division
by zero
>>> print(False/True)------0.0

d) Complex: “Complex” is the one of pre-defined class and treated as


Fundamental Data Type.
The purpose of complex data type “To store Complex values (Imaginary
Values)”.
The General Format of complex number is shown below:
a+bj or a-bj
Here, ‘a’ is called “Real Part”, ‘b’ is called “Imaginary Part ” & ‘ j ’
represents sqrt (-1).

The type of Real and Imaginary Parts are by-default belongs “float”.
To Extract Real Part from Complex object, we use “real” attribute /
variable of complex object.

Syntax: complexobj.real ---- Gives real part of complex number.


Data Types in Python
To Extract Imaginary pert from Complex Object, we use “imag” attribute /
variable of complex object.

Syntax: complexobj. imag ---Gives imaginary part of complex number.


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

2) Sequence Category Data Types:

The purpose of sequence category data type is that “To Organize or store
Sequence of Values”.
We have 4 data types in sequence category, they are:
a) str b) bytes c) byte array d) range

a) str :
Purpose of str.
Types of str.
Memory management of str.
Operations on str ----- a) Indexing b) slicing
Data Types in Python
“str” is one of the pre-defined class in sequence datatype.
The purpose of “str” data is that “To store sequence or collection of
character(s) or special symbols or digits within ‘single quotes’ or “double
quotes” or ‘’’triple single quotes ’’’ or “””triple double quotes”””.

Types of strings: In Python, we have two types of strings 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 quotes’ or “double quotes”.

Syntax: strobj= “Single line string data” or ‘Single line string data’ .
Examples:
>>> s1="Python Program"
>>> print(s1,type(s1))---Python Program <class 'str'>
>>> s2="K"
>>> print(s2,type(s2))---------K <class 'str'>
>>> s3='K'
>>> print(s3,type(s3))---------K <class 'str'>
>>> s4="$#%^&@!"
>>> print(s4,type(s4))-------- $#%^&@! <class 'str'>
>>> s5="123456"
>>> print(s5,type(s5))--------123456 <class 'str'>

Note: The single quotes and double quotes can organized or store single line
string data but unable to store multi line string data.

Invalid Examples:
-------------------------------
>>> s1="Python is an oop lang
Error Name---->SyntaxError: unterminated string
literal (detected at line 1)
>>> s2='Pythin is an oop lang
Error Name---->SyntaxError: unterminated string
literal (detected at line 1)

b) Multi Line String Data: Multi Line String Data must be enclosed within ‘’’ triple
single quotes ‘’’ or “”” triple double quotes “””. Only
Data Types in Python
Syntax: strobj= """
String Data -1
String Data -2
-------------------
-------------------
String Data -n """
(OR

Syntax: strobj= '''


String Data -1
String Data -2
-------------------
-------------------
String Data -n ' ' '

Here ‘’’ triple single quotes ‘’’ or “”” triple double quotes “”” can be both
Single and Multi-lines String data.

Examples:

>>> s12= ' ' 'Guido Van Rossum


... HNO:3-4, red sea side
... Python Software Foundation
... Nether Lands 555666 ' ' '
>>> print(s12,type(s12))------Guido Van Rossum
HNO:3-4, red sea side
Python Software Foundation
Nether Lands 555666
<class 'str'>

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


... python is also fun prog lang
... python invented by RS
... Python version is 3.10.4" " "
>>> print(s10,type(s10))-------Python is an oop lang
python is also fun prog lang python invented by RS
Python version is 3.10.4 <class 'str'>
>>> s1= """Python"""
>>> s2= '''Java'''
>>> print(s1,type(s1))-----------Python <class 'str'>
>>> print(s2,type(s2))-----------Java <class 'str'>
Data Types in Python

Memory management of str.

Operation on str data (Part-1):

On str data, we can perform 2 type of operations. They are:


1. Indexing 2. Slicing

1) Indexing: The process of obtaining a single character from given str


object is called Indexing.
Syntax: strobj[ Index ]
Here index represent either +ve index or –ve Index.
If the Index values is invalid then PVM gives IndexError.

Examples:
>>> s="PYTHON"
>>> print(s,type(s))-----------PYTHON <class 'str'>
>>> s[0]---------------'P'
>>> s[1]---------------'Y'
>>> s[2]----------------'T'
>>> s[4]---------------'O'
>>> s[-1]---------------'N'
>>> s[-6]--------------'P'
>>> s[-2]---------------'O'
>>> s[-3]---------------'H'
>>> s[-33]---------IndexError: string index out of range
>>> s[12]----------IndexError: string index out of range
Data Types in Python
--------------------------------------------------------
>>> s="Mango"
>>> print(s[0])--------------M
>>> print(s[-1])-------------o
>>> print(s[-3])----------n
>>> print(s[2])------------n
>>> print(s[22])---IndexError: string index out of range
>>> print(s[-22])--IndexError: string index out of range.

2) Slicing: The process of obtaining range of characters or part of given


string or Sub string of given str object is called Slicing.
To perform slicing operation we have 5 Syntaxes. They are:

Syntax-1: strobj[ Begin : End ]


This syntax obtain range of character from Begin to End Index-1 Provided
Begin Index < End Index otherwise we never get any Output ( ‘ ’ )

Examples:
-------------------
>>> s="PYTHON"
>>> s[0:4]----------------'PYTH'
>>> print(s[0:4])---------PYTH
>>> print(s[4:0])------ No Output

(OR)
>>> s[4:0]-------- ' ' Indicates No Output
---------------------------------------------
>>> s="PYTHON"
>>> s[2:5]----------------'THO'
>>> s[0:5]---------------'PYTHO'
>>> s[0:3]---------------'PYT'
>>> s[4:6]----------------'ON'
>>> s[-6:-4]---------------'PY'
>>> s[-4:-1]------------------'THO'
>>> s[-5:-1]---------------'YTHO'
>>> s[-3:-5]---------------' ' Indicates No Output
--------------------------------------------------------
Special case:
-------------------------------------
>>> s="PYTHON"
>>> print(s)-------------PYTHON
>>> s[2:-2]------------'TH'
>>> s[2:-1]----------'THO'
Data Types in Python
Syntax-2: strobj [ Begin : ]

In this Syntax, we have Begin Index and not specified End Index.
Syntax give range of character from Begin Index to End Index Taken as
Len( strobj )-1.

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

Syntax-3: strobj [ : End]

In This Syntax, we have End Index and not specified Begin Index.
Syntax gives range of character from first character (initial positive Index)
to End Index -1.
Examples:
----------------
>>> s="PYTHON"
>>> s[:4]---------------------'PYTH'
>>> s[:5]--------------------'PYTHO'
>>> s[:2]-------------------'PY'
>>> s[:-4]------------------'PY'
>>> s[:-1]-------------------'PYTHO'

Syntax-4: strobj [ : ]

In this syntax, we didn’t specify Begin and End Index.


If we don’t specify the Begin and End Index then PVM takes Initial
Character Index as Begin Index (+ve Initial Index) and Last Character Index
as End Index.
This Syntax gives total str data.
Data Types in Python
Examples:
--------------------
>>> s="PYTHON"
>>> print(s)------------------PYTHON
>>> print(s[:])-----------------PYTHON
>>> print(s[0:])---------------PYTHON
>>> print(s[:6])-------------PYTHON

Note: All the above Syntaxes are Moving in Forward Direction with equal Interval.
Syntax- 5: strobj[Begin : End : step]

To understand this Syntax, we have 5 Rules:

1) Here Begin, End and Step can be either +ve or –ve or Both.
2) If Step value is +ve then PVM takes Range of character from Begin Index to
End Index-1 in forward direction provided Begin index < End Index.
3) If step value is –ve then PVM takes Range of character from Begin Index to
End Index +1 in backward direction provided Begin Index > End Index.
4) In Forward Direction, if End Index is 0 then we never get any Output ( ‘ ’ ).
5) In backward direction, if End Index is -1 then we never get Output ( ‘ ’ )

Examples:
-----------------------
>>> s="PYTHON"
>>> s[0:5:2]----------------'PTO'
>>> s[0:6:3]----------------'PH'
>>> s[::]-------------------'PYTHON'
>>> s[::2]------------------'PTO'
>>> s[::3]------------------'PH'
>>> s[3::2]-----------------'HN'
>>> s[-6:-1:2]--------------'PTO'
>>> s[-4:-1:3]--------------'T'
>>> s="PYTHON"
>>> s[0:6:-1]---------------''
>>> s[5:2:-1]---------------'NOH'
>>> s[::-1]-----------------'NOHTYP'
>>> s[::-2]-----------------'NHY'
>>> s[-1:-6:-1]-------------'NOHTY'
>>> "PROG"[::-1]------------'GORP'
>>> "PROG"[::-1][::]--------'GORP'
>>> "PROG"[::-1][::-1]------'PROG'
Data Types in Python
>>> s="PYTHON"
>>> s[:0:-1]----------------'NOHTY'
>>> s[:0:1]----------------- ''
>>> s[:-1:-1]--------------- ''

>>> s="MADAM"
>>> s==s[::-1]-------------- True
>>> "LIRIL"=="LIRIL"[::-1]------True
Data Types in Python

Type Casting Techniques in Python

The purpose of type casting techniques is that “To convert one possible
type of value into another possible types of value.

In Python programming, we have 5 Fundamental type casting techniques.


They are:

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

1) int(): int() is used to converting one possible type of value into “int”
type value.
Syntax: varname= int( float / bool / complex / str)
Examples:float Type Value into int Type Value-->Possible
-------------------
>>> a=10.23
>>> print(a,type(a))-----------10.23 <class 'float'>
>>> b=int(a)
>>> print(b, type(b))-----------10 <class 'int'>
--------------------------------------------------------
Examples:bool Type Value into int Type Value-->Possible
--------------------------------------------------------
>>> a=True
>>> print(a,type(a))-------------True <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------ 1 <class 'int'>
>>> a=False
>>> print(a,type(a))-------------False <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------0 <class 'int'>
Data Types in Python
Examples : Complex Type Value into int Type Value-----
---->Not Possible
--------------------------------------------------------
>>> a=2+3j
>>> print(a,type(a))----(2+3j) <class 'complex'>
>>> b=int(a)----------TypeError: int() argument should
not be 'complex'
--------------------------------------------------------
Examples :
--------------------------------------------------------
>>> a="12" # int str into int type ------>Possible
>>> print(a,type(a))-------------12 <class 'str'>
>>> b=int(a)
>>> print(b, type(b))------------12 <class 'int'>

*********************************************
>>> a="12.34" # float str into int type --- Not Possible
>>> print(a,type(a))--------------12.34 <class 'str'>
>>> b=int(a)----ValueError: invalid literal for int()
with base 10: '12.34'
*********************************************

>>> a="True" # bool str into int type --- Not Possible
>>> print(a,type(a))-------------True <class 'str'>
>>> b=int(a)-------ValueError: invalid literal for int()
with base 10: 'True'
**************************************************
>>> a="2+3j" # complex str into int type ---- Not Possible
>>> print(a,type(a))-------------2+3j <class 'str'>
>>> b=int(a)--------ValueError: invalid literal for
int() with base 10: '2+3j'
****************************************************
>>> a="PYTHON" # Pure Str into int type --- 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 to converting one possible type of value into float
type value.
Syntax: varname = float( int / bool / complex / str )
Data Types in Python

Examples: int Type Value into float Type Value---Possible


--------
>>> a=10
>>> print(a,type(a))----------------10 <class 'int'>
>>> b=float(a)
>>> print(b, type(b))---------------10.0 <class 'float'>

Examples: bool Type Value into float Type Value--->Possible


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

Examples : complex Type Value into float Type Value---


->Not Possible
----------
>>> a=2+3.5j
>>> print(a,type(a))---------(2+3.5j) <class 'complex'>
>>> b=float(a)-----TypeError: float() argument must be
a string or a real number, not 'complex'
--------------------------------------------------------
Examples:
-----------
>>> a="12" # int str into float type ------- Possible
>>> print(a,type(a))----------12 <class 'str'>
>>> b=float(a)
>>> print(b, type(b))-----------12.0 <class 'float'>
*******************************************************
>>> a="12.34" # float str int float -------Possible
>>> print(a,type(a))------12.34 <class 'str'>
>>> b=float(a)
>>> print(b, type(b))-------12.34 <class 'float'>
*******************************************************
>>> a="2+3j" # complex str into float---- Not Possible
>>> print(a,type(a))---------2+3j <class 'str'>
>>> b=float(a)----ValueError: could not convert string
to float: '2+3j'
*******************************************************
>>> a="PYTHON.Java" # Pure String into float---Not possible
Data Types in Python
>>> print(a,type(a))-------PYTHON.Java <class 'str'>
>>> b=float(a)-----------ValueError: could not Convert
string to float:'PYTHON.Java'

3) bool(): bool() is used to convert one possible type of value into bool
type value.
Syntax: varname= bool ( int / float / complex / str )

All none-zeros value are “True”.


All Zero values are “False”.
Examples: int type value into bool type---->Possible
---------
>>> a=100
>>> print(a,type(a))------------100 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>

>>> a=-12
>>> print(a,type(a))----------- -12 <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 type value into bool type-->Possible
>>> a=12.45
>>> print(a,type(a))---------12.45 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))----------True <class 'bool'>
>>> a=0.00000000000000000004
>>> print(a,type(a))-----------4e-20 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>
>>> a=0.0
>>> print(a,type(a))------------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-------------False <class 'bool'>
Data Types in Python
--------------------------------------------------------
Examples: complex type value into bool type---->Possible
--------------------------------------------------------
>>> a=2+3j
>>> print(a,type(a))---------(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))---------0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))---------False <class 'bool'>
--------------------------------------------------------
Examples:
---------
>>> a="123"
>>> print(a,type(a))---------123 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a="12.34"
>>> print(a,type(a))---------12.34 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a="0+j"
>>> print(a,type(a))---------0+j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a="12+3.4j"
>>> print(a,type(a))--------12+3.4j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a="False"
>>> print(a,type(a))--------False <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a="Python"
>>> print(a,type(a))--------Python <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a=" "
>>> print(a,type(a))--------<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>

========================================================
Data Types in Python
Special Point
------------------------------------------------
>>> a=""
>>> print(a,type(a))-------<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------False <class 'bool'>

Mutability and Immutability

Mutability: A mutable object is one which allows to modify/update its


value/content at same ADDRESS.
Ex: list , set , dict …… etc.
Immutability: A Immutable object is one which will satisfy the following
properties:
a) Modification / Updation not possible at same address (if at all the value
modified then the modification value placed in new memory address)
b) Immutable objects never allows/ support item Assignment.
Ex: int , float , str , tuple , frozenset …. Etc.

2) bytes: “bytes” is one of the pre-defined class and treated as sequence


data type. The purpose of byte data type
“To organize sequence of positive numerical integer value range from
(0, 256) i.e. it store value from 0 to 255 (256-1) only”.
For storing the element in an object into an object of bytes, there is no
symbolic notation but we can convert other types of object into an object
of bytes by using bytes ().

Syntax: varname = bytes(object)

On the object of bytes, we can perform both indexing and slicing operations.
An object of bytes belong to immutable because bytes object does not
support item assignment.
Data Types in Python
An object of bytes maintains Insertion Order (Nothing but
whichever order, we insert the data in the same order elements will be
displayed).
Examples:
-----------------------------------------------------
>>> l1=[10,20,34,0,256]
>>> print(l1,type(l1))---[10, 20, 34, 0, 256] <class 'list'>
>>> b=bytes(l1)---ValueError: bytes must be in range(0, 256)
-----------------------------------------------------
>>> l1=[10,-20,34,0,255]
>>> print(l1,type(l1))---[10, -20, 34, 0, 255] <class 'list'>
>>> b=bytes(l1)-----ValueError: bytes must be in range(0, 256)
-------------------------------------------------------
>>> l1=[10,20,34,0,255]
>>> print(l1,type(l1))---[10, 20, 34, 0, 255] <class 'list'>
>>> b=bytes(l1)
>>> print(b,type(b))---b'\n\x14"\x00\xff' <class 'bytes'>
>>> for val in b:
... print(val)
...
10
20
34
0
255

>>> for val in b[0:3]:


... print(val)
...
10
20
34
>>> print(b[0])--------------------- 10
>>> print(b[2])--------------------34
>>> print(b[0:4])--------------- b'\n\x14"\x00'
-----------------------------------------------------
>>> print(b,type(b),id(b))---b'\n\x14"\x00\xff' <class
'bytes'> 2019441206896
>>> print(b[0])--------------10
>>> b[0]=100--------TypeError: 'bytes' object does not
support item assignment
Data Types in Python
3) bytearray: “bytearray” is one of the pre-defined class and treated as
Sequence date type.
The purpose of bytearray data type is that “To organized sequence
of positive Numerical Integer value range from (0 to 256) .i.e. it stores
value from 0 to 255 (256-1) only”.
For storing the element in an object of bytearray, there is no
symbolic notation. But we can convert other type of objects into an
object of bytearray by using bytearray ().

Syntax: varname = bytearray ( object )

On the object of bytearray, we can perform both Indexing and


Slicing Operations.
An object of bytearray belongs to mutable because bytearray
object supports item assignment.
An object of bytearray maintains Insertion order (Nothing but whichever
order, we insert the data, in the same order element will be displayed)
Note: The Functionality of bytearray is exactly similar to bytes but an object
of bytes belongs to immutable and an object of bytearray belongs mutable.
Examples:
----------
>>> l1=[10,20,34,0,256]
>>> print(l1,type(l1))---[10, 20, 34, 0, 256] <class 'list'>
>>> ba=bytearray(l1)--ValueError:byte must be in range(0,256)
>>> l1=[-10,20,34,0,255]
>>> print(l1,type(l1))---[-10, 20, 34, 0, 255] <class 'list'>
>>> ba=bytearray(l1)--ValueError: byte must be in range(0, 256)
--------------------------------------------------------
>>> l1=[10,20,34,0,255]
>>> print(l1,type(l1))---[10, 20, 34, 0, 255] <class 'list'>
>>> ba=bytearray(l1)
>>> print(ba,type(ba),id(ba))---
bytearray(b'\n\x14"\x00\xff')<class 'bytearray'>
2019441802864
Data Types in Python
>>> for kvr in ba:
... print(kvr)
...
10
20
34
0
255
-----------------------------------------------------
>>> for kvr in ba[::-1]:
... print(kvr)
...
255
0
34
20
10
>>> print(ba[0])------------------10
>>> print(ba[-1])-----------------255
>>> ba[1]=9 # Updation on bytearray object---
Possible--It is mutable
>>> for kvr in ba:
... print(kvr)
...
10
9
34
0
255
>>> print(ba,type(ba),id(ba))----
bytearray(b'\n\t"\x00\xff') <class 'bytearray'>
2019441802864

4) range: ‘range’ is one of the pre-defined class and treated as sequence


data type.

The purpose if range data type is “To store sequence of ‘Numerical


integer values’ with ‘Equal Interval’.
On the object of range belongs to immutable because range object
does not support item assignment (it’s become problem in range of
values with interval).
Range data type contains 3 syntax. They are:
Data Types in Python
Syntax-1: varname= range (value)

This syntax generates range of values from 0 to value–1.

Examples:
-----------------
>>> r=range(10)
>>> print(r,type(r))----range(0, 10) <class 'range'>
>>> for i in r:
... print(i)
...
0
1
2
3
4
5
6
7
8
9
>>> for i in r:
... print(i,end=" ")------0 1 2 3 4 5 6 7 8 9

Syntax-2: varname=(begin , End)

This syntax generates range of values from Begin to End-1.

Examples:
-----------------
>>> r=range(20,26)
>>> print(r,type(r))---range(20, 26) <class 'range'>
>>> for i in r:
... print(i)
...
20
21
22
23
24
25
Data Types in Python
>>> for i in r[::-1]:
... print(i)
...
25
24
23
22
21
20
>>> for i in r[0:3]:
... print(i)
...
20
21
22
>>> print(r[0])--------------20

Note: The above two syntaxes are generating range of values in forward
direction with default step or interval as 1.
Syntax-3: varname= (Begin, End, Step)
This syntax generates range of values from Begin to End-1 with equal
interval value of “Step”.
Examples:
-------------------
>>> r=range(50,101,10)
>>> for i in r:
... print(i)
...
50
60
70
80
90
100
-------------------------------------------------------
Data Types in Python
>>> for i in range(10,31,5):
... print(i)
...
10
15
20
25
30
------------------------------------------------------
>>> for val in range(100,1001,100)[::-1]:
... print(val)
...
1000
900
800
700
600
500
400
300
200
100

Special Examples:
-----------------
>>> range(100,1001,100)[2]-------300
>>> range(100,1001,100)[-2]------900
===========================x===========================
Examples:
----------
Q1) 0 1 2 3 4 5 6 7 8 9------------range(10)

>>> for val in range(10):


... print(val)
...
0
1
2
3
4
5
6
7
8
9
-----------------------------------------------------
Data Types in Python
Q2) 10 11 12 13 14 15 16 17 18 -----range(10,19)

>>> for val in range(10,19):


... print(val)
...
10
11
12
13
14
15
16
17
18
-----------------------------------------------------

Q3) 20 22 24 26 28 30---------range(20,31,2)
>>> for val in range(20,31,2):
... print(val)
...
20
22
24
26
28
30
-----------------------------------------------------

Q4) 1000 1010 1020 1030 1040 1050-- range(1000,1051,10)


>>> for val in range(1000,1051,10):
... print(val)
...
1000
1010
1020
1030
1040
1050
-----------------------------------------------------
Data Types in Python
Q5) -1 -2 -3 -4 -5 -6 -7 -8 -9 -10-----
>>> for i in range( -1, -11, -1):
... print(i)
...
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10

Q6)-10 -8 -6 -4 -2 --- range(-10,-1,2)or range(-10,0,2)

>>> for i in range(-10,-1,2):


... print(i)
...
-10
-8
-6
-4
-2
>>> for i in range(-10,0,2):
... print(i)
...
-10
-8
-6
-4
-2
-----------------------------------------------------
Data Types in Python
Q8)-5 -4 -3 -2 0 1 2 3 4 5---range(-5,6,1) or
range(-5,6)-------IMP
>>> for i in range(-5,6,1):
... print(i)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
>>> for i in range(-5,6):
... print(i)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
-----------------------------------------------------
Q9) 1000 900 800 700 600 500-----range(1000,499,-100)
>>> for i in range(1000,499,-100):
... print(i)
...
1000
900
800
700
600
500
-----------------------------------------------------
Data Types in Python
Special Case:
-----------------------------------------------------
>>> 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
-----------------------------------------------------

3) List category data type (Collections Data type/ Data Structure)

The purpose of List Category of Data Type is that “To store Collections
of values or Multiples Values either of Same Type, different Type or Both of
the types with Unique and Duplicate.”
We have two data types in List Category. They are:
1) list 2) tuple

1) list: ‘list’ is one of the pre-defined class and treated as list data type.

The purpose of list data type is “To store Collection of values or


multiples values either of same type, different type or both of the values
with unique and duplicates”.
The elements of list must be stored within Square brackets [ ] and
the elements must be separated by comma.
An object of list belongs to Mutable. To convert any other object
into list type object, we use list().
Syntax: listobject= list(another object)
Data Types in Python
We can create two types of list object. They are:
a) Empty list b) non-empty list

a) empty list: Am empty list is one, which does not contain any elements
and length is 0.

Syntax :- listobj= [ ] or listobj= list()

Examples:
----------
>>> l=[]
>>> print(l,type(l),id(l))---[] <class'list'> 2722448959680
>>> len(l)----------------0
>>> l1=list()
>>> print(l1,type(l1),id(l1))---[] <class'list'>
2722452472064
>>> len(l1)---------------0

b) non-empty list: A non-empty list is one, which contains elements and


length is > 0.
Examples:
----------
>>> l1=[10,20,30,40,10,20]
>>> print(l1,type(l1),id(l1))---------
[10, 20, 30, 40, 10, 20] <class 'list'> 2722448006784
>>> len(l1)-----------------------6
>>> l2=[10,"Rossum",34.56,True]
>>> print(l2,type(l2),id(l2))----------
[10, 'Rossum', 34.56, True] <class 'list'> 2722452472064
>>> len(l2)------------------------4
-----------------------------------------------------
Examples:
----------
>>> l1=[10,20,30,40,10,20]
>>> print(l1,type(l1),id(l1))------------
[10, 20, 30, 40, 10, 20] <class 'list'> 2722448006784
>>> l2=[10,"Rossum",34.56,True]
>>> print(l2,type(l2),id(l2))-----------
[10, 'Rossum', 34.56, True] <class 'list'> 2722448959936
>>> print(l1[0])------------------10
>>> l1[0]=1000
>>> print(l1,type(l1),id(l1))----------
[1000, 20, 30, 40, 10, 20] <class 'list'> 2722448006784
>>> l1[1:4]-----------------[20, 30, 40]
Data Types in Python

Copy Techniques in Python

In Python Programming, we have two types of Copy techniques. They are:


1) Shallow Copy 2) Deep Copy

1) Shallow Copy: In this Shallow Copy process, the following Points will satisfy:

a) The Initial content of both the object are same.


b) Both the objects contents different memory address.
c) Modification on both the object are Independent (Modification are
not reflected to each other).
To Implement Shallow Copy, we use copy ().

Syntax: obj2=obj1.copy()
Examples:
----------
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))---[10, 'Rossum'] 1843503104896
>>> l2=l1.copy()
>>> print(l2,id(l2))---[10, 'Rossum'] 1843499592064
>>> l1.append("Python")
>>> l2.insert(1,"Django")
>>> print(l1,id(l1))---[10,'Rossum','Python'] 1843503104896
>>> print(l2,id(l2))---[10,'Django','Rossum'] 1843499592064

2) Deep Copy: In deep copy process, the following points will satisfy:

a) The Initial content of both the object are same.


b) Both the object contents same memory address.
c) Modification on both the objects are dependent (modification are
reflected to each other).
To Implement Deep copy, we use Assignment Operator (=)

Syntax: object2 = object1


Data Types in Python

Examples:
---------
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))-----[10, 'Rossum'] 1843498922432
>>> l2=l1 # Deep Copy with Assignment Operator
>>> print(l2,id(l2))-----[10, 'Rossum'] 1843498922432
>>> l1.append("Python")
>>> print(l1,id(l1))---[10,'Rossum','Python'] 1843498922432
>>> print(l2,id(l2))---[10,'Rossum','Python'] 1843498922432
>>> l2.insert(2,"Django")
>>> print(l1,id(l1))--[10,'Rossum','Django','Python']
1843498922432
>>> print(l2,id(l2))--[10, 'Rossum', 'Django', 'Python']
1843498922432

Pre-defined functions in list

We know that, on the object of list, we can perform both Indexing


and slicing operations.
Along with these operation, we can also perform many more
operations on the object of list by using pre-defined functions which are
present in list object.

1) append (): This function is used for adding the value to the list object
always at the end.

Syntax: listobj.append(value)

Examples:
----------------------
>>> l1=[]
>>> print(l1,len(l1), id(l1))-----[] 0 2722448959936
>>> l1.append(10)
>>> l1.append(10.5)
>>> print(l1,len(l1), id(l1))---[10, 10.5] 2 2722448959936
>>> l1.append("Rossum")
>>> print(l1,len(l1), id(l1))---[10, 10.5, 'Rossum']
3 2722448959936
>>> l1.append(True)
>>> print(l1,len(l1), id(l1))----
[10, 10.5, 'Rossum', True] 4 2722448959936
Data Types in Python
2) insert() : This function is used for inserting the values at valid existing
index.
Syntax: listboject. Insert (index, value)
(Here index can either +ve or –ve.)

Examples:
--------------------
>>> l2=[10,"Rossum",34.56,True]
>>> print(l2,id(l2))-----[10, 'Rossum', 34.56, True]
2722448006784
>>> l2.insert(2,"Python")
>>> print(l2,id(l2))-----[10, 'Rossum', 'Python',
34.56, True] 2722448006784
>>> l2[-2]=96.66
>>> print(l2,id(l2))-----[10, 'Rossum', 'Python',
96.66, True] 2722448006784

3) clear(): This function is used to removing all the element of list.

Syntax: listobj.clear()

Examples:
-----------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)--[100, 'Rossum', 45.56, 'Python', True]
>>> len(l1)-----5
>>> l1.clear()
>>> print(l1)-------[]
>>> len(l1)-----------0

4) remove() : This function is used for removing First occurrence of


specified element from list on the basis of Based Value.
If the specified element not found in list then we get Value Error.

Syntax: listobj. remove (Value)


Examples:
------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)
[100, 'Rossum', 45.56, 'Python', True]
Data Types in Python
>>> l1.remove(100)
>>> print(l1)-------['Rossum', 45.56, 'Python', True]
>>> l1.remove(45.56)
>>> print(l1)-------['Rossum', 'Python', True]
>>> l1.remove(True)
>>> print(l1)-------['Rossum', 'Python']
>>> l1.remove(100)--------------ValueError:
list.remove(x): x not in list
>>> [].remove(0)-------------ValueError:
list.remove(x): x not in list
>>> list().remove(10)----ValueError: list.remove(x):
x not in list
-----------------------------------------------------
>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)------[10, 20, 10, 30, 10, 20, 20, 10]
>>> l2.remove(10)
>>> print(l2)------[20, 10, 30, 10, 20, 20, 10]
>>> l2.remove(10)
>>> print(l2)------[20, 30, 10, 20, 20, 10]

5) pop(index): This function is used for removing the element from list
based on Index. The index can be either +ve or –ve.

If the index valid then the corresponding element removed from


list and returned. Otherwise we get IndexError.
Syntax: listobj.pop(index)
Examples:
----------------
>>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)-------[10, 20, 10, 30, 10, 20, 20, 10]
>>> l2.pop(2)--------10
>>> print(l2)-------[10, 20, 30, 10, 20, 20, 10]
>>> l2.pop(-1)-------10
>>> print(l2)-------[10, 20, 30, 10, 20, 20]
>>> l2.pop(1)--------20
>>> l2.pop(11)-----IndexError: pop index out of range
-----------------------------------------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> l1.pop(1)-------'Rossum'
>>> print(l1)-------[100, 45.56, 'Python', True]
>>> l2.pop(22)-----IndexError: pop index out of range
>>> [].pop(0)------IndexError: pop from empty list
>>> list().pop(-1)--IndexError: pop from empty list
Data Types in Python
6) pop() : This function is used for removing last element of list. When we
call this function upon empty list object then we get IndexError.
Syntax: listobj.pop()
Examples:
----------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)--[100, 'Rossum', 45.56, 'Python', True]
>>> l1.pop()---True
>>> print(l1)--[100, 'Rossum', 45.56, 'Python']
>>> l1.insert(2,"Python")
>>> print(l1)--[100, 'Rossum', 'Python', 45.56, 'Python']
>>> l1.pop()---'Python'
>>> print(l1)--[100, 'Rossum', 'Python', 45.56]
>>> l1.pop()----45.56
>>> print(l1)--[100, 'Rossum', 'Python']
>>> l1.pop()----'Python'
>>> print(l1)--[100, 'Rossum']
>>> l1.pop()----'Rossum'
>>> print(l1)--[100]
>>> l1.pop()----100
>>> print(l1)--[]
>>> l1.pop()---- -IndexError: pop from empty list

del operator: The operator “del” is used for removing.

a) Based on Indexing ----- del obj [ ]


b) Based on Slicing ---- del obj [Begin:End:Step]
c) Complete object ----- del obj

Examples:
-------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)----[100, 'Rossum', 45.56, 'Python', True]
>>> del l1[2] # Index Based Removal
>>> print(l1)----[100, 'Rossum', 'Python', True]
>>> del l1[1:3] # Slicing Based Removal
>>> print(l1)----[100, True]
>>> del l1 # Removing entire object
>>> print(l1)----NameError: name 'l1' is not defined.
Data Types in Python

7) index(): This function obtains index of first occurrence of the specified


element.
Syntax: listobj.index(value)
If the value does not exit then we get ValueError.
Examples:
-------------------
>>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)----[10, 20, 10, 30, 10, 20, 20, 10]
>>> l2.index(10)---0
>>> l2.index(100)---ValueError: 100 is not in list
>>> l2.index(20)-----1

8) count(): This function finds number of occurrence of a particular element.


Syntax: listobj.count(value)
If the value does not exit then this function gives 0.
Examples:
---------------------
>>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)------[10, 20, 10, 30, 10, 20, 20, 10]
>>> l2.count(10)----4
>>> l2.count(20)----3
>>> l2.count(30)----1
>>> l2.count(300)---0
>>> list().count(0)--0
-----------------------------------------------------
>>> list([10,10,0]).count(0)------1
>>> list([10,10,0]).count(10)-----2
>>> list([10,10,0]).count(100)----0

9) copy(): This function is used for copying the content of one object into
another object (implements Shallow Copy).
Syntax: listobj2=listobj1.copy()
Data Types in Python
Examples:
-------------------
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))---[10, 'Rossum'] 1843503104896
>>> l2=l1.copy() # shallow Copy
>>> print(l2,id(l2))---[10, 'Rossum'] 1843499592064
>>> l1.append("Python")
>>> l2.insert(1,"Django")
>>> print(l1,id(l1))--[10, 'Rossum', 'Python'] 1843503104896
>>> print(l2,id(l2))--[10, 'Django', 'Rossum'] 1843499592064
-----------------------------------------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> l2=l1[1:4] # Slice Based Copy is called Shallow Copy
>>> print(l1,id(l1))----
[100, 'Rossum', 45.56, 'Python', True] 1843499592064
>>> print(l2,id(l2))----
['Rossum', 45.56, 'Python'] 1843503104896
-----------------------------------------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> l2=l1[::] # Slice Based Copy is called Shallow Copy
>>> print(l1,id(l1))
[100, 'Rossum', 45.56, 'Python', True] 1843498922432
>>> print(l2,id(l2))
[100, 'Rossum', 45.56, 'Python', True] 1843499592064

10) reverse(): This function is used to obtaining reverse of the element of


list (front to back & back to front).
Syntax: listobj.reverse()
Examples:
----------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1,id(l1))-----[100, 'Rossum', 45.56,
'Python', True] 1843503104896
>>> l1.reverse()
>>> print(l1,id(l1))-----[True, 'Python', 45.56,
'Rossum', 100] 1843503104896

11) sort(): This function is used for sorting the data in either ascending
Order or descending order.
By-default we get in ascending order.
Syntax: listobject.sort(reverse=True or False)
Data Types in Python

Here, reverse= True: Descending order.


reverse= False: Ascending order.(by- dafult)

Examples:
--------------------
>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1)-----[10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> l1.sort() # default value of reverse=False
>>> print(l1)-----[-4, 0, 2, 3, 10, 12, 14, 34, 56]
-----------------------------------------------------
>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1)-----[10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> l1.sort(reverse=False)
>>> print(l1)-----[-4, 0, 2, 3, 10, 12, 14, 34, 56]
-----------------------------------------------------
>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1)-----[10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> l1.sort(reverse=True)
>>> print(l1)-----[56, 34, 14, 12, 10, 3, 2, 0, -4]
-----------------------------------------------------
Examples:
-------------------
l1=["Trump","Biden","Putin","Modi","Rossum","Adam"]
>>> print(l1)---['Trump', 'Biden', 'Putin', 'Modi',
'Rossum', 'Adam']
>>> l1.sort(reverse=False)
>>> print(l1)---['Adam', 'Biden', 'Modi', 'Putin',
'Rossum', 'Trump']
l1=["Trump","Biden","Putin","Modi","Rossum","Adam"]
>>> print(l1)---['Trump', 'Biden', 'Putin', 'Modi',
'Rossum', 'Adam']
>>> l1.sort(reverse=True)
>>> print(l1)---['Trump', 'Rossum', 'Putin', 'Modi',
'Biden', 'Adam']
----------------------------------------------------
Examples:
---------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)------
[100, 'Rossum', 45.56, 'Python', True]
>>> l1.sort()-----TypeError: '<' not supported
between instances of 'str' and 'int'
Data Types in Python
12) extend(): This function is used for adding the content of one list
object to another list object.
Syntax: listobj1.extend(listobj2)
here listobj2 are added to listobj1

Examples:
------------------
>>> l1=[10,20,30]
>>> l2=["RS","DR","TS"]
>>> print(l1)------------[10, 20, 30]
>>> print(l2)------------['RS', 'DR', 'TS']
>>> l1.extend(l2)
>>> print(l1)---------[10, 20, 30, 'RS', 'DR', 'TS']
>>> print(l2)------------['RS', 'DR', 'TS']
Data Types in Python

Inner or nested list

The process of defining one list inside another list is called inner list /
nested list.
On the inner list, we can perform both indexing and slicing operations.
On the inner list object, we can apply all pre-defined functions of list.

Syntax: listobj1= [ val1, val2...[val11,val12..val1n], [val 21,val 22...val 2n],


.... val - n]
Here listobj is called outer list.
[val11, val12, … val1n] is called one inner list of listobj1.
[val21, val22,..val2n] is called another inner list of listobj1.
Data Types in Python
Examples:
-------------------------------
>>> lst=[10,"Rossum", [19,15,18] , [77,67,79], "OUCET" ]
>>> print(lst,type(lst))
[10,'Rossum',[19, 15, 18],[77, 67, 79],'OUCET'] <class'list'>
>>> print(lst[0])---------10
>>> print(lst[1])---------Rossum
>>> print(lst[2])---------[19, 15, 18]
>>> print(lst[3])---------[77, 67, 79]
>>> print(lst[4])---------OUCET
>>> print(lst[-2])--------[77, 67, 79]
>>> print(lst[-1])--------OUCET
>>> print(lst)
[10, 'Rossum', [19, 15, 18], [77, 67, 79], 'OUCET']
>>> lst[2].append(16)
>>> print(lst)
[10, 'Rossum', [19, 15, 18, 16], [77, 67, 79], 'OUCET']
>>> lst[-2].insert(1,73)
>>> print(lst)
[10, 'Rossum', [19, 15, 18, 16], [77, 73, 67, 79], 'OUCET']
>>> lst[-3].sort()
>>> print(lst)
[10, 'Rossum', [15, 16, 18, 19], [77, 73, 67, 79], 'OUCET']
>>> lst[-2].sort(reverse=True)
>>> print(lst)
[10, 'Rossum', [15, 16, 18, 19], [79, 77, 73, 67], 'OUCET']
>>> lst[2][0::2]-------------[15, 18]
>>> lst[3][1]-----------------77
>>> lst[3][-3]----------------77

2) tuple: ‘tuple’ is the one of the pre-defined class and treated as list data type.

The purpose of tuple data type is that “To store collection of


values or multiple values either of same type or both the types with
unique and duplicate”.
The element of tuple must be stored within braces () and the
elements must be separated by commas.
An object of tuple maintains insertions order.
On the object of tuple, we can perform both indexing and slicing operations.
An object of tuple belongs to immutable.
To convert any other object into tuple type object, we use tuple ().
Data Types in Python
Syntax: tupleobject = tuple(another object)

We can create two types of tuple object. They are:

a) empty tuple: An empty tuple is one, which does not contain any
element and its length is 0.

Syntax: tupleobj=() or tupleobj=tuple()

Examples:
----------
>>> t=()
>>> print(t,type(t),id(l))---() <class 'tuple'>
2722448959680
>>> len(t)----------0
>>> l1=tuple()
>>> print(l1,type(l1),id(l1))---() <class 'tuple'>
2722452472064
>>> len(l1)--------------0

b) non- empty tuple: A non-empty tuple is one, which contains elements


and its length is > 0.
Syntax: tupleobj=(val1,val2…val-n) or tupleobj= val1, val2….val-n.

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


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

Examples:
------------------------
>>> t1=(10,20,30,40,10,10)
>>> print(t1,type(t1))------(10, 20, 30, 40, 10, 10)
<class 'tuple'>
>>> t2=(10,"Ram",34.56,True,2+4.5j)
>>> print(t2,type(t2),id(t2))---(10, 'Ram', 34.56,
True, (2+4.5j)) <class 'tuple'> 2328568492208
>>> t2[0]----------------10
>>> t2[1]------------------'Ram'
>>> t2[-1]-----------------(2+4.5j)
>>> t2[1:4]---------------------('Ram', 34.56, True)
>>> t2[2]=56.78-----------TypeError: 'tuple' object
does not support item assignment
Data Types in Python
--------------------------------------------------
>>> t1=()
>>> print(t1,len(t1))------------() 0
(OR)
>>> t2=tuple()
>>> print(t2,len(t2))------------() 0
-----------------------------------------------------
>>> l1=[10,"Rossum"]
>>> print(l1,type(l1))---[10, 'Rossum'] <class 'list'>
>>> t1=tuple(l1)
>>> print(t1,len(t1))----(10, 'Rossum') 2
-----------------------------------------------------
>>> a=10,"KVR","Python",True # wi8thout braces ( )
>>> print(a,type(a))---(10, 'KVR', 'Python', True)
<class 'tuple'>
>>> a=10,
>>> print(a,type(a))-------(10,) <class 'tuple'>
>>> a=10
>>> print(a,type(a))-------10 <class 'int'>
>>> t=tuple(a)---TypeError: 'int' object is not iterable
>>> t=tuple(a,)--TypeError: 'int' object is not iterable
>>> t=tuple((a))--TypeError: 'int' object is not iterable
>>> t=(a,) # correct conversion
>>> print(t,type(t))--------(10,) <class 'tuple'>
>>> print(a,type(a))---------10 <class 'int'>

Pre-defined functions in tuple

tuple object contains the following functions:


a) count() b) index()

Examples:
----------------------
>>> t1=(10,"Ram",10,"Ram","python")
>>> t1-----------(10, 'Ram', 10, 'Ram', 'python')
>>> t1.count(10)---------2
>>> t1.index("Ram")------1

The following functions not present in tuple:


Append() Insert() Clear() Remove() Pop(index)
Pop() Copy() Reverse() Sort() Extend()
Data Types in Python

Inner tuple or nested tuple:

The process of defining one tuple inside of another tuple is called


inner tuple/ nested tuple.
On the inner tuple, we can perform both indexing and slicing
operations.
On the inner tuple object, we can apply count () and index()
functions only.

Syntax: tplobj1= ( val1,val2...(val11,val12…val1n), (val21,val22…val2n), val-n)

Here tplobj is called outer tuple.


(val11,val12…val1n) is called one inner tuple of tplobj.
(val21,val22…val2n) is called another inner tuple of tplobj.

Examples:
-------------------------
>>> t1=(10,"Rossum",(14,17,16),(56,34,78),"OUCET")
>>> print(t1,type(t1))---(10, 'Rossum', (14, 17, 16),
(56, 34, 78), 'OUCET') <class 'tuple'>
>>> t1[2]-----------------(14, 17, 16)
>>> t1[3]------------------(56, 34, 78)
-----------------------------------------------------
>>> t1=(10,"Rossum",[14,17,16],(56,34,78),"OUCET")
>>> print(t1,type(t1))-----(10, 'Rossum', [14, 17,
16], (56, 34, 78), 'OUCET') <class 'tuple'>
>>> t1[2]-----------------[14, 17, 16]
>>> print(t1[2],type(t1[2]))---[14, 17, 16] <class 'list'>
>>> t1[2].sort()
>>> print(t1,type(t1))-----(10, 'Rossum', [14, 16,
17], (56, 34, 78), 'OUCET') <class 'tuple'>
>>> del t1[3]--------------TypeError: 'tuple' object
doesn't support item deletion

Note: It is possible to write one list in another list.


It is possible to write one tuple in another tuple.
It is possible to write one list in another tuple.
It is possible to write one tuple to another list.
Data Types in Python

4) Set Category Data Types (Collections Data Types or Data Structures)

The purpose of set Category Data type is that “To store Collection
or multiple values either of same type or different type or both the types
with unique values (No duplicates are allowed)”.
We have two data types in set category, they are:
1) set (mutable and immutable) 2) frozenset (immutable)

1) set (mutable and immutable): “set” is one of the pre-defined class and
treated as set data type.

The purpose of set data type is that “To store collection or


multiple values either of same type or different type or both types with
unique values (No duplicates are allowed)”.

The elements of set must be organised within curly brackets { }


and elements must be separated by comma.

An object of set does not maintain insertion order because PVM


displays any order of multiple possibilities.

On the object of set, we can’t perform Indexing and slicing


operations because set object does not maintain insertion order.

An object of set belongs to immutable (because of ‘set’ object


does not support item assignment) and also mutable (because in the case
of add() ).

By using set class, we have two types of set objects, they are:

a) empty set b) non-empty set

a) empty set: An empty set is one, which doen not contain any elements
and whose length is 0.

Syntax: setobj = set()


Data Types in Python

b) non-empty set: A non-empty set is one, which contains elements and


whose length is > 0

Syntax: setobj = { val1,val2…val-n }

To convert one type of object into set type object, we use set().

Syntax: setobj = setobj = set(obj)

Examples:
-----------------------
>>> s1={10,20,30,40,50,10,10,20,75}
>>> print(s1,type(s1))-----------------{50, 20, 40,
10, 75, 30} <class 'set'>
>>> s1={10,20,25,35,10,20}
>>> print(s1,type(s1))-------------------{25, 10, 35,
20} <class 'set'>
>>> s1[0]----------------TypeError: 'set' object is
not subscriptable
>>> s1[0:3]--------------TypeError: 'set' object is
not subscriptable
-----------------------------------------------------
-------
>>> s1={10,20,30,40,50}
>>> print(s1,id(s1))-------------------------------
{50, 20, 40, 10, 30} 1473821509440
>>> s1[0]=100-------------TypeError: 'set' object
does not support item assignment
>>> s1.add("KVR")
>>> print(s1,id(s1))------------------{50, 20, 40,
10, 'KVR', 30} 1473821509440
-----------------------------------------------------
>>> s1=set()
>>> print(s1,type(s1))------------------{} <class
'set'>
>>> len(s1)------------0
>>> s2={10,20,30,10,20}
>>> print(s2,type(s2))---------------{10, 20, 30}
<class 'set'>
>>> len(s2)-------------------3
-----------------------------------------------------
Data Types in Python
>>> l1=[10,20,10,20,"Python",23.45]
>>> s1=set(l1)
>>> print(s1)-----------------{10, 20, 23.45,
'Python'}
>>> t1=tuple(s1)
>>> print(t1,type(t1))------------(10, 20, 23.45,
'Python') <class 'tuple'>
>>> t1=list(s1)
>>> print(t1,type(t1))------------[10, 20, 23.45,
'Python'] <class 'list'>

Pre-defined functions in set

On the object of set, we can perform various operations by using


the pre-defined functions in set.

Set contains the following pre-defined functions:

1) add(): This function is use for adding the elements to set object.

Synatx: setobj. add(value)

Examples:
----------------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))--------------{10,
'Rossum'} <class 'set'> 1473821509888
>>> s1.add("python")
>>> s1.add(34.56)
>>> print(s1,type(s1),id(s1))-------{10, 'Rossum',
34.56, 'python'} <class 'set'> 1473821509888

2) clear(): This function is use for removing all the elements from the set.

Syntax: setobj.clear()
=>Examples:
------------------------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))------------{10,
'Rossum'} <class 'set'> 1473821508992
>>> s1.clear()
>>> print(s1,type(s1),id(s1))-------------set()
<class 'set'> 1473821508992
Data Types in Python
3) remove(): This function is used for removing an element from set object.

Syntax: setobj.remove(value)

If the value not exists in the setobj then we get KeyError.


Examples:
-------------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))------------------{10,
'Rossum'} <class 'set'> 1473821509888
>>> s1.remove(10)
>>> print(s1,type(s1),id(s1))--------------{'Rossum'}
<class 'set'> 1473821509888
>>> s1.remove("Rossum")
>>> print(s1,type(s1),id(s1))-------------set()
<class 'set'> 1473821509888
----------------------------------------------
>>> s1={10,"Rossum"}
>>> s1.remove(100)----------KeyError: 100
>>> s1.remove("python")-----------KeyError: 'python'
>>> set().remove(100)---------------KeyError: 100
>>> print(set().clear())----------------None
-----------------------------------------------------
4) discard(): This function is used for removing an element from set object.

Syntax: setobj.discard(value)

If the value does not exists in setobj then we never get any error.
Examples:
----------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))--------------------{10,
'Rossum'} <class 'set'> 1473821509664
>>> s1.discard(10)
>>> print(s1,type(s1),id(s1))---------------
{'Rossum'} <class 'set'> 1473821509664
>>> s1.discard(100)----------No Error will come
>>> print(s1,type(s1),id(s1))---------------
{'Rossum'} <class 'set'> 1473821509664
>>> s1.discard("Rossum")
>>> print(s1,type(s1),id(s1))---------------set()
<class 'set'> 1473821509664
>>> s1.discard(100)------------No Error will come
-----------------------------------------------------
Data Types in Python
5) pop(): This function is used for removing any arbitrary element from setobj.

Syntax: setobj.pop()

Examples:
----------------------
>>> s1={10,"Rossum",23.45,"Python",True,2+3j} # No
output is shown
>>> s1.pop()------------True
>>> len(s1)----------------5
>>> s1.pop()-----------23.45
>>> len(s1)-------------4
>>> s1.pop()-------------'Python'
>>> len(s1)-------------3
>>> s1.pop()-----------10
>>> len(s1)--------------2
>>> s1.pop()------------'Rossum'
>>> len(s1)-----------1
>>> s1.pop()-----------(2+3j)
>>> len(s1)-------------0
>>> print(s1)-------------set()
>>> s1.pop()-------KeyError: 'pop from an empty set'
>>> set().pop()----KeyError: 'pop from an empty set'
>>> set().discard(10) # No Error
>>>set().remove(10)----------KeyError :10
-----------------------------------------------------
Special Note:
----------------------
>>> s2={10,20,20,30,50,"python",34.56}
>>> print(s2)---------{34.56, 50, 20, 10, 'python',
30} Output Shown
>>> s2.pop()----------34.56
>>> print(s2)-----------{50, 20, 10, 'python', 30}
>>> s2.pop()------------50
>>> print(s2)------------{20, 10, 'python', 30}
>>> s2.pop()-------------20
>>> print(s2)-------------{10, 'python', 30}
>>> s2.pop()-------------10
>>> print(s2)-------------{'python', 30}
>>> s2.pop()---------------'python'
>>> print(s2)------------{30}
>>> s2.pop()-------------30
>>> print(s2)----------------set()
>>> s2.pop()------KeyError: 'pop from an empty set'
-----------------------------------------------------
Data Types in Python

6) copy(): This function is used for copying the content of one setobject
into another set object.

Syntax: setobj2= setobj1.copy()


Examples:
------------------
>>> s3={12,"Django","Python"}
>>> print(s3,id(s3))----------------{12, 'Django',
'Python'} 1473821510784
>>> s4=s3.copy() # Shallow Copy
>>> print(s4,id(s4))-------------{12, 'Django',
'Python'} 1473821511008
>>> s3.add("DS")
>>> s4.add("Flask")
>>> print(s3,id(s3))--------------{'DS', 12,
'Django', 'Python'} 1473821510784
>>> print(s4,id(s4))--------------{'Flask', 12,
'Django', 'Python'} 1473821511008
-----------------------------------------------------
Deep Copy on sets
---------------------------
>>> s3={12,"Django","Python"}
>>> s4=s3 # Deep Copy
>>> print(s3,id(s3))-------------{12, 'Django',
'Python'} 1473821510112
>>> print(s4,id(s4))-------------{12, 'Django',
'Python'} 1473821510112
>>> s4.add("Flask")
>>> print(s3,id(s3))-----------{'Flask', 12,
'Django', 'Python'} 1473821510112
>>> print(s4,id(s4))------------{'Flask', 12,
'Django', 'Python'} 1473821510112
-----------------------------------------------------

7) union(): This function is used for obtaining all Unique values from setobj1
and setobj2 and placed them in setobj3.

Syntax: setobj3= setobj1.union(setobj2)


(or)
setobj3= setobj2.union(setobj1)
Data Types in Python

Examples:
------------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.union(s2)
>>> print(s3)------------{40, 10, 15, 20, 25, 30}
OR
>>> s1.union(s2)-------------{40, 10, 15, 20, 25, 30}
-----------------------------------------------------
>>> s1={"Python","Django","DS"}
>>> s2={10,"Python",23.45}
>>> s3=s1.union(s2)
>>> print(s3)---{'Python', 'Django', 23.45, 10, 'DS'}
-----------------------------------------------------

8) intersection(): This function is used for obtaining Common values from


setobj1 and setobj2 and placed them in setobj3.

Syntax: setobj3= setobj1.intersection(setobj2)


Or
setobj3= setobj2.intersection(setobj1)

Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.intersection(s2)
>>> print(s3)------------------{10, 20}
-----------------------------------------------------
>>> s1={"Python","Django","DS"}
>>> s2={10,"Python",23.45}
>>> s3=s1.intersection(s2)
>>> print(s3)-------------{'Python'}
>>> s1={10,20,30,40}
>>> s2={15,25,100,200}
>>> s3=s1.intersection(s2)
>>> print(s3)--------------set()
-----------------------------------------------------
Data Types in Python

9) difference(): This function is user for removing the common element


from both setobj1 and setobj2 and takes remaining
element from setobj1 and place them in setobj3.

Syntax: setobj3= setobj1.difference(setobj2)

This function also removes the common element from setobj2 and
setobj1 and takes remaining element from setobj2 and placed them in setobj3.

Syntax: setobj3= setobj2.difference(setobj1)

Examples:
-----------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.difference(s2)
>>>print(s3)-------------{40, 30}
--------------------------------------------------
>>> s3=s2.difference(s1)
>>> print(s3)------------{25, 15}
----------------------------------------------------

10) symmetric difference(): This function removes the common element


from setobj1 and setobj2 and takes the remaining element from
setobj1 and setobj2 and placed them in setobj3.

Syntax: setobj3= setobj1.symmetric_difference(setobj2)


Or
setobj3= setobj2.symmetric_difference(setobj1)

Examples:
-----------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3)-----------------------{40, 15, 25, 30}
-----------------------------------------------------
>>> s4=s2.symmetric_difference(s1)
>>> print(s4)-----------------{40, 15, 25, 30}
-----------------------------------------------------
Data Types in Python
Special Examples:
-----------------------------------------
>>> tp={"Kohli","Ram","Rossum"}
>>> allcptp=cp.union(tp)
>>> print(allcptp)--------------{'Sachin', 'Ram',
'Rohit', 'Kohli', 'Rossum'}
>>> allcptp=cp|tp # Bitwise OR
>>> print(allcptp)----------------{'Sachin', 'Ram',
'Rohit', 'Kohli', 'Rossum'}
--------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp)--------------{'Kohli'}
>>> bothcptp=cp&tp # Bitwise AND
>>> print(bothcptp)---------------{'Kohli'}
-----------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> onlycp=cp.difference(tp)
>>> print(onlycp)------------------{'Sachin',
'Rohit'}
>>> onlycp=cp-tp # Arithmetic Operator -
>>> print(onlycp)------------{'Sachin', 'Rohit'}
---------------------------------------------
>>> onlytp=tp.difference(cp)
>>> print(onlytp)----------{'Ram', 'Rossum'}
>>> onlytp=tp-cp # Arithmetic Operator -
>>> print(onlytp)-----------{'Ram', 'Rossum'}
-----------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> cptponly=cp.symmetric_difference(tp)
>>> print(cptponly)--------------{'Sachin', 'Ram',
'Rohit', 'Rossum'}
>>> cptponly=cp^tp # Bitwise XOR
>>> print(cptponly)--------------{'Sachin', 'Ram',
'Rohit', 'Rossum'}
-----------------------------------------------------
Data Types in Python
11) update(): This function updates the setobj1 values with setobj2 values.

Syntax: setobj.update(setobj2)
Examples:
>>> s1={10,20,30}
>>> s2={"python","Java","Data Science","IOT"}
>>> s3=s1.update(s2)
>>> print(s3)-------------None
>>> print(s1)---------{20, 'python', 'IOT', 10,
'Java', 30, 'Data Science'}
>>> print(s2)----------{'Java', 'python', 'IOT',
'Data Science'}
-----------------------------------------------------
>>> ur={10,"Ram"}
>>> skill={"Python","Java","IOT",10}
>>> ur.update(skill)
>>> print(ur)----{'Python', 'Ram', 'IOT', 10, 'Java'}
>>> print(skill)----{'Python', 10, 'Java', 'IOT'}
-----------------------------------------------------

2) frozenset: ‘frozenset’ is one of the pre-defined class and treated as set


data type.

The purpose of frozenset data type is that “To store multiple


values of either of same type or different type or both types with unique
values in single object”.

The element set must be organised with curly braces { } and value
separated by comma and those value can be converted into frozenset by
using frozenset().

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

An object of frozenset does not maintain insertion order because


PVM display any possibilities of element of frozenset.

Since frozenset object does not maintain insertion order, we can’t


perform Indexing and slicing operations (frozenset object is not subscript-able)
Data Types in Python

An object of frozenset belongs to immutable (in this case of


frozenset object does not support item assignment and adding element
also not possible)

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


belongs to both immutable (in case of item assignment) and mutable (in
case of add()) where as an object of frozenset belongs to immutable.

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

Pre-defined functions in frozenset

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

Examples:
-----------------------------------------------------
>>> s1={10,20,30,40}
>>> s2={15,25,30,40}
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1)-------frozenset({40, 10, 20, 30})
>>> print(fs2)-------frozenset({40, 25, 30, 15})
>>> fs3=fs1.union(fs2)
>>> print(fs3)----frozenset({40, 10, 15, 20, 25, 30})
>>> fs4=fs1.intersection(fs2)
>>> print(fs4)-------frozenset({40, 30})
>>> fs5=fs1.difference(fs2)
>>> print(fs5)-------frozenset({10, 20})
>>> fs6=fs2.difference(fs1)
>>> print(fs6)-------frozenset({25, 15})
Data Types in Python
>>> fs7=fs2.symmetric_difference(fs1)
>>> print(fs7)-------frozenset({10, 15, 20, 25})
>>> fs7=fs1.symmetric_difference(fs2)
>>> print(fs7)-------frozenset({10, 15, 20, 25})
-----------------------------------------------------
>>> s1={10,20,30,40}
>>> fs1=frozenset(s1)
>>> fs2=fs1.copy()
>>> print(fs1,id(fs1))---frozenset({40, 10, 20, 30})
2299638113984
>>> print(fs2,id(fs2))---frozenset({40, 10, 20, 30})
2299638113984
Data Types in Python

>>> cp={"sachin","rohit","kohli"}
>>> tp={"rossam","kohli","ram"}
>>> ap= cp.union(tp)
>>> print("all players=",ap)---all players= {'rohit', 'ram', 'sachin', 'rossam', 'kohli'}
>>> ct= cp.intersection(tp)
>>> print("cricket and tennis player",ct)----cricket and tennis player {'kohli'}
>>> oc= cp.difference(tp)
>>> print("only cricket player=",oc)----only cricket player= {'sachin', 'rohit'}
>>> ot= tp.difference(cp)
>>> print("only tennis player=",ot)-----only tennis player= {'ram', 'rossam'}
>>> ex= cp.symmetric_difference(tp)
>>> print("exclusive player of cricket and tennis=",ex)------
exclusive player of cricket and tennis= {'rohit', 'sachin', 'ram', 'rossam'}
Data Types in Python

5. dict category data type (collection data types or data structures)

The purpose of dict category data type is that “To organise the data
in the form of kyes:values”.

To organize the data in the form (key:value), we use predefined


class called ‘dict’.

‘dict’ is one of the predefined class and treated as dict category data
type.

The element of dict must be organised in the form curly braces { }


and {key,values} and must be separated by comma.

An the object of dict maintains insertion order.

On the object of dict, we can’t perform Indexing and Slicing


operations.

An object of dict belongs to mutable. In other words, the values of


keys are belongs to immutable and values of values are belongs to
mutable.
By using dict class, we can create two types of dict objects, they are:

a) empty dict b) non-empty dict

a) empty dict: An empty dict is one, which does not contains any
element and whose length is 0.

Syntax: dictobj={ } or dictobj= dict()

Syntax for adding (keys,values) to empty dict object:

Dictobj[key1]=value1
Dictobj[key2=value2
---------------------------
Dictonj[key-n]=value-n
Data Types in Python
b) non-empty dict: A non-empty dict is one, which contains element and
whose length is >0.

Syntax: dictobj={key1:val1,key2:val2…key-n:val-n}

Here key1,key2…key-n are kyes and they are unique and they can be
either strs or numerics.

Here val1,val2…val-n are called values and they may be unique or


duplicateand the can be either strs or numerics.

Examples:
--------------------
>>> d1={}
>>> print(d1,type(d1))-------{} <class 'dict'>
>>> len(d1)---------------0
>>> d2={10:1.2,20:2.5,30:2.5,40:4.5}
>>> print(d2,type(d2))----{10: 1.2, 20: 2.5, 30: 2.5,
40: 4.5} <class 'dict'>
>>> len(d2)------------4
-----------------------------------------------------
>>> d3=dict()
>>> print(d3,type(d3),len(d3))----{}<class 'dict'> 0
>>> d1={"Rossum":"Python","Ritche":"C",
"Gosling":"Java"}
>>> print(d1,type(d1))----{'Rossum': 'Python',
'Ritche': 'C', 'Gosling': 'Java'} <class 'dict'>
>>> d2={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d2)-----{10: 'Apple', 20: 'Mango', 30:
'Kiwi', 40: 'Sberry'}
-----------------------------------------------------
>>> print(d2[0])--------KeyError: 0
>>> print(d2[10])---------Apple
>>> print(d2[40])--------Sberry
>>> print(d2[400])--------KeyError: 400
-----------------------------------------------------
>>> d1={}
>>> print(d1,type(d1),len(d1), id(d1))----{} <class
'dict'> 0 2299637840384
>>> d1[100]="Rossum"
>>> d1[101]="Ritche"
>>> d1[102]="Travis"
>>> d1[103]="MCKinney"
Data Types in Python
>>> print(d1,type(d1),len(d1), id(d1))----{100:
'Rossum', 101: 'Ritche', 102: 'Travis', 103:'MCKinney'}
<class 'dict'> 4 2299637840384
>>> d1[100]="Guido"
>>> print(d1,type(d1),len(d1), id(d1))-----{100:
'Guido', 101: 'Ritche', 102: 'Travis',
103:'MCKinney'} <class 'dict'> 4 2299637840384

Pre-defined functions in dict

To do various operations on dict object, we use the predefined


functions present in dict object.

1) clear(): This function is used for removing all the elements from dict.

Syntax: dictobj.clear()
Examples:
-----------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))----------------{100: 'Rossum',
101: 'Gosling', 102: 'Ritche'} 3
>>> d1.clear()
>>> print(d1,len(d1))--------------{} 0
-----------------------------------------------------

2) pop(): This function removes(key,value) from dict by passing value of key.

If value of key does not exists then we get KeyError.

Syntax: dictobj.pop(key)
Examples:
------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))------------------{100:
'Rossum', 101: 'Gosling', 102: 'Ritche'} 3
>>> d1.pop(100)---------------'Rossum'
>>> print(d1,len(d1))------------{101: 'Gosling',
102: 'Ritche'} 2
>>> d1.pop(101)------------'Gosling'
Data Types in Python
>>> print(d1,len(d1)-------{102: 'Ritche'} 1
>>> d1.pop(103)--------------KeyError: 103
-----------------------------------
>>> dict().pop(100)----------------KeyError: 100
>>> {}.pop(101)----------KeyError: 101
-----------------------------------------------------

3) popitem(): This function is used for removing last (key.value) from


non-empty-dict object.

When we call popitem() on empty dict object then we get KeyError.

Syntax: dictobj.popitem()

Examples:
------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))--------------{100: 'Rossum',
101: 'Gosling', 102: 'Ritche'} 3
>>> d1.popitem()----------------(102, 'Ritche')
>>> print(d1,len(d1))-------------{100: 'Rossum',
101: 'Gosling'} 2
>>> d1.popitem()----------(101, 'Gosling')
>>> print(d1,len(d1))-----------{100: 'Rossum'} 1
>>> d1.popitem()--------------(100, 'Rossum')
>>> print(d1,len(d1))--------------{} 0
>>> d1.popitem()---------------KeyError: 'popitem():
dictionary is empty'
--------------------------------------------------------
>>> {}.popitem()---KeyError:'popitem():dictionary is empty'
>>> dict().popitem()----KeyError: 'popitem():
dictionary is empty'

4) copy(): This function copy the contain of dict object into another dict
object(Implementing as shallow copy)

Syntax: dictobj2=dictobj1.copy()

Examples:
--------------------
>>> d1={100:"Rossum",101:"Gosling"}
>>> print(d1,id(d1))---------------{100: 'Rossum',
101: 'Gosling'} 2002260856320
>>> d2=d1.copy() # shallow copy
Data Types in Python
>>> print(d2,id(d2))-----------{100: 'Rossum', 101:
'Gosling'} 2002260855808
>>> d1[110]="Travis"
>>> d2[210]="Kinney"
>>> print(d1,id(d1))---{100: 'Rossum', 101:
'Gosling', 110: 'Travis'} 2002260856320
>>> print(d2,id(d2))---{100: 'Rossum', 101:
'Gosling', 210: 'Kinney'} 2002260855808
-----------------------------------------------------

5) get(): This function is user for getting value of values by passing value
of key.
If the value of key does not exists then we get Non as resultant value.

Syntax: dictobj.get(key)
Examples:
----------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1)--------------{100: 'Rossum', 101:
'Gosling', 102: 'Ritche'}
>>> d1[100]------------------'Rossum'
>>> d1[101]-----------------'Gosling'
>>> d1[102]------------------'Ritche'
>>> d1.get(100)------------'Rossum'
>>> d1.get(101)------------'Gosling'
>>> d1.get(102)-----------'Ritche'
>>> d1[103]---------------KeyError: 103
>>> d1.get(103)---------------No Result
>>> print(d1.get(103))---None--kwd--value of NoneType
-----------------------------------------------------

6) values(): This function gives list of values of value.

Syntax: dictobj.values() or values= dict.values()


Examples:
-----------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1)-----------{100: 'Rossum', 101:
'Gosling', 102: 'Ritche'}
>>> d1.values()----------dict_values(['Rossum',
'Gosling', 'Ritche'])
Data Types in Python
>>> for v in d1.values():
... print(v)
...
Rossum
Gosling
Ritche
(OR)

>>> vals=d1.values()
>>> print(vals)-------------dict_values(['Rossum',
'Gosling', 'Ritche'])
>>> for v in vals:
... print(v)
...
Rossum
Gosling
Ritche
-----------------------------------------------------

7) keys(): This function gives list of values of key.

Syntax: dictobj.keys() or ks= dictobj.keys()


Examples:
----------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1)
{100: 'Rossum', 101: 'Gosling', 102: 'Ritche'}
>>> d1.keys()
dict_keys([100, 101, 102])
>>> for k in d1.keys():
... print(k)
...
100
101
102
(OR)
>>> ks=d1.keys()
>>> print(ks)
dict_keys([100, 101, 102])
>>> for k in ks:
... print(k)
...
100
101
102
Data Types in Python
8) item(): This function is used for obtaining list of tuples (key,value)
from non-empty dict.

Syntax: dictobj.item() or varname= dictobj.item()


Examples:
------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1)------------{100: 'Rossum', 101:
'Gosling', 102: 'Ritche'}
>>> d1.items()--------dict_items([(100, 'Rossum'),
(101, 'Gosling'), (102, 'Ritche')])

>>> for it in d1.items():


... print(it)
...
(100, 'Rossum')
(101, 'Gosling')
(102, 'Ritche')
>>> for k,v in d1.items():
... print(k,"--->",v)
...
100 ---> Rossum
101 ---> Gosling
102 ---> Ritche
(OR)

>>> kvs=d1.items()
>>> print(kvs)-----------dict_items([(100, 'Rossum'),
(101, 'Gosling'), (102, 'Ritche')])
>>> for k,v in kvs:
... print(k,"==>",v)
...
100 ==> Rossum
101 ==> Gosling
102 ==> Ritche
-----------------------------------------------------
Data Types in Python
9) update (): This function is used for updating dictobj1 values with
dictobj2 values.

Synatax: dictobj1.update(dictobj2)

Examples:
-----------------
>>> d1={10:"Python",20:"Java"}
>>> d2={30:"Django",40:"DS"}
>>> print(d1)------{10: 'Python', 20: 'Java'}
>>> print(d2)------{30: 'Django', 40: 'DS'}
>>> d1.update(d2)
>>> print(d1)-----------{10: 'Python', 20: 'Java',
30: 'Django', 40: 'DS'}
----------------------------------------------
>>> d1={10:"Python",20:"Java"}
>>> d2={10:"Django",20:"DS"}
>>> print(d1)-------------{10: 'Python', 20: 'Java'}
>>> print(d2)-------------{10: 'Django', 20: 'DS'}
>>> d1.update(d2)
>>> print(d1)------------{10: 'Django', 20: 'DS'}
-----------------------------------------------------
>>> d1={10:"Python",20:"Java"}
>>> d2={20:"Django",30:"DS"}
>>> print(d1)----------{10: 'Python', 20: 'Java'}
>>> print(d2)----------{20: 'Django', 30: 'DS'}
>>> d1.update(d2)
>>> print(d1)--{10: 'Python', 20: 'Django', 30: 'DS'}
=====================================================
Special Examples:
------------------------------
d1={1:["Python","DS","Django"],2:("Java","Servlets","
Spring"),3:{"Oracle","MySql","MongoDB"} }
>>> print(d1)------
{1: ['Python', 'DS', 'Django'], 2: ('Java',
'Servlets', 'Spring'), 3: {'MySql', 'Oracle',
'MongoDB'}}

>>> for k,v in d1.items():


... print(k,"==>",v)
...
1 ==> ['Python', 'DS', 'Django']
2 ==> ('Java', 'Servlets', 'Spring')
3 ==> {'MySql', 'Oracle', 'MongoDB'}
Data Types in Python

6)NoneType data type

“Nonetype” is one of 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. The value of


‘NoneType’ class can’t be created explicitly.

Examples:
------------------
>>> a=None
>>> print(a,type(a))------------None <class
'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType'
is not defined
-----------------------------------------------------
Approaches to develop python program
In real time, to develop any python program, we have two approaches.
They are:
a) Interactive Mode b) Batch Mode

a) Interactive Mode: In this mode of Development, Python Programmer


can issue a single statement and obtains single result.

This mode of development is most useful for testing one


Instruction at a time.

This mode of development is not recommended for big problem


solving because big problem solving statement are not possible to save
and more over re-using the statements of Interactive mode on other
parts of the projects is not possible.

Hence to solve big problems we must go for batch mode Programming.

Example of software’s Interactive Mode:

Python Command Prompt & Python IDLE

b) Batch Mode: In this Mode of Development, Python Programmer


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

Examples Software’s:

1) Python IDLE 2) Edit Plus 3) Pycharm 4) VS Code

5) Jupiter Note Book 6) Atom 7) Spider 8) Sub lime text…. etc.


Python program developing
------------------------------------------------------------------------------------------------
#program for adding of two numbers
a=10
b=20
c=a+b
print("Val of a=",a)
print("Val of b=",b)
print("Sum=",c)
------------------------------------------------------------------------------------------------
#Program for multiplying two values
a=int(input("Enter First Value:"))
b=int(input("Enter Second Value:"))
c=a*b
print("="*5)
print("Val of a=",a)
print("Val of b=",b)
print("Mul=",c)
print("="*10)
--------------------------------------------------------------------------------------------------------------
#This program will accept two values from KBD and
subtract them
a=int(input("Enter First Value:"))
b=int(input("Enter Second Value:"))
c=a-b
print("Value of=a",a)
print("Value of=b",b)
print("sum=",c)
------------------------------------------------------------------------------------------------

Display the result of Python program on console window

To display the result of the program on the console, we use a pre-


defined function called “ print() ”.
In other words print() is used to display the result of Python
program on the console. print() can be used in different ways, they are:

Syntax1: print(val1, val2,…val-n) or print(var1, var2,..var-n)

This Syntax display only Value on the console.


Python program developing
Examples:
---------------
>>> a=10
>>> print(a)------------------------10
>>> b=20
>>> print(b)-----------------------20
>>> sno=10
>>> sname="Rossum"
>>> print(sno,sname)-------------------10 Rossum
>>> print(10,"Rossum")---------------10 Rossum
-----------------------------------------------------

Syntax2: print(messages)

This Syntax displays only Messages on the console.


Examples:
----------------
>>> print("Hello Python World")----Hello Python World
>>> print('Hello Python World')----Hello Python World
>>> print('''Hello Python World''')------------Hello
Python World
>>> print("""Hello Python World""")--Hello Python World
-----------------------------------------------------

Syntax3: print(value cum message)


Or
Print(message cum value)

This Syntax displays all values along with messages on the console.

Examples:
------------
>>> 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
--------------------------------
Python program developing
>>> a=1
>>> b=2
>>> c=3
>>> d=a+b+c
>>> print("sum of ",a,",",b," and ",c,"=",d)---------
sum of 1 , 2 and 3 = 6
=====================================================

Syntax4: print (value cum message with format () )


Or
Print (message cum value with format () )

This Syntax displays all values along with messages with format() on console.

Examples:
-------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum=",c)-------------Sum= 30
>>> print("sum={}".format(c))-----sum=30
>>> print("{} is the sum".format(c))----30 is the sum
>>> print("sum of {} and {}={}".format(a,b,c))-------
sum of 10 and 20=30
>>> a=1
>>> b=2
>>> c=3
>>> d=a+b+c
>>> print("Sum of {},{} and {}={}".format(a,b,c,d))--
------Sum of 1,2 and 3=6
=====================================================

Syntax5: print(value cum message with format specifiers)


Or
print(message cum value with format specifiers)
This Syntax displays all values along with with messages with format
specifiers on the console.

%d------------------------int value
%f-------------------------float value
%s------------------------str value

If any data type does not contain any specifier than we must convert it into str().
Python program developing
Examples:
---------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum=%d" %c)-------------------Sum=30
>>> print("Sum=%f" %c)------------Sum=30.000000
>>> print("Sum=%0.2f" %c)----------Sum=30.00
>>> print("Sum=%0.3f" %c)----------Sum=30.000
>>> print("Sum of %d and %d=%d" %(a,b,c) )--------Sum
of 10 and 20=30
>>> sno=10
>>> sname="Rossum"
>>> print("My Number is %d and Name is %s"
%(sno,sname))---My Number is 10 and Name is Rossum
-----------------------------------------------------
>>> lst=[10,"KVR","OUCET",11.11,True]
>>> print(lst)-----[10, 'KVR', 'OUCET', 11.11, True]
>>> print("List Elements=",lst)------------List
Elements= [10, 'KVR', 'OUCET', 11.11, True]
>>> print("List Elements={}".format(lst))-----List
Elements=[10, 'KVR', 'OUCET', 11.11, True]
>>> print("List Elements=%s" %str(lst) )--List
Elements=[10, 'KVR', 'OUCET', 11.11, True]
=====================================================
MiSc Examples:
-------------------------------
>>> per=98
>>> print("My Percent %d %s " %(per,"%"))---My Percent 98 %
-----------------------
>>> per="98%"
>>> print("My percent=%s" %per)------My percent=98%
-----------------------------------------------------
>>> # =====
>>> s="="
>>> s=s+s+s+s+s
>>> print(s)------------- =====
>>>
>>> print("="*5)---------- =====
>>> print("="*20)---- ====================
>>> print("*"*5)----------- *****
>>> print("#"*15)--- ###############
---------------------------------------------------
>>> lst=[10,"Ram"]
>>> print(lst*3)-----[10, 'Ram', 10, 'Ram', 10, 'Ram']
----------------------------------------------------
Python program developing
>>> print("*"*50)----
**************************************************
=======================X=============================
ASSIGNMENT-1:
WAPP TO GET AREA OF RECTANGLE:
WAY-1==============================================

print("Enter Length:")
l=input()
print(l, type(l))
print("Enter Breadth:")
b=input()
print(b, type(b))
#conver l and b value into float
length=float(l)
breadth=float(b)
#calculate area of rect
ar=length*breadth
print("Area of Rect=",ar)

WAY-2=================================================

print("Enter Length and Breadth:")


l=input()
b=input()
#conver l and b value into float
length=float(l)
breadth=float(b)
#calculate area of rect
ar=length*breadth
print("Area of Rect=",ar)

WAY-3==================================================
print("Enter Length and Breadth:")
length=float(input())
breadth=float(input())
#calculate area of rect
ar=length*breadth
print("Area of Rect=",ar)

WAY-4==========================================================
print("Enter Length and Breadth:")
ar=float(input())*float(input())
print("Area of Rect=",ar)
Python program developing
WAY-5================================================
print("Enter Length and Breadth:")
print("Area of Rect=",float(input())*float(input()))
WAY-6================================================
print("Area of Rect=",float(input("Enter Length:"))*
float(input("Enter Breadth:")))
WAY-7================================================
#program for cal area of rect
length=12
breadth=23
ar=length*breadth
print("="*50)
print("Area of Rect")
print("="*50)
print("Length={}".format(length))
print("Breadth={}".format(breadth))
print("Area of Rect={}".format(ar))
print("="*50)

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

Reading the data dynamically from Key-Board

To read the data dynamically from key-board, we use two pre-defined


functions, they are:
1) input() 2 input(message)

1) input(): This function is used for reading any type of data from keyboard
in the form of str only.

Programmatically, to convert str type into other type, we use typecasting


techniques.

Syntax: varname=input()

Here varname is an object of type<class, ‘str’>


Input() is one of the pre-defined function.
Python program developing
Examples:
---------------------
#Program for sum of two numbers

print("Enter First Value:")


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

(OR)

#Program for sum of two numbers


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

(OR)

#Program for sum of two numbers


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

2) input(message): This function is used for reading any type values from
keyboard in the form of str type additionally with this function we can
give user-prompting message.
Programmatically, to convert str type into other type, we use type-
casting techniques.
Python program developing
Syntax: varname= input(message)

Here varname is an object of type <class, ‘str’>


Input() is one of the pre-defined function.
‘message’ represent user-prompting message.

Examples:
------------------------------
r=float(input("Enter Radious:"))
ac=3.14*r*r
pc=2*3.14*r
print("Area of Circle={}".format(ac))
print("Perimeter of Circle=%0.2f" %pc)
=====================================================
# Program for accepting Length and Breadth and find
area of rectangle
#DataRead1.py
-----------------------------------------------------
l=input("Enter Length:")
b=input("Enter breadth:")
print(l, type(l))
print(b, type(b))
#convert l and b into float
length=float(l)
breadth=float(b)
area=length*breadth
print("Area of Rect={}".format(area))
=================================================================
# Program for accepting Length and Breadth and find
area of rectangle
#DataRead2.py
-----------------------------------------------------
l=float(input("Enter Length:"))
b=float(input("Enter breadth:"))
area=l*b
print("Area of Rect=",area)
=================================================================
#program for cal simple intrest
#simpleint.py
-----------------------------------------------------
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
Python program developing
#calculate si
si=(p*t*r)/100
totamt=p+si
#display the result
print("="*50)
print("\tSimple Interest Calculations:")
print("="*50)
print("\tPrinciple Amount:{}".format(p))
print("\tTime:{}".format(t))
print("\tRate of Interest:{}".format(r))
print("\tSimple Interest:{}".format(si))
print("\tTotal Amount to pay:{}".format(totamt))
print("="*50)
===========================================================
Opertors and Expressions in Python
Opertors and Expressions in Python
==============================================================
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.3333333333333335
(float Quotient)
5. // Floor Division print(a//b)------ 3
(Integer Quotient)
6. % Modulo Division print(a%b)----1
7. ** Exponentiation print(a**b)---1000
==============================================================
#Special Case
----------------
>>> a=100
>>> b=30
>>> print(a/b)--------------3.3333333333333335
>>> print(a//b)-------------3
-----------------------------------------------------
>>> a=100.0
>>> b=30.0
>>> print(a/b)--------------3.3333333333333335
>>> print(a//b)----------- 3.0
=====================================================
#Program for demonstrating Arithmetic Operators
#aop.py
-----------------------------------------------------
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*50)
print("\tArithmetic Operators and Results")
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("\tFloor Div({},{})={}".format(a,b,a//b))
print("\tMod Div({},{})={}".format(a,b,a%b))
print("\tExpo({},{})={}".format(a,b,a**b))
print("-"*50)
================================================================
Opertors and Expressions in Python
#program for cal square root of a given number
#sqroot.py
-----------------------------------------------------
n=int(input("Enter a number:"))
res=n**0.5
print("squareroot({})={}".format(n,round(res,3)))
print("-------------OR-------------")
print("squareroot(%d)=%0.3f" %(n,res))
================================================================
#program for cal square root of a given number
#sqroot1.py
-----------------------------------------------------
n=int(input("Enter a number:"))
res=n**0.5
print("squareroot({})={}".format(n,res))
print("-------------OR-------------")
print("squareroot(%d)=%s" %(n,str(res)))
========================================================
Ass-2
---------
1) WAPP to calculate the area of Rectangle:
-------------------------------------------------------------------------------------------
print("\tArea of Rectangle is:",float(input("\tEnter the Length of
Rectangle:")) * float(input("\tEnter the Length of Rectangle:")))
========================================================
2) WAPP to calculate simple interest calculation and total Amount payable.
-------------------------------------------------------------------------------------------
p=float(input("Emter the Principle Amount:"))
r=float(input("Enter the Rate of Intrest:"))
t=float(input("Enter the Time Period:"))
print("Payable Amount:",((p*r*t)/100)+p)
========================================================
3) WAPP to calculate the circumference of circle.
-------------------------------------------------------------------------------------------
print("Circumference of Circle is:",(float(input("Enter the Radious of
Circle:")))*2*3.14)
========================================================
Opertors and Expressions in Python
4) WAPP to calculate the area of circle.
-------------------------------------------------------------------------------------------
r=float(input("Enter the Radious of Circle:"))
print("Area of Circle is:",(r**2)*3.14)
========================================================
5) WAPP to calculate area of triangle.
-------------------------------------------------------------------------------------------
print("The Area of Triangle is:",(float(input("Enter the base of
Triangle:"))*float(input("Enter the height of Triangle:")))*0.5)
========================================================
6) WAPP to calculate the sqrt of a user input number.
------------------------------------------------------------------------------------------
print("SQRT of Given Number is:",float(input("Enter the number to
find SQRT:"))**0.5)
========================================================
7) WAPP to calculate the cube root of user input number.
-------------------------------------------------------------------------------------------
print("SQRT of Given Number is:",float(input("Enter the number to
find SQRT:"))**(1/3))
========================================================
Opertors and Expressions in Python

=========================X===========================
Opertors and Expressions in Python
Opertors and Expressions in Python
Opertors and Expressions in Python
2) Assignment Operator: The purpose of assignment is that “To assign or
transfer Right Hand Side (RHS) Value / Expression Value to the Left Hand
Side (LHS) Variable”.
The symbol for Assignment Operator is single equal to ( = ).
In Python Programming, we use Assignment Operator in two ways:

1) Single Line Assignment 2) Multi Line Assignment

1) Single Line Assignment:


Syntax: LHS Varname = RHS Value or RHS Expression

With Single line assignment at a time we can assign one RHS Value or
Expression to the single LHS Variable Name.
Examples:
-----------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)------------10 20 30
-----------------------------------------------------

2) Multi Line Assignment:


Syntax: Var1, Var2,… Var-n = Val1, Val2,…Val-n (or)
Var1, Var2,…Var-n = Expr1,Expr2,…Expr-n

Here the values of Val1, Val2,…Val-n are assigned to Var1, Var2,…Var-n


Respectively.
Here the Values of Expr1, Expr2,…Expr-n are assigned to Var1, Var2,…Var-n
Respectively.

Examples:
-------------------
>>> a,b=10,20
>>> print(a,b)------------10 20
>>> c,d,e=a+b,a-b,a*b
>>> print(c,d,e)-------------30 -10 200
=========================X===========================
Opertors and Expressions in Python
#Program for swapping of any two values by using
Multi line assignment
=====================================================
#Swap.py
-----------------------------------------------------
a,b=input("Enter Value of a:"),input("Enter Value of b:")
print("="*40)
print("Original Value of a={}".format(a))
print("Original Value of b={}".format(b))
print("="*40)
#swapping Logic
a,b=b,a # Multi line assigment.
print("Swapped Value of a={}".format(a))
print("Swapped Value of b={}".format(b))
print("="*40)
====================================================
3) Relational Operators: The purpose of relational Operators is that “To
Compare Two or More Values”.
If two or more object or variables connected with Relational Operators
then it is called relational Expression.
Relational Expression is also called Test Condition and the result of
Relational Expression is either True or False.
In Python Programming, we have 6 relational operators and they are
given in the following table.
=====================================================
SLNO Symbol Meaning Example
=====================================================
1. > greater than print(100>20)-----True
print(100>200)----False
2. < Less than print(100<20)------False
print(100<200)-----True
3. == Equality print(10==10)------True
(Double Equal to) print(10==5)-------False
4. != Not Equal to print(10!=4)------True
print(10!=10)-----False
5. >= greater than print(10>=2)------True
or equal to print(10>=20)-----False
6. <= Less than print(10<=20)----True
or equal to print(10<=2)------False
=====================================================
Opertors and Expressions in Python
#relational Operators Functionality
-----------------------------------------------------
a=float(input("Enter Value of a:"))
b=float(input("Enter Value of b:"))
print("-"*50)
print("\tResult of Relational Operators")
print("-"*50)
print("\t {} > {} = {}".format(a,b,a>b))
print("\n\t {} < {} = {}".format(a,b,a<b))
print("\n\t {} == {} = {}".format(a,b,a==b))
print("\n\t {} != {} = {}".format(a,b,a!=b))
print("\n\t {} >= {} = {}".format(a,b,a>=b))
print("\n\t {} <= {} = {}".format(a,b,a<=b))
print("-"*50)
================================================================
#Python Ternary Operator
-----------------------------------------------------
a=int(input("Enter Value of a:")) # a=100
b=int(input("Enter Value of b:")) # b=30
result= a if a>b else b
print("Big({},{})={}".format(a,b,result))
================================================================
#Python Ternary Operator
-----------------------------------------------------
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:")) # b=10
result="BOTH VALUES ARE EQUAL" if (a==b) else a if
(a>b) else b
print("Big({},{})={}".format(a,b,result))
print("--------------------------------------")
result="BOTH VALUES ARE EQUAL" if (a==b) else a if
(a<b) else b
print("small({},{})={}".format(a,b,result))
==========================X=============================
Opertors and Expressions in Python
Ass-3
======
1) WAPP which accept any two values and interchange them or swap
them by using multiline assignment operator.
------------------------------------------------------------------------------------------
a=int(input("Enter first Value A="))
b=int(input("Enter secound Value B="))
a,b=b,a
print("swaped values of A=",a)
print("swaped values of B=",b)
========================================================
2) WAPP which will accept two values and find the biggest/smallest or
equal number among them.
------------------------------------------------------------------------------------------
a=int(input("Enter first Value:"))
b=int(input("Enter secound Value:"))
print("="*40)
res="Both values are Equal" if (a==b) else a if (a>b) else b
print("Biggest among them:",res)
print("="*40)
reslt="Both Values are Equal" if (a==b) else a if (a<b) else b
print("Smallest among them:",reslt)
print("="*40)
========================================================
.
Opertors and Expressions in Python

4) Logical Operators: The purpose of logical operators is that


“To connect two or more relational expression”.
If two or more Relational Expression connected with Logical Operators
then it is called Logical Expression or Compound Conditions is either True
or False.
In Python Programming, we have Three Types of Logical Operators.
they are given in the following table.
Opertors and Expressions in Python
=====================================================
SLNO SYMBOL MEANING
=====================================================
1 and Physical ANDing
2. or Physical ORing
3. not ---------------
=====================================================
1) and operator: The functionality of “and” operator is described in the
following Truth table.
=====================================================
Rel Expr1 RelExpr2 RelExpr1 and Rel Expr2
=====================================================
False False False

True False False

False True False

True True True


=====================================================
Examples:
----------
>>> print(100>20 and 20>4)---------------True
>>> print(100>200 and 20>4)-False-Short Circuit Evaluation
>>> print(-100>200 and 20>4 and 10>2)--False---Short
Circuit Evaluation
-----------------------------------------------------
Short Circuit Evaluation or Lazy Evaluation in the case of “and” operator:
In Case of “and” operator, if First Relation Expression result is False
then PVM will not evaluate rest of the Relational Expression and total
Logical Expression result will be considered as False. This process is called
Short circuit Evaluation (or) Lazy Evaluation of “and” operator.
Opertors and Expressions in Python
2) or operator: The Functionality of “or” operator is described in the
following Truth table.
=====================================================
RelExpr1 RelExpr2 RelExpr1 or Rel Expr2
=====================================================
False False False

True False True

False True True

True True True


=====================================================
Examples:
-----------------
>>> print(10>2 or 10>4)----------True-----Short
Circuit Evaluation
>>> print(10<2 or 20>3 or 5>50)-------True----Short
Circuit Evaluation
>>> print(10>2 or 20==3 or 5!=50)------True---Short
Circuit Evaluation
>>> print(10==2 or 20==3 or 5>=50)------False
---------------------------------------------------------------------------------------------------------
Short Circuit expression or Lazy Evaluation in the case of “or”.
In the case of “or” operator, if First Relational Expression result is
True then PVM will not evaluate rest of the Relational Expressions and
total Logical Expression result will be considered as True. This process is
called Short Circuit Evaluation or Lazy Evaluation of “or” operator.

3) not operator: The Functionality of of “not” operator is described in


the following Truth Table.
=====================================================
RelExpr1 not RelExpr1
=====================================================
False True

True False
=====================================================
Opertors and Expressions in Python
Examples:
----------------
>>> a=10
>>> b=20
>>> a==b-----------False
>>> not(a==b)-----------True
>>> print( not (10==2 or 20==3 or 5>=50))------True
---------------------------------------------------
>>> a=True
>>> not a-------------False
>>> not False-----------True
-----------------------------------------------------
Special Examples:
------------------
>>> 100>20 and 100>40---------------True
>>> 100>20 or 100>40-----------True
=====================================================
>>> 100 and -100---------- -100
>>> 100 and 0-------------- 0
>>> -100 and -225--------- -225
>>> 0 and 100-------------- 0
>>> 100 and -1234567------- -1234567
>>> 100 and 0------------- 0
>>> 0 and 345----------- 0
>>> 0 and 0--------------- 0
>>> 100 or 200-------------- 100
>>> -100 or -223----------- -100
>>> 0 or -223------------ -223
>>> 0 or 0----------------- 0
>>> not (0 or 0)------------- True
===========================X========================
Opertors and Expressions in Python

6) Membership Operators: The purpose of Membership operators is that


“To check whether the value present or not in Iterable Object”.

An Iterable object is one which contains multiple values or Sequence of


values.

Examples: Sequence, List set and dict.

In Python Programming, we have two types of membership operators.


They are:
1) in 2) not in

1) in Operator: The “in” operator returns True provided “value” present


in Iterable object. And also returns False if value not present in the
iterable object.
Syntax: value in Iterable_object

2) not in operator: The “not in” operator returns True provided “value”
not present in Iterable object. And also returns False if value present in
the iterable object.
Syntax: value not in Iterable_object
Opertors and Expressions in Python

Examples:
-----------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))
PYTHON <class 'str'>
>>> "P" in s
True
>>> "O" in s
True
>>> "o" in s
False
>>> s="PYTHON"
>>> "T" in s
True
>>> "T" not in s
False
>>> "t" not in s
True
>>> "K" not in s
True
>>> s="PYTHON"
>>> "PY" in s
True
>>> "PYTH" in s
True
>>> "PYTH" not in s
False
>>> "PYT" not in s
False
>>> "PYTHO" not in s
False
>>> "PYTHO" in s
True
>>> s="PYTHON"
>>> "PYO" not in s
True
>>> "PYN" not in s
True
>>> "PYN" in s
False
>>> "HON" in s
True
>>> "NOH" not in s
True
Opertors and Expressions in Python

>>> "NOH" not in s[::-1]


False
>>> "NOH" in s[::-1]
True
>>> "NOT" not in s
True
>>> "NOT" in s[::-1]
False
>>> s="PYTHON"
>>> "PTO" not in s[::2]
False
>>> "PTO" in s[::2]
True
=====================================================
>>> lst=[10,"PYTHON",34.56,2+3j]
>>> print(lst,type(lst))
[10, 'PYTHON', 34.56, (2+3j)] <class 'list'>
>>> 10 in lst
True
>>> 100 not in lst
True
>>> 2+3j not in lst
False
>>> "PYTHON" not in lst
False
>>> "PYThon" not in lst
True
>>> "PYT" in lst
False
>>> "PYT" in lst[1]
True
>>> "TYP" not in lst[1]
True
>>> "TYP" in lst[1][::-1]
True
>>> "PH" not in lst[1][::3]
False
>>> "PH" in lst[1][::3]
True
>>> lst[1] in lst
True
>>> lst[1][::-1] in lst[1]
False
>>> lst[-1].real in lst[3].real--------------
TypeError: argument of type 'float' is not iterable
Opertors and Expressions in Python
=====================================================

7) Identity Operators (Python Command Prompt): The purpose of Identity


Operators is that “To Compare Memory Address of two object”.
In Python programming, we have two types of Identity Operators.
They are:
1) is 2) is not
To get the memory address of anobject, we use id()

1) is : “is” operator returns True when obj1 and obj2 contains same
memory address. And also returns False when obj1 and obj2
contains different memory address.

Syntax: varname = obj1 is obj2

2) is not: “is not” operator returns True when obj1 and obj2 contains
different memory address. And also returns False when obj1
and obj2 contains same memory address.

Syntax: varname = obj1 is not obj2

Examples:
-----------------------
>>> a=None
>>> b=None
>>> print(a,type(a),id(a))---------None <class
'NoneType'> 140709278021624
>>> print(b,type(b),id(b))-------None <class
'NoneType'> 140709278021624
>>> a is b----------True
>>> a is not b---------False
----------------------------------------------------
>>> d1={10:"Apple",20:"Mango"}
>>> d2={10:"Apple",20:"Mango"}
>>> print(d1,type(d1),id(d1))---{10: 'Apple', 20:
'Mango'} <class 'dict'> 1872666607552
>>> print(d2,type(d2),id(d2))---{10: 'Apple', 20:
'Mango'} <class 'dict'> 1872666640512
>>> d1 is d2---------False
>>> d1 is not d2---True
-----------------------------------------------------
Opertors and Expressions in Python

>>> s1={10,20,30}
>>> s2={10,20,30}
>>> print(s1,type(s1),id(s1))---{10, 20, 30} <class
'set'> 1872670853824
>>> print(s2,type(s2),id(s2))---{10, 20, 30} <class
'set'> 1872670854272
>>> s1 is s2-------False
>>> s1 is not s2---True
-------------------
>>> fs1=frozenset({10,20})
>>> fs2=frozenset({10,20})
>>> print(fs1,type(fs1),id(fs1))
frozenset({10, 20}) <class 'frozenset'> 1872670855616
>>> print(fs2,type(fs2),id(fs2))
frozenset({10, 20}) <class 'frozenset'> 1872670854496
>>> fs1 is fs2
False
>>> fs1 is not fs2
True
-----------------------------------------------------
>>> l1=[10,"KVR"]
>>> l2=[10,"KVR"]
>>> print(l1,type(l1),id(l1))
[10, 'KVR'] <class 'list'> 1872666654784
>>> print(l2,type(l2),id(l2))
[10, 'KVR'] <class 'list'> 1872667375104
>>> l1 is l2
False
>>> l1 is not l2
True
-----------
>>> t1=(10,0)
>>> t2=(10,0)
>>> print(t1,type(t1),id(t1))
(10, 0) <class 'tuple'> 1872667061632
>>> print(t2,type(t2),id(t2))
(10, 0) <class 'tuple'> 1872667278336
>>> t1 is t2
False
>>> t1 is not t2
True
-----------------------------------------------------
Opertors and Expressions in Python

>>> r1=range(10,21)
>>> r2=range(10,21)
>>> print(r1,type(r1),id(r1))
range(10, 21) <class 'range'> 1872666787392
>>> print(r2,type(r2),id(r2))
range(10, 21) <class 'range'> 1872666787344
>>> r1 is r2
False
>>> r1 is not r2
True
-----------------------------------------------
>>> ba1=bytearray([10,20])
>>> ba2=bytearray([10,20])
>>> print(ba1,type(ba1),id(ba1))
bytearray(b'\n\x14') <class 'bytearray'>
1872670887088
>>> print(ba2,type(ba2),id(ba2))
bytearray(b'\n\x14') <class 'bytearray'>
1872670887536
>>> ba1 is ba2
False
>>> ba1 is not ba2
True
-----------------------
>>> b1=bytes((10,20))
>>> b2=bytes((10,20))
>>> print(b1,type(b1),id(b1))
b'\n\x14' <class 'bytes'> 1872666783360
>>> print(b2,type(b2),id(b2))
b'\n\x14' <class 'bytes'> 1872666781008
>>> b1 is b2
False
>>> b1 is not b2
True
-----------------------------------------------------
"Same String data with Same Case, Meaning and Order then they are
treated as String Constant and they contains Same Memory Address
otherwise we get Different Address".

>>> s1="INDIA"
>>> s2="INDIA"
>>> print(s1,type(s1),id(s1))
INDIA <class 'str'> 1872670887728
>>> print(s2,type(s2),id(s2))
Opertors and Expressions in Python
INDIA <class 'str'> 1872670887728

>>> s1 is s2
True
>>> s1 is not s2
False
>>> s1="INDIA"
>>> s2="INDIa"
>>> print(s1,type(s1),id(s1))
INDIA <class 'str'> 1872670887728
>>> print(s2,type(s2),id(s2))
INDIa <class 'str'> 1872670887600
>>> s1 is s2
False
>>> s1 is not s2
True
-----------------------------------------------------
>>> a=2+3j
>>> b=2+3j
>>> print(a,type(a), id(a))
(2+3j) <class 'complex'> 1872662488464
>>> print(b,type(b), id(b))
(2+3j) <class 'complex'> 1872662488304
>>> a is b
False
>>> a is not b
True
-----------------------------------------------------
>>> a=True
>>> b=True
>>> print(a,type(a), id(a))
True <class 'bool'> 140709277969256
>>> print(b,type(b), id(b))
True <class 'bool'> 140709277969256
>>> a is b
True
>>> a is not b
False
---------------------------------------
>>> a=True
>>> b=False
>>> print(a,type(a), id(a))
True <class 'bool'> 140709277969256
>>> print(b,type(b), id(b))
False <class 'bool'> 140709277969288
>>> a is b------------------ False
>>> a is not b------------- True
Opertors and Expressions in Python
-----------------------------------------------------

>>> a=1.2
>>> b=1.2
>>> print(a,type(a), id(a))
1.2 <class 'float'> 1872662481552
>>> print(b,type(b), id(b))
1.2 <class 'float'> 1872662485456
>>> a is b
False
>>> a is not b
True
---------------------------------------------------
Most Important:
---------------------------
1) 0 to 256 in multiple objects of int type contains same memory address.
2) More Than 256 in multiple objects of int type contains different
memory address
3) -1 to -5 in multiple objects of int type contains same memory address
4) Less than -5 in multiple objects of int type contains different
memory address
-----------------------------------------------------
>>> a=10
>>> b=10
>>> print(a,type(a), id(a))
10 <class 'int'> 1872661447184
>>> print(b,type(b), id(b))
10 <class 'int'> 1872661447184
>>> a is b
True
>>> a is not b
False
>>> a=256
>>> b=256
>>> print(a,type(a), id(a))
256 <class 'int'> 1872661455056
>>> print(b,type(b), id(b))
256 <class 'int'> 1872661455056
>>> a is b
True
>>> a is not b
False
>>> a=257
>>> b=257
>>> print(a,type(a), id(a))
Opertors and Expressions in Python
257 <class 'int'> 1872662488464

>>> print(b,type(b), id(b))


257 <class 'int'> 1872662488400
>>> a is b
False
>>> a is not b
True
>>> a=-1
>>> b=-1
>>> print(a,type(a), id(a))
-1 <class 'int'> 1872661446832
>>> print(b,type(b), id(b))
-1 <class 'int'> 1872661446832
>>> a is b
True
>>> a is not b
False
>>> a=-5
>>> b=-5
>>> print(a,type(a), id(a))
-5 <class 'int'> 1872661446704
>>> print(b,type(b), id(b))
-5 <class 'int'> 1872661446704
>>> a is b
True
>>> a is not b
False
>>> a=-6
>>> b=-6
>>> print(a,type(a), id(a))---- -6 <class 'int'>
1872662488400
>>> print(b,type(b), id(b))---- -6 <class 'int'>
1872662485104
>>> a is b
False
>>> a is not b
True
=============================X=======================
Special Cases
----------------------------------------------
>>> a,b=300,300
>>> print(a,type(a), id(a))
300 <class 'int'> 1872662488496
>>> print(b,type(b), id(b))
300 <class 'int'> 1872662488496
>>> a is b
Opertors and Expressions in Python
True

>>> a is not b
False
>>> a,b=30000,30000
>>> print(a,type(a), id(a))
30000 <class 'int'> 1872662484944
>>> print(b,type(b), id(b))
30000 <class 'int'> 1872662484944
>>> a is b
True
>>> a is not b
False
>>> a,b=3,4
>>> print(a,type(a), id(a))
3 <class 'int'> 1872661446960
>>> print(b,type(b), id(b))
4 <class 'int'> 1872661446992
>>> a is b
False
>>> a is b
False
------------------------------------------------
>>> a,b=-10,-10
>>> print(a,type(a), id(a))
-10 <class 'int'> 1872662484944
>>> print(b,type(b), id(b))
-10 <class 'int'> 1872662484944
>>> a is b
True
>>> a is not b
False
============================================
>>> a=1.5
>>> b=1.5
>>> print(a,type(a), id(a))
1.5 <class 'float'> 1872662481552
>>> print(b,type(b), id(b))
1.5 <class 'float'> 1872662485840
>>> print("%0.20f" %a)
1.50000000000000000000
>>> print("%0.60f" %a)
1.500000000000000000000000000000000000000000000000000
000000000
>>> a is b
False
>>> a is not b
Opertors and Expressions in Python
True

>>> a,b=1.2,1.2
>>> print(a,type(a), id(a))
1.2 <class 'float'> 1872662485232
>>> print(b,type(b), id(b))
1.2 <class 'float'> 1872662485232
>>> a is b
True
>>> a is not b
False
>>> a,b=2+3j,2+3j
>>> print(a,type(a), id(a))
(2+3j) <class 'complex'> 1872662488464
>>> print(b,type(b), id(b))
(2+3j) <class 'complex'> 1872662488464
>>> a is b
True
>>> a is not b
False
==========================X==========================
Flow Control Statements in Python (OR)
Control Structures in Python
The purpose of Flow Control Statements in Python is that “To perform
Certain Operation only once (Perform X-Operation in the case of True or
Y-Operation in the case of False) OR Perform Certain Operation
Repeatedly for finite number of time until Test Condition Become False.”

In Python Programming, The Flow Control Statements are classified into 3


types. They are:
1) Conditional OR Selection OR Branching Statements
2) Looping OR Iterative OR Repetitive Statements
3) Misc OR Transfer Flow statements

1) Conditional OR Selection OR Branching Statements:

The purpose of Conditional OR Selection OR Branching Statements is that


“To perform some operation when the condition is True or perform some
other operation when the condition is False Only Once”.
In Pyhton programming, Conditional or Selection or Branching Statement
are classified into 4 types. They are:
1) Simple if statement
2) if…else statement
3) if…elif…else statement
4) match case statement (Python 3.10 version)
===========================================================
Programs examples for simple if statement:
------------------------------------------------------------------------------------------------
1) movie ticket:
---------------------
tkt=input("Do u have a ticket(yes/no):")
if(tkt.capitalize()=="Yes"):
print("Enter into theater")
print("Watch the moviee")
print("Eat!")
print("\nGoto Home and Read Python Notes!")
Flow Control Statements in Python (OR)
Control Structures in Python
2) Program for deciding whether the number is +ve or -ve or zero:
------------------------------------------------------------------------------------------------
n=int(input("Enter a number:")) # n=10 or -10 or 0
if(n>0):
print("{} is Possitive:".format(n))
if(n<0):
print("{} is Negative:".format(n))
if(n==0):
print("{} is Zero".format(n))
print("Program execution Completed!")
========================================================
Pictorial Explanation of simple if Statements:

========================================================
#This Program find biggest of three nums.
-----------------------------------------
a=int(input("Enter Value of a:"))# a=100
b=int(input("Enter Value of b:")) # b=200
c=int(input("Enter Value of c:")) # c=300
#biggest logic
if(c<a>b):
print("big({},{},{})={}".format(a,b,c,a))
if(a<b>c):
print("big({},{},{})={}".format(a, b, c, b))
if(a<c>b ):
print("big({},{},{})={}".format(a, b, c, c))
if(a==b==c):
print("ALL VALUES ARE EQUAL")
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
#program for finding biggest among 3 numbers
---------------------------------------------
#bigex3.py
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:"))#b=10
c=int(input("Enter Value of c:"))# c=10
#biggest logic
if (a>b and a>c):
print("big({},{},{})={}".format(a,b,c,a))
else:
if(b>a and b>c):
print("big({},{},{})={}".format(a,b,c,b))
else:
if(a<c>b):

print("big({},{},{})={}".format(a,b,c,c))
else:
print("ALL VALUES ARE EQUAL:")
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
#Program for accepting a digit and print its name
--------------------------------------------------
d=int(input("Enter a Digit:"))#d --> 0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is ZERO".format(d))
else:
if(d==1):
print("{} is ONE".format(d))
else:
if(d==2):
print("{} is TWO".format(d))
else:
if(d==3):
print("{} is THREE".format(d))
else:
if(d==4):
print("{} is FOUR".format(d))
else:
if(d==6):
print("{} is SIX".format(d))
else:
if(d==5):
print("{} is FIVE".format(d))
else:
if(d==7):
print("{} is SEVEN".format(d))
else:
if(d==8):
print("{} is EIGHT".format(d))
else:
if(d==9):
print("{} is NINE".format(d))
else:
print("{} is
number:".format(d))

=====================================================
Flow Control Statements in Python (OR)
Control Structures in Python
#Program for accepting a digit and print its name
---------------------------------------------------
d=int(input("Enter a Digit:")) # d----> 0 1 2
3 4 5 6 7 8 9
if d in range(0,10):
print("{} is a digit:".format(d))
else:
print("{} is a number:".format(d))

========================================================
#Program for accepting a digit and print its name
--------------------------------------------------
d1={1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SI
X",7:"SEVEN",8:"EIGHT",9:"NINE",0:"ZERO"}
dig=int(input("Enter a Digit:"))
res=d1.get(dig)
if(res!=None):
print("{} is {}".format(dig,res))
else:
print("{} is a number:".format(dig))
=======================================
#program for deciding even or odd
----------------------------------
n=int(input("Enter a number:"))
if(n%2==0):
print("{} is EVEN".format(n))
if (n%2!=0):
print("{} is ODD".format(n))
=======================================
#Program for accepting a number and decides whether
it is even or odd
---------------------------------------------------
n=int(input("Enter a number:"))
if(n%2==0):
print("{} is EVEN:".format(n))
else:
print("{} is ODD" .format(n))
print("Program execution Completed:")
=======================================
Flow Control Statements in Python (OR)
Control Structures in Python
Pictorial Explanation of if else Statement:

Pictorial Explanation of if else Statement Flow chart:


Flow Control Statements in Python (OR)
Control Structures in Python
#Program for accepting a digit and print its name
--------------------------------------------------
d=int(input("Enter a Digit:")) # d----> 0 1 2
3 4 5 6 7 8 9
if(d==0):
print("{} is Zero:".format(d))
elif(d==1):
print("{} is One:".format(d))
elif(d==2):
print("{} is Two:".format(d))
elif(d==3):
print("{} is Three:".format(d))
elif(d==4):
print("{} is Four:".format(d))
elif(d==5):
print("{} is Five:".format(d))
elif(d==6):
print("{} is Six:".format(d))
elif(d==8):
print("{} is Eight:".format(d))
elif(d==7):
print("{} is Seven:".format(d))
elif(d==9):
print("{} is Nine:".format(d))
else:
print("{} is a Number:".format(d))
print("Program execution Completed:")
=======================================
Flow Control Statements in Python (OR)
Control Structures in Python
#Program for payslip
----------------------
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
basicsal=float(input("Enter Employee Basic Salary:"))
dsg=input("Enter Employee Designation:")
if(basicsal<=0):
print("Invalid Basic Salary:")
else:
if(basicsal>=10000):
da=basicsal*(10/100)
ta=basicsal*(12/100)
ma=basicsal*(2/100)
hra=basicsal*(6/100)
lic=basicsal*(2/100)
gpf=basicsal*(2/100)
elif(basicsal<10000):
da=basicsal*(15/100)
ta=basicsal*(14/100)
ma=basicsal*(3/100)
hra=basicsal*(7/100)
lic=basicsal*(2/100)
gpf=basicsal*(2/100)
netsal=(basicsal+da+ta+ma+hra)-(lic+gpf)
#display the pay slip
print("="*50)
print("\tEmployee Pay Slip")
print("="*50)
print("\tEmployee Number:{}".format(empno))
print("\tEmployee Name:{}".format(ename))
print("\tEmpoloyee Designation:{}".format(dsg))
print("\tEmployee Basic
Salary:{}".format(basicsal))
print("\tEmployee TA:{}".format(ta))
print("\tEmployee DA:{}".format(da))
print("\tEmployee MA:{}".format(ma))
print("\tEmployee HRA:{}".format(hra))
print("Deductions:")
print("\tEmployee LIC:{}".format(lic))
print("\tEmployee GPF:{}".format(gpf))
print("-"*50)
print("\tEmployee Net Salary:{}".format(netsal))
print("="*50)
Flow Control Statements in Python (OR)
Control Structures in Python
Match Case Statement (Python 3.10): It is one of new feature in Python 3.10

This feature is also known as Multi way decision making statement.

Syntax: match Choice Expression:


case label1:
block of statements-I
case label2:
block of statements-II
------------------------------------
-------------------------------------
case label-n:
block of statements-n
case _ : # default case block
default block of statements
----------------------------------------------------------
--------------------------------------------------------------------------
Other statement in Program
------------------------------------------
Explanation:
1) here 'match' and 'case' are the keywords.
2) here 'expression' can be any data type value except float.
3) here the value of choice expression is comparing with case label1 . If it
is True then execute Block of statements-I and also execute other
statements in Program. Choice expression is not matching with case
label1 then it compares with case label2 and if it matches then execute
Block of statements-II and also execute other statements in Program and
so on.
4) In general if the value of choice expression is matching with any case
label then PVM executes corresponding block of statements and also
executes Other statements in the program.
5) if value of choice expression is not matching with any case labels then
PVM executes block of statements written under default case block and
also executes Other statements in the program.
6) Writing default case label is optional.
7) If we write default case label then we must write it at last otherwise
we get SyntaxError.
Flow Control Statements in Python (OR)
Control Structures in Python
#Program for implementing all AOPs by using menus
-----------------------------------------------------
print("="*50)
print("\tArithmetic Operations")
print("="*50)
print("\t1.Addition")
print("\t2.Substraction")
print("\t3.Multiplication")
print("\t4.Division")
print("\t5.Modulo Div")
print("\t6.Exponentiation")
print("\t7.Exit:")
print("="*50)
ch=int(input("Enter Ur Choice:"))
match (ch):
case 1:
a,b=float(input("Enter First Value for
addition:")),float(input("Enter Second Value for addition:"))
print("sum({},{})={}".format(a,b,a+b))
case 2:
a,b=float(input("Enter First Value for
Subtract:")),float(input("Enter Second Value for Subtract:"))
print("sub({},{})={}".format(a,b,a-b))
case 3:
a,b=float(input("Enter First Value for
Mul:")),float(input("Enter Second Value for Mul:"))
print("mul({},{})={}".format(a,b,a*b))
case 4:
a,b=float(input("Enter First Value for
Div:")),float(input("Enter Second Value for Div:"))
print("Div({},{})={}".format(a,b,a/b))
print("FloorDiv({},{})={}".format(a,b,a//b))
case 5:
a,b=float(input("Enter First Value for Modulo
div:")),float(input("Enter Second Value for Modulo div:"))
print("Mod({},{})={}".format(a,b,a%b))
case 6:
a,b=float(input("Enter
Power:")),float(input("Enter Base:"))
print("pow({},{})={}".format(a,b,a**b))

case 7:
print("Thnaks for using this program")
exit()
case _: # default case block
print("Ur Selection of Operations is wrong")

print("Program execution completed"


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

2) Looping OR Iterative OR Repetitive Statements

The purpose of Looping or Iterative or Repetitive Statements is that “To


perform certain operations repeatedly for finite number of times until
Test Condition Becomes False”.
In Python Programming, we have 2 types of looping statements. They are:
1. while loop or while…else loop
2. for loop or for…else loop

To deal with any looping statements, we have to follow 3-steps. They are:
1. Initialization part
2. Conditional part
3. Updation part(Incrimination or Decrimination)

1. while loop or while…else loop:


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

========================================================
1. Program for generating 1 to n numbers where n is +ve.
--------------------------------------------------------
n=int(input("Enter Value of n:")) # n= 5
if(n<=0):
print("{} is invalid input".format(n))
else:
print("="*50)
print("Numbers within {}".format(n))
print("="*50)
i=1 # Initlization part
while(i<=n): # Cond Part
print("\t{}".format(i))
i=i+1 # Updation Part
print("="*50)
print("\nProgram execution completed:")

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

2. Program for generating n to 1 where n is +ve


---------------------------------------------------------------------------
n=int(input("Enter Value of n:"))
if(n<=0):
print("{} is invalid number:".format(n))
else:
print("="*50)
print("Numbers within {}".format(n))
print("="*50)
while(n>=1):
print("\t{}".format(n))
n=n-1
else:
print("*"*50)
print("\nProgram execution completed:")
========================================================
3. Program mul table for a given number n where n is +ve
------------------------------------------------------------------------------------------------
n=int(input("Enter value of n:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("="*50)
print("Mul table for {}".format(n))
print("="*50)
i=1
while(i<=10):
print("\t{} x {}={}".format(n,i,n*i))
i=i+1
else:
print("="*50)
========================================================
4. Program for accepting a line of text and display all chars
------------------------------------------------------------------------------------------------
line=input("Enter Line of Text:") # PYTHON
i=0
while(i<len(line)):
print("\t{}".format(line[i]))
i=i+1
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python

5. Program for accepting a line of text and display all chars


-----------------------------------------------------------------------------------------------
line=input("Enter Line of Text:") # PYTHON
line=line[::-1]
i=0
while(i<len(line)):
print("\t{}".format(line[i]))
i=i+1
===========================x============================
Flow Control Statements in Python (OR)
Control Structures in Python

2. for loop or for…else loop:

Syntax1:-
-----------
for varname in Iterable_object:
--------------------------------
Indentation block of stmts
--------------------------------
-------------------------------------
Other statements in Program
-------------------------------------

---------------
Syntax2:
---------------
for varname in Iterable_object:
--------------------------------
Indentation block of stmts
--------------------------------
else:
--------------------------------
else block of statements
--------------------------------
-------------------------------------
Other statements in Program
-------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python

Explanation:
Here 'for' and 'else' are keywords.
Here Iterable_object can be Sequence (bytes, bytearray, range, str),
List (list, tuple), set (set, frozenset) and dict.
The execution process of for loop is that "Each of Element of
Iterable_object selected, placed in varname and executes Indentation
block of statements". This Process will be repeated until all elements of
Iterable_object completed.
After execution of Indentation block of statements, PVM executes
else block of statements which are written under else block and later
PVM executes other statements in Program.
Writing else block is optional.

===========================================================
1. WAPP to generate 1 to n numbers where n is +ve integer.
------------------------------------------------------------------------------------------------
n=int(input("Enter Value of n:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
for i in range(1,n+1):
print("\t{}".format(i))
else:
print("i am from else block")
print("Program execution completed")
===========================================================
Flow Control Statements in Python (OR)
Control Structures in Python

2. Program to generate n to 1 numbers, where n is +ve integer.


------------------------------------------------------------------------------------------------
n=int(input("Enter Value of n:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
for val in range(n,0,-1):
print("\t{}".format(val))
===========================================================
3. Program to generate the characters to text line.
------------------------------------------------------------------------------------------------
text=input("Enter a line of text:")
print("Given Line={}".format(text))#Python
print("="*50)
for ch in text:
print("\t{}".format(ch))
==========================================================
4. Program for generating Factors for a given number.
-----------------------------------------------------------------------------------------------
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid".format(n))
else:
print("Factors for :{}".format(n))
print("="*50)
for i in range(1,n//2+1):
if(n%i==0):
print("\t{}".format(i))
else:
print("=" * 50)
===========================================================
Flow Control Statements in Python (OR)
Control Structures in Python

5. Program finding sum of first natural nums.


------------------------------------------------------------------------------------------------
n=int(input("Enter Value of n:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("=" * 50)
print("Sum of First {} Natural
Numbers".format(n))
print("=" * 50)
s=0
for i in range(1,n+1):
print("\t{}".format(i))
s=s+i
else:
print("="*50)
print("sum={}".format(s))
print("=" * 50)
===========================================================
6. Program finding sum of natural numbers, squares and cubes first natural nums.
------------------------------------------------------------------------------------------------------------
n=int(input("Enter Value of n:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("="*50)
print("\tNatNum\tSquares\tCubes")
print("="*50)
s,ss,cs=0,0,0
for i in range(1,n+1):
print("\t{}\t{}\t{}".format(i,i**2,i**3))
s=s+i
ss=ss+i**2
cs=cs+i**3
else:
print("="*50)
print("\t{}\t{}\t{}".format(s,ss,cs))
print("="*50)
===========================================================
Flow Control Statements in Python (OR)
Control Structures in Python

7. Program accepting a number and find sum of its digits.


-----------------------------------------------------------------------------------------------
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid Input:".format(n))
else:
s=0
while(n>0):
d=n%10
s=s+d
n=n//10
else:
print("sum of Digits of Given
Number={}".format(s))
========================================================
8. Program for cal factorial of a given number.
-----------------------------------------------------------------------------------------------
Logic:
Flow Control Statements in Python (OR)
Control Structures in Python

n=int(input("Enter a number:"))
if(n<0):
print(" factorial not defined for negative values")
else:
k=1
for i in range(1,n+1):
k=k*i
else:
print("Factorial({})={}".format(n,k))
print("===============OR=====================")
k=1
t=n
while(n>0):
k=k*n
n=n-1
else:
print("Factorial({})={}".format(t,k))
========================================================
9. Program to deciding whether the given number or name is palindrome
or no
-----------------------------------------------------------------------
val=input("Enter a Number or Word:")
if(val==val[::-1]):
print("Given Number or word is Palindrome")
else:
print("Given Number or word is not Palindrome")
========================================================
10. Program for converting Ordinary Number into Roman Eqv.
------------------------------------------------------------------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python

n=int(input("Enter a number:"))
if(n<=0):
print("No Roman Number:")
else:
while(n>=1000):
print("M",end="")
n=n-1000
if(n>=900):
print("CM",end="")
n=n-900
if(n>=500):
print("D",end="")
n=n-500
if(n>=400):
print("CD",end="")
n=n-400
while(n>=100):
print("C",end="")
n=n-100
if(n>=90):
print("XC",end="")
n=n-90
if(n>=50):
print("L",end="")
n=n-50
if(n>=40):
print("XL",end="")
n=n-40
while(n>=10):
print("X",end="")
Flow Control Statements in Python (OR)
Control Structures in Python
n=n-10
if(n>=9):
print("IX",end="")
n=n-9
if(n>=5):
print("V",end="")
n=n-5
if(n>=4):
print("IV",end="")
n=n-4
while(n>=1):
print("I",end="")
n=n-
=========================x=======================

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".
When break statement takes place inside for loop or while loop
then PVM will not corresponding else block (because loop is not
becoming False) but it executes other statements in the program
Syntax1:
---------
for varname in Iterable_object:
------------------------------
if (test cond):
break
------------------------------
------------------------------

Syntax2:
---------
while(Test Cond-1):
------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
if (test cond-2):
break
------------------------------
------------------------------
===========================x===========================

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 inside of loop then 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
-------------------------------------
------------------------------------

Syntax:-
----------
Flow Control Statements in Python (OR)
Control Structures in Python
while (Test Cond):
-------------------------------
if ( Test Cond):
continue
statement-1 # written after
continue stateemnt
statement-2
statement-n
-------------------------------------
-------------------------------------

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

1. This program demonstrates the functionality of break statement.


------------------------------------------------------------------------------------------------
s="PYTHON"
for ch in s:
if(ch=="H"):
break
else:
print("\t{}".format(ch))
else:
print("i am from else block")
print("Other statements in program")
========================================================
2. This program demonstrates the functionality of break statement.
------------------------------------------------------------------------------------------------
s="PYTHON"
i=0
while(i<len(s)):
if(s[i]=="H"):
break
else:
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else block of while loop")
print("other statements in program")
========================================================
3. Program for deciding whether the number is prime or not.
-----------------------------------------------------------------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
n=int(input("Enter a number:")) #n=2
if(n<=1):
print("{} is invalid input ".format(n))
else:
result=True # For prime
for i in range(2,n):
if(n%i==0):
result=False # for not prime
break
if(result==True):
print("{} is a prime".format(n))
else:
print("{} is not a prime".format(n))
===================================================

4. Program for deciding whether the number is prime or not.


------------------------------------------------------------------------------------------------
n=int(input("Enter a number:")) #n=4
if(n<=1):
print("{} is invalid input ".format(n))
else:
result=True # For prime
for i in range(2,n):
if(n%i==0):
result=False # for not prime
break
if(result):
print("{} is a prime".format(n))
else:
print("{} is not a prime".format(n))

========================================================
5. Program for deciding whether the number is prime or not.
------------------------------------------------------------------------------------------------
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="notprime" # for not prime
break
if(result=="prime"):
Flow Control Statements in Python (OR)
Control Structures in Python
print("{} is a prime".format(n))
else:
print("{} is not a prime".format(n))
=====================================================

6. Program for demonstrating continue statement


#continueex1.py-----will display PYTON
-------------------------------------------------------------------------------------------
s="PYTHON"
for ch in s:
if(ch=='H'):
continue
else:
print("\t{}".format(ch))
else:
print("i am from else block of for loop")
print("Other statement in program")
=====================================================
7. Program for demonstrating continue statement
#continueex2.py
-------------------------------------------------------------------------------------------
lst=["Python","Java","Venky","Django","Data
Sci","Flask","Pyramid"]
for name in lst:
if(name=="Venky") or (name=="Flask"):
continue
else:
print("\t{}".format(name))
else:
print("i am from else block of for loop")
print("Other statements in program ")
====================================================
8. Program for demonstrating continue statement
Flow Control Statements in Python (OR)
Control Structures in Python
#continueex3.py
-----------------------------------------------------------------------------------------
lst=["Python","Java","Venky","Django","Data
Sci","Flask","Pyramid"]
for name in lst:
if name not in ["Venky","Flask","Python"]:
continue
else:
print("\t{}".format(name))
else:
print("i am from else block of for loop")
print("Other statements in program")
=========================x===========================

Nested or Inner Loops

The Process of defining one loop inside of another loop is called


Nested / Inner loop.
For every value outer loop , inner loop repeated for finite number
of times.
Inner loop can be in 4 ways. They are
Syntax1: (for loop in for loop)
-----------------
for varnam1 in Iterbale_object1: # Outer for loop
------------------------------------
------------------------------------
for varname2 in Iterbale_object2: #Inner for loop
--------------------------------------
--------------------------------------
else:
---------------------------------------
else:
------------------------------------------

------------------------------------------
Other statements in Program
-----------------------------------------
================================================================
Syntax2: (while loop in while loop)
-----------------
-------------------------------------
while(Test Cond1): # Outer while loop
Flow Control Statements in Python (OR)
Control Structures in Python
--------------------------------------
--------------------------------------
while(Tesd Cond2): #Inner while loop
---------------------------------
---------------------------------
else:
--------------------------------
else:
--------------------------------------

-------------------------------------------
Other statements in Program
-------------------------------------------
================================================================

Syntax3: (while loop in for loop)


--------
for varnam1 in Iterbale_object1: # Outer for loop
------------------------------------------
------------------------------------------
while(Test Cond) : # Inner while loop
-----------------------------------------
----------------------------------------
else:
-------------------------------------------
else:
-------------------------------------------------
--------------------------------------------------
Other statements in Program
--------------------------------------------------------
================================================================
Syntax4: (for loop in while loop)
-----------------
while(Test Cond): # Outer while loop
------------------------------------------
------------------------------------------
for varname in Iterbale_object: # Inner for loop
------------------------------------------
------------------------------------------
else:
-------------------------------------------
else:
-------------------------------------------------
--------------------------------------------------
Other statements in Program
--------------------------------------------------------

=============================X==================================
Flow Control Statements in Python (OR)
Control Structures in Python
1. Program for demonstrating inner or nested loop --- for loop in for
loop
#innerloopex1.py
-------------------------------------------------------------------------------------------
for i in range(1,6):
print("Value of i--outer for loop:{}".format(i))
print("-"*40)
for j in range(1,4):
print("\tValue of j--inner for loop:{}".format(j))
else:
print("Out of inner for loop")
print("-"*40)
else:
print("Out of outer for loop")
print("-"*40)
print("\n Program Execution Completed!")

"""
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex1.py
Value of i--outer for loop:1
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:2
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:3
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:4
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:5
----------------------------------------
Value of j--inner for loop:1
Flow Control Statements in Python (OR)
Control Structures in Python
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Out of outer for loop
----------------------------------------

E:\KVR-PYTHON-6PM\LOOPS>py innerloopex1.py
Value of i--outer for loop:1
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:2
----------------------------------------

Value of j--inner for loop:1


Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:3
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:4
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:5
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Out of outer for loop
----------------------------------------

Program Execution Completed!


"""

========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
2. Program for demonstrating inner or nested loop --- while loop in
while loop
#innerloopex2.py
--------------------------------------------------------------------------------------------
i=1 # Initlization for outer while loop
while(i<6):
print("Value of i--outer while loop:{}".format(i))
print("-"*40)
j=1 # Initlization for inner while loop
while(j<=3):
print("\tValue of j--inner while
loop:{}".format(j))
j=j+1 # Updation for inner while loop
else:
i=i+1 # Updation for outer while loop
print("Out of inner while loop")

print("-"*40)
else:
print("Out of outer while loop")
print("-"*40)
print("\n Program Execution Completed!")

"""
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex2.py
Value of i--outer while loop:1
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Value of i--outer while loop:2
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Value of i--outer while loop:3
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Value of i--outer while loop:4
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Flow Control Statements in Python (OR)
Control Structures in Python
Out of inner while loop
----------------------------------------
Value of i--outer while loop:5
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Out of outerwhile loop
----------------------------------------

Program Execution Completed!


"""

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

3. Program for demonstrating inner or nested loop --- while loop in for
loop
#innerloopex3.py
------------------------------------------------------------------------------------------
for i in range(5,0,-1):
print("Value of i--outer for loop:{}".format(i))
print("-"*40)
j=3
while(j>=1):
print("\tValue of j--inner while
loop:{}".format(j))
j=j-1
else:
print("Out of inner while loop")
print("-"*40)
else:
print("Out of outer for loop")
print("-"*40)
print("\n Program Execution Completed!")

"""
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex3.py
Value of i--outer for loop:5
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:4
----------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:3
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:2
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:1
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Out of outer for loop
----------------------------------------
Program Execution Completed!

"""
==============================================================
4. Program for demonstrating inner or nested loop --- for loop in while
loop
#innerloopex4.py
------------------------------------------------------------------------------------------
i=1 # Initlization for outer while loop
while(i<6):
print("Value of i--outer while
loop:{}".format(i))
print("-"*40)
for j in range(3,0,-1):
print("\tValue of j--inner for
loop:{}".format(j))
else:
i=i+1 # Updation for outer while loop
print("Out of inner for loop")
print("-"*40)
Flow Control Statements in Python (OR)
Control Structures in Python
else:
print("Out of outer while loop")
print("-"*40)
print("\n Program Execution Completed!")
=====================================================

5. Program for accepting list of value and generate mul tables for all
+ve numbers
#multables.py
-------------------------------------------------------------------------------------------
n=int(input("Enter How many mul tables u want to
generate:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
# accept 'n' number of values in list
lst=[] # create empty list
for i in range(1,n+1):
val=int(input("Enter {}Value:".format(i)))
lst.append(val)
else:
print("-"*50)
print("Given List of Elements:{}".format(lst))
# [10, 6, -5, 19, 2]
print("-"*50)
#Generate Mul tables for list of values.
for n in lst: # Outer for loop
if(n<=0):
print("{} not value mul
table:".format(n))
else:
print("-"*50)
Flow Control Statements in Python (OR)
Control Structures in Python
print("Mul Table for {}".format(n))
print("-"*50)
for i in range(1,11): #Inner for loop
print("\t{} x {} =
{}".format(n,i,n*i))
else:
print("-"*50)
=====================================================

6. Program for generating mul table for 1 to 20


#multables1-20.py
-------------------------------------------------------------------------------------------
for n in range(1,21):
print("-"*50)
print("Mul Table for {}".format(n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
else:
print("-"*50)
=====================================================
7. forforforloopex1.py
------------------------------------------------------------------------------------------
for i in range(1,3):
print("i={}".format(i))
for j in range(10,12):
print("\tj={}".format(j))
for k in range(50,52):
print("\t\tk={}".format(k))

"""
E:\KVR-PYTHON-6PM\LOOPS>py forforforloopex1.py
i=1
j=10
k=50
Flow Control Statements in Python (OR)
Control Structures in Python
k=51
j=11
k=50
k=51
i=2
j=10
k=50
k=51
j=11
k=50
k=51
"""

8. Program which for will accept list of numeric values. Separate


positive values and negative values.
#PosNegValue.py
--------------------------------------------------------------------------------------------
n=int(input("Enter How many values u want enter:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
# accept 'n' number of values in list
lst=list() # create empty list
for i in range(1,n+1):
val=int(input("Enter {}
Value:".format(i)))
lst.append(val)
else:
print("-"*50)
print("Given List of
Elements:{}".format(lst)) # [10, -23, 20, -45, -2, 0]
print("-"*50)
#get Possitive Values
pl=[]
for val in lst:
if(val<=0):
continue
else:
pl.append(val)
Flow Control Statements in Python (OR)
Control Structures in Python
#get Negative Values
nl=[]
for val in lst:
if(val>=0):
continue
else:
nl.append(val)
else:
print("Possitive List={}".format(pl))
print("Negative List={}".format(nl))
=====================================================

9. Program for accepting age of citizen and decide eligible to vote or not.
#VoterEx1.py
--------------------------------------------------------------------------------------------
age=int(input("Enter ur age:"))
if(age>=18) and (age<=100):
print("{} year old citizen eligible to
vote".format(age))
else:
print("citizen not eligible to vote")
========================================================
10. Program for accepting age of citizen and decide eligible to vote or not
#VoterEx2.py
--------------------------------------------------------------------------------------------
while(True):
age=int(input("Enter ur age:"))
if(age>=18) and (age<=100):
break
print("Ur age is invalid")
print("{} year old citizen eligible to
vote".format(age))
========================================================

Problem statements:
----------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
1) aceept sno,name, marks in three subjects (cm-100,cpp-100,pym-100)
2) cal total marks (totmarks=cm+cppm+pym)
3) cal percentage of marks (percent=(totmarks/300)*100 )
4) Give Grade=Fail provided the student secures less than 40 atleast
in one subject
5) Give Grade="Distinction " provided totmarks>=250 and totmarks<=300
6) Give Grade="First " provided totmarks>=200 and totmarks<=249
7) Give Grade="Second" provided totmarks>=150 and totmarks<=199
8) Give Grade="Third" provided totmarks>=120 and totmarks<=149\
9) Display Student Marks Memo.
--------------------------------------------------------------

------------------------------------------------------------
"""
#Program display student Marks report
#studentmarksreport.py
#accept student number
while(True): # validation student number
sno=int(input("Enter the Student Number(500--600):"))
if(sno>=500) and (sno<=600):
break
print("Invalid Student Number")
#accept student name
while(True):
sname=input("Enter Student Name:")
if(sname.isalpha() ):
break
print("Invalid Student Name")
#validation of C Marks
while(True):
cm=int(input("Enter Marks in C(0-100):"))
if(cm>=0) and (cm<=100):
break
print("Invalid Marks in C")

#validation of CPP Marks


while(True):
cppm=int(input("Enter Marks in CPP(0-100):"))
if(cppm>=0) and (cppm<=100):
break
print("Invalid Marks in CPP")

#validation of pym Marks


Flow Control Statements in Python (OR)
Control Structures in Python
while(True):
pym=int(input("Enter Marks in Python(0-100):"))
if(pym>=0) and (pym<=100):
break
print("Invalid Marks in PYTHON")

# cal total marks (totmarks=cm+cppm+pym)


totmarks=cm+cppm+pym
#cal percentage of marks (percent=(totmarks/300)*100 )
percent=(totmarks/300)*100
#decide the grade
if(cm<40) or (cppm<40) or (pym<40):
grade="FAIL"
else:
if(totmarks>=250) and (totmarks<=300):
grade="DISTINCTION"
elif(totmarks>=200) and (totmarks<=249):
grade="FIRST"
elif(totmarks>=150) and (totmarks<=199):
grade="SECOND"
elif(totmarks>=120) and (totmarks<=149):
grade="THIRD"

#display student marks report


print("="*50)
print("\tS t u d e n t M a r k s R e p o r t")
print("="*50)
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Marks in C:{}".format(cm))
print("\tStudent Marks in CPP:{}".format(cppm))
print("\tStudent Marks in Python:{}".format(pym))
print("-"*50)
print("\tStudent Total Marks:{}".format(totmarks))
print("\tStudent Percentage of Marks:{}".format(percent))
print("\tStudent Grade:{}".format(grade))
print("="*50)
===========================================
Functions in Python
Index:
1. Purpose of Functions.
2. Definition of Function.
3. Types of Functions.
a) Pre-defined Functions
b) Programmer/User/Custom Defined Functions
4. Parts of Functions.
5. Phases in Functions.
6. Syntax for Approaches to defining Programmer-defined Functions.
7. Programming Examples.
------------------------------------------------------------------------------------------------
8. Arguments and Parameters.
9. Types of Arguments.
a) Positional Arguments.
b) Default arguments.
c) Keyword Arguments.
d) Variable length Arguments.
e) Keyword Variable length Arguments.
10. Programming Examples.
11. Global Variables and Local Variables.
12. global keyword and global().
13. Programming Examples.
------------------------------------------------------------------------------------------------
14. Anonymous Functions or Lambda Functions.
15. Syntax for defining Anonymous Functions or Lambda Functions.
16. Programming Examples.
------------------------------------------------------------------------------------------------
17. Special Functions in Python:
a) filter() with Normal and Anonymous Functions
b) map() with Normal and Anonymous Functions
c) reduce with Normal and Anonymous Functions.
Programming Examples.
Functions in Python

Types of Languages in the context of Functions

In the context of Functions, we have two types of programming


Languages. They are:

1) Un-Structured Programming Languages.


2) Structured Programming Languages.

1) Un-Structured Programming Languages:

In Un-Structured Programming Languages, There is no concept of Functions.


So that Un-Structured Programming Languages gives the Following
Limitations:
1. Application Development time is more.
2. Application Memory space is more.
3. Application Execution is more.
4. Application Performance is degrading.
5. Redundancy (Duplication or Replication) of the code is more.

Examples: GW-BASIC

2) Structured Programming Languages.

In Structured Programming Languages, There is a concept of Functions.


So that Structured Programming Languages contains the Following
advantages:
1. Application Development time is less.
2. Application Memory space is less.
3. Application Execution is less.
4. Application Performance is enhancing.
5. Redundancy (Duplication or Replication) of the code is minimised.

Examples: c, c++, JAVA, .NET, PYTHON….etc.


Functions in Python

Functions in Python

Purpose of Functions: The purpose of Functions concept is that “To perform


certain operation and provides code re-usability”.

Definition of Function: A part of main program or sub-program of main


program is called function.

Parts of Function: At the time of dealing with Function in python, we


must ensure that there must exists 2 parts. They are:

1) Function definition
2) Function Call

 Particular Function definition Exists only Once.


 Function Call may exists one or more times.
 For Every Function Call there must exist a separate Function
Definition otherwise we get NameError.
 Function Definition will execute when we call through Function Call
but not execution the function by itself.

Phases of Function: when we define a function, we must ensure that


there must be exists 3 phases. They are:

1. Taking INPUT
2. Doing the PROCESS.
3. Giving OUTPUT/RESULT.
Functions in Python
Syntax for defining functions and Explanation:

Number of approaches to define Functions Programs:

In Python Programming, we have 4 approaches to define a function. They are:

Approach-1:
 Input: Function Call
 Process: Function Body
 Output: Function Call
Functions in Python

Example:
#Approach1.py

def addop(a,b): # Here 'a' and 'b' are called Formal params
c=a+b # here 'c' is called Local Variable
return c

#main program
#Taking Input
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
res=addop(x,y) # Function Call--
print("Sum=",res) # disp the result

Apporach-2:

 Input: Function Body


 Process: Function Body
 Output: Function Body

Example:
#Approach2.py
def addop():
#taking Input
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#Process
c=a+b
#disp the Result / Output
print("sum({},{})={}".format(a,b,c))

#main program
addop() # Function Call

Approach-3:
 Input: Function Call
 Process: Function Body
 Output: Function Body
Functions in Python

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

#main program
k=float(input("Enter First Value:"))
v=float(input("Enter Second Value:"))
addop(k,v)#Function call

Approach-4:
 Input: Function Body
 Process: Function Body
 Output: Function Call

Example:
#Approach4.py
def addop():
#taking Input
k=float(input("Enter First Value:"))
v=float(input("Enter Second Value:"))
#process
r=k+v
#return result
return k,v,r # In Python return statement can return one
or more values

#main program
a,b,result=addop() # Function Call with multi line assigment
print("sum({},{})={}".format(a,b,result))
print("-----------------OR----------------------")
result=addop() # Function Call.
# Here result variable is holding 3 values returned by
Function Defintion and variable result is of type tuple
#print(result, type(result)) ---- (3.4, 12.5, 15.9) <class
'tuple'>
print("sum({},{})={}".format(result[0],result[1],result[2]))
Functions in Python
===================================================================
Prog 1(a): WAPP to accept the values from user and arrange it in ascending and
descending order using function.
--------------------------------------------------------------------------------------------------------------

def readvalues():
n=int(input("Enter how many number u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def sortvalues():
result=readvalues()
if(result==None):
print("No Elements are present and nothing to sort")
else:
print("Original Elements")
for val in result:
print("\t{}".format(val))
#sort the data--ASC Irder
result.sort()
print("Sorted Elements--Asending Order")
for val in result:
print("\t{}".format(val))
#sort the data--ASC Irder
result.sort(reverse=True)
print("Sorted Elements--Decending Order")
for val in result:
print("\t{}".format(val))

#main program
sortvalues()

===================================================================
Functions in Python
Prog 1(b): WAPP to accept the values from user and arrange it in ascending and
descending order using function.
------------------------------------------------------------------------------------------------------------
def readvalues():
n=int(input("Enter how many number u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def dispvalues(lst):
print("="*50)
for val in lst:
print("\t{}".format(val))
print("="*50)

def sortvalues():
result=readvalues() # Function Chaining
if(result==None):
print("No Elements are present and nothing to sort")
else:
print("Original Elements")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
result.sort()
print("Sorted Elements--Asending Order")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
result.sort(reverse=True)
print("Sorted Elements--Decending Order")
dispvalues(result) # Function Chaining
#main program
sortvalues()

===================================================================
Functions in Python
Prog 2: Program for accepting list of values and find sum and avg.
-----------------------------------------------------------------------------------------------
def readvalues():
n=int(input("Enter how many number u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def computersumavg(result):
if(result==None):
print("No Values present and we can't cal sum and avg")
else:
s=0
for val in result:
print("\t{}".format(val))
s=s+val
else:
print("Sum={}".format(s))
print("Avg={}".format(s/len(result)))
#main program
result=readvalues()
computersumavg(result)

===================================================================
Functions in Python
Prog 3: Program for finding max and min from list of values by using Functions.
#maxminvalue.py
------------------------------------------------------------------------------------------------
def readvalues():
print("\nEnter List of values separated by space:")
lst=[ int (val) for val in input().split() ]
return lst

def findmaxvalue():
lst=readvalues()
maxv=lst[0] # maxv=10
for i in range(1,len(lst)):
if(lst[i]>maxv):
maxv=lst[i]
return maxv

def findminvalue():
lst=readvalues()
minv=lst[0] # minv=10
for i in range(1,len(lst)):
if(lst[i]<minv):
minv=lst[i]
return minv

#main program
maxv=findmaxvalue()
print("Max Element={}".format(maxv))
minv=findminvalue()
print("Min Element={}".format(minv))

===================================================================
Functions in Python
Prog 4: Program for finding max and min from list of values by using Functions.
#maxminvaluewithlib.py
-----------------------------------------------------------------------------------------------
def readvalues():
print("\nEnter List of values separated by space:")
lst=[ int (val) for val in input().split() ]
return lst

def findmaxvalue():
lst=readvalues()
return max(lst)

def findminvalue():
lst=readvalues()
return min(lst)

#main program
maxv=findmaxvalue()
print("Max Element={}".format(maxv))

minv=findminvalue()
print("Min Element={}".format(minv))

===================================================================
Functions in Python

List comprehension

The purpose of List comprehension is that “To read the values dynamically
from key board separated by a delimiter (space, comma, colon…etc)”.
List comprehension is the most effective way for reading the data
for list instead traditional reading the data.

Syntax: listobj = [ expression for varname in Iterable_object ]

Here expression represents either type casting or mathematical expression.

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

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

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

===================================================================
Functions in Python
Prog 1: This program accept list of values dynamically by using list
comprehension and sort them.
#listsortcompre.py
------------------------------------------------------------------------------------------------
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)

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

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

===================================================================
Functions in Python
Prog 2: This program accept list of names dynamically by using list
comprehension and sort them.
#listsortcompre1.py
----------------------------------------------------------------------------------------------
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)

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

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

===================================================================
Prog 3: Program for finding max and min from list of values by using Functions.
#indexvalue.py
-----------------------------------------------------------------------------------------------
def readvalues():
print("\nEnter List of values separated by space:")
lst=[ int (val) for val in input().split() ]
return lst
def findindex():
lst=readvalues()
indval=-1
sk=int(input("Enter which value u want to search:"))
for i in range(0,len(lst)):
if(sk==lst[i]):
indval=i
break
if(indval>-1):
print("{} Found at {} Index:".format(sk,indval))
else:
print("{} does not exist in list".format(sk))
#main program
findindex()
================================================================
Functions in Python

Prog 4: Program for squaring the values.


------------------------------------------------------------------------------------------------
lst=[10,12,45,6,23]
sqlist=[]
for val in lst:
res=val**2
sqlist.append(res)
print("Original list={}".format(lst))
print("Square list={}".format(sqlist))
print("==========OR================")
sqlist1=[val**2 for val in lst ]
print("Original list={}".format(lst))
print("Square list={}".format(sqlist))

===================================================================
#listcomprehenex2.py
-----------------------------------------------------------------------------------------------
print("Enter List of values separated by space:")
lst=[ int (val) for val in input().split() ] # 10 20 34 -45 -
56 23
print("\nGiven List of elements:{}".format(lst))
print("================OR=====================")
print("Enter List of values separated by comma:")
lst=[ int (val) for val in input().split(",") ]
print("\nGiven List of elements:{}".format(lst))

===============================x====================================
Functions in Python

Arguments and Parameters

Parameters are of two Types. They are:

1. Formal Parameters
2. Local Parameters

 Formal Parameters are always used in Function Heading and they are
used for storing Input Values coming from Function call.
 Local Parameters are always used inside of Function Body and they
are used for storing Temporary results.
 Arguments are the variables used in Function Calls.

Syntax for Function Definition:


def functionname(list of formal params):

-----------------------------------------------------
-----------------------------------------------------
Syntax for Function Call:
functionname(list of arguments)

 The relationship between Arguments and Parameters is that Every


Values of arguments is passing Formal Parameter.

Numbers of Arguments and Parameters:

Based on the values of arguments passing to parameters, the arguments


are classified into 5-Types. They are:

1. Positional Arguments (Default).


2. Default Arguments.
3. Keyword Arguments.
4. Variable Length Arguments.
5. Keyword Variable Length Arguments.
Functions in Python
1. Positional Arguments OR Parameters:

The concept of Positional Parameters or arguments says that “The


Number of Arguments (Actual Arguments) must be equal to the number
of Formal Parameters”.

This Parameters mechanism also recommend Order and Meaning of


Parameters for Higher Accuracy.

To Pass the Specific Data from Functional call to Functional Definition


then we must take Positional Argument Mechanism.

The default Arguments Passing Mechanism is Positional Arguments or


Parameters.

Syntax for Function Definition:

def functionname(parm1, parm2,…parm-n):


----------------------------------------------------------
----------------------------------------------------------
Syntax for Function Call:

functionname( arg1, arg2,…arg-n)

Here the values of arg1, arg2,…arg-n are passing to parm1,


parm2,…parm-n respectively.

2. Default Parameters or Arguments:

When there is a Common Value for family of Function Call 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).
Functions in Python
Syntax for Function Definition with Default Parameters:

Def functionname(parm1, parm2, …parm-(n-1)=val1, parm-n=val2):


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

Here parm-(n-1) and parm-n are called “Default Parameters” and


parm1, parm2 …. Are called “Positional Parameters”.

Rule: when we use Default Parameters in the Function Definition, they


must be used as the Last Parameters (s) otherwise we get
Error( SyntaxError: non-default(Positional) follows default argument).

Examples:
--------------
#ArgsParams.py
--------------------
def disp(a,b):
print("val of a={}".format(a))
print("val of b={}".format(b))

#main program
x=input("Enter Val of x:")
y=input("Enter Val of y:")
disp(x,y)
===========================================================
Prog 1: Program for demonstrating Possitional Arguments concept
#PosArgsex1.py
-----------------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks):
print("\t{}\t{}\t{}".format(stno,sname,marks))

#main program
print("="*50)
print("\tStno\tName\tMarks")
print("="*50)
dispstudinfo(10,"RS",34.56) # Function Call
dispstudinfo(20,"TS",54.56) # Function Call
dispstudinfo(30,"MC",14.16) # Function Call
dispstudinfo(40,"RT",56.78) # Function Call
print("="*50)
=======================================================
Functions in Python
Prog 2: Program for demonstrating Positional Arguments concept
#PosArgsex2.py
-----------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks,crs):
print("\t{}\t{}\t{}\t{}".format(stno,sname,marks,crs))

#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
dispstudinfo(10,"RS",34.56,"PYTHON") # Function Call
dispstudinfo(20,"TS",54.56,"PYTHON") # Function Call
dispstudinfo(30,"MC",14.16,"PYTHON") # Function Call
dispstudinfo(40,"RT",56.78,"PYTHON") # Function Call
print("="*50)
=========================================================
Prog 3: Program for demonstrating Default Arguments concept
#DefArgsex1.py
----------------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(stno,sname,marks,crs))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
dispstudinfo(10,"RS",34.56) # Function Call
dispstudinfo(20,"TS",54.56) # Function Call
dispstudinfo(30,"MC",14.16) # Function Call
dispstudinfo(40,"RT",56.78) # Function Call
dispstudinfo(50,"XR",26.78,"JAVA")# Function Call
dispstudinfo(60,"SR",26.78)
print("="*50)
==========================================================
Functions in Python
Prog 4: Program for demonstrating Default Arguments concept
#DefArgsex2.py
---------------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(stno,sname,marks,crs
,cnt))

#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse\tCountry")
print("="*50)
dispstudinfo(10,"RS",34.56) # Function Call
dispstudinfo(20,"TS",54.56) # Function Call
dispstudinfo(30,"MC",14.16) # Function Call
dispstudinfo(40,"RT",56.78) # Function Call
dispstudinfo(50,"XR",26.78,"JAVA")# Function Call
dispstudinfo(60,"SR",26.78)
dispstudinfo(70,"TR",16.78,"Django","USA")
print("="*50)
===========================================================
Prog 5: Program for demonstrating Default Arguments concept
#DefArgsex3.py
---------------------------------------------------------------------------------------
def disp(a=10,b=20,c=30):
print("\t{}\t{}\t{}".format(a,b,c))

#main program
print("="*50)
print("\ta\tb\tc")
print("="*50)
disp()
disp(100)
disp(100,200)
disp(100,200,300)
print("="*50)

================================================================
Functions in Python
Prog 6: Program for demonstrating Default Arguments concept
#DefArgsex4.py
---------------------------------------------------------------------------------------
def area(r,pi=3.14):
ar=pi*r**2
print("Area of Cirtcle={}".format(ar))

def peri(r,pi=3.14):
pr=2*pi*r
print("Perimeter of Cirtcle={}".format(pr))

#main program
area(float(input("Enter Radious for area cal:")))
peri(float(input("\nEnter Radious for peri cal:")))
==========================================================

3) Keyword Parameter OR Arguments:


In some of the circumstances, we know the function name and formal
Parameters names and we don’t know the order of formal parameters
names and to pass the data / value accurately we must use the concept
of Keyword Parameters or Arguments.
The implementation of Keyword Parameters or Arguments says that
all the formal parameters 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 Keyword


Arguments.
Functions in Python
Examples:
============================================================
#kwdargsex1.py a=10 b=20 c=30
def disp(a,b,c):
print("\t{}\t{}\t{}".format(a,b,c))
#main program
print("="*50)
print("\ta\tb\tc")
print("="*50)
disp(10,20,30) # Function Call with Possitionals
disp(c=30,a=10,b=20) # # Function Call with Key word args
disp(b=20,c=30,a=10) # # Function Call with Key word args
disp(10,c=30,b=20) # # Function Call with Possitionals and Key
word args
disp(10,20,c=30) # # Function Call with Possitionals and Key
word args
#disp(c=30,b=20,10) SyntaxError: positional argument follows
keyword argument
#disp(10,c=30,20) SyntaxError: positional argument follows
keyword argument
print("="*50)
============================================================
#kwdargsex1.py
def dispempinfo(eno,ename,sal,dsg):
print("\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg))

#main program
print("="*50)
print("\tEmpno\tName\tSal\tDesg")
print("="*50)
dispempinfo(10,"RS",1.2,"Author") # Function Call with
Possitional args
dispempinfo(sal=2.3,dsg="SE",eno=20,ename="DR")# Function Call
with kwd args
dispempinfo(dsg="TL",eno=30,sal=4.5,ename="TR") # Function
Call with kwd args
dispempinfo(40,"RT",dsg="TRINER",sal=2.3)# Function Call with
Pos args and kwd args
print("="*50)
============================================================
Functions in Python
===========================================================
#kwdargsex3.py
def dispempinfo(eno,ename,sal,dsg,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,cr
s))

#main program
print("="*50)
print("\tEmpno\tName\tSal\tDesg\tCourse")
print("="*50)
dispempinfo(10,"RS",1.2,"Author") # Function Call with
Possitional args
dispempinfo(sal=2.3,dsg="SE",eno=20,ename="DR")# Function Call
with kwd args
dispempinfo(dsg="TL",eno=30,sal=4.5,ename="TR") # Function Call
with kwd args
dispempinfo(40,"RT",dsg="TRINER",sal=2.3)# Function Call with
Pos args and kwd args
dispempinfo(50,"MC",1.5,"Jr.SE","JAVA")
dispempinfo(sal=3.4,crs="D.Sci",eno=60,dsg="PM",ename="DT")
print("="*50
===========================================================
#Varargsex2.py------This Program will execute as it is written
def disp(a): # Function Definition-1
print(a)
disp(10) # Function call-1

def disp(a,b): # Function Definition-2


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

disp(10,20) # Function Call-2

def disp(a,b,c): # Function Definition-3


print("{}\t{}\t{}".format(a,b,c))

disp(10,20,30) # Function Call-3

def disp(a,b,c,d): # Function Definition-4


print("{}\t{}\t{}\t{}".format(a,b,c,d))

disp(10,20,30,40) # Function Call-4


===========================================================
Functions in Python
4) Variable Length Parameters or Arguments:

When we have family of multiple function calls with Variable numbers


of values/arguments then with normal python programming, we must
define multiple function definition. This process leads to more
development time. To overcome this process, we must use the concept
of variable length Parameters.

To implement, Variable Length Parameters concept, we must define


single Function Definition and takes a formal Parameter process with a
symbol called asterisk (*param) and the formal parameters with asterisk
symbol is called Variable Length Parameters and whose purpose is to
hold / store any number of values coming from similar function call and
whose type is <class, ‘tuple’>.

Syntax for function definition with Variable length Parameters:

def functionname(list of formal params, *params, param2=value)


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

Here *param is called Variable Length Parameter and it can hold any number
of arguments 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 at last and before we use variable length
parameters and in function call, we should not use default parameter as
keyword argument because Variable number of Values are treated as
Positional Argument Value(s).
============================================================
Functions in Python
Examples:
==============================================================
#Varargsex1.py------This Program will not execute as it is
written
def disp(a): # Function Definition-1
print(a)
def disp(a,b): # Function Definition-2
print("{}\t{}".format(a,b))

def disp(a,b,c): # Function Definition-3


print("{}\t{}\t{}".format(a,b,c))

def disp(a,b,c,d): # Function Definition-4


print("{}\t{}\t{}\t{}".format(a,b,c,d))

#main program
disp(10) # Function call-1
disp(10,20) # Function Call-2
disp(10,20,30) # Function Call-3
disp(10,20,30,40) # Function Call-4
===========================================================
#Varargsex2.py------This Program will execute as it is written
def disp(a): # Function Definition-1
print(a)
disp(10) # Function call-1

def disp(a,b): # Function Definition-2


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

disp(10,20) # Function Call-2

def disp(a,b,c): # Function Definition-3


print("{}\t{}\t{}".format(a,b,c))

disp(10,20,30) # Function Call-3

def disp(a,b,c,d): # Function Definition-4


print("{}\t{}\t{}\t{}".format(a,b,c,d))

disp(10,20,30,40) # Function Call-4


===========================================================
Functions in Python
#PureVarargsex1.py
def disp( *a ): # Function definition with variable length
parameter
print("="*50)
print("Number of Values=",len(a))
for val in a:
print("{}".format(val),end=" ")
print()
print("="*50)
#main program
disp(10) # Function call-1
disp(10,20) # Function Call-2
disp(10,20,30) # Function Call-3
disp(10,20,30,40) # Function Call-4
disp(10,20,30,40,50) # Function Call-5
disp(10,20,30,40,50,60) # Function Call-6
disp("KVR","PYTHON") # Function Call-7
disp() # Function Call-8
disp(10,20,30,40,50,60, "KVR","PYTHON")
==============================================================
#Program for cal sum of Variable length Values
#PureVarargsex2.py
def findsum(sname,*a ):
print("-"*50)
print("Name of the student={}".format(sname))
s=0
for val in a:
print("{}".format(val),end=" ")
s=s+val
print()
print("sum={}".format(s))
print("-"*50)
def findmul(sname,*a ):
print("-"*50)
print("Name of the student={}".format(sname))
s=1
for val in a:
print("{}".format(val),end=" ")
s=s*val
print()
print("mul={}".format(s))
print("-"*50)
#main program
findsum("Naredra",10) # Function call-1
findsum("Ravi",10,20) # Function Call-2
findsum("Neel",10,20,30) # Function Call-3
findsum("Hema",10,20,30,40) # Function Call-4
findmul("SreeVani",10,20,30,40,50) # Function Call-5
findmul("Sruthi",10,20,30,40,50,60) # Function Call-6
findsum("Venkatesh") # Function Call-6
#findsum(-2,-3,-4,-5,"bavika") TypeError: unsupported operand
type(s) for +: 'int' and 'str'
findmul("praneeth",-5,-6,-7)
Functions in Python
============================================================
#PureVarargsex3.py
def dispstudinfo(id,uname,*snames,crs="PYTHON"):
print("-"*50)
print("\tId of Students:{}".format(id))
print("\tName of University:{}".format(uname))
print("\tCommon Course:{}".format(crs))
print("\tStudent Names:")
for name in snames:
print("\t{}".format(name))
print("-"*50)

#main program
dispstudinfo(1,"OU","RS","TR","MC")
dispstudinfo(2,"HCU","X","Y","Z","K")
#dispstudinfo("P","Q",id=3,crs="Django",uname="JNTU") --
TypeError: dispstudinfo() got multiple values for argument
'id'
dispstudinfo(3,"JNTU", "P","Q", crs="Django")
=============================================================

5. Keyword Variable Length Parameters OR Arguments:

When we have family of multiple function calls with Keyword Variable


number of values/arguments then with normal python programming, we
must defined multiple function definitions. 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


defined single Function Definition and take a Formal Parameter preceded
with a symbol called double asterisk (**param) and the formal parameter
with double asterisk symbol is called Keyword Variable Length Parameters
and whose purpose is to hold/store any number of (key, value) coming from
similar function calls and whose type is <class, ‘dict’>.

Syntax for function definition with Keyword Variable Length Parameters:

def functionname (list of formal params, **param):


-------------------------------------------------------------------
-------------------------------------------------------------------
Functions in Python
Here **param is called Keyword Variable Length Parameter and it can hold
any number of keyword argument values or Keyword variable number of
argument value and **param type is <class, ‘dict’>.

Rule: The **param must always written at last part of Function Heading and
it must be only one (but not multiple)

Final Syntax:

Def functionname(PosFormal params, *VarLen param, Default params,


**Keyword VarLen param):
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
==============================x=============================
#Program demonstrating Keyword Variable length Arguments
#kwdvarlenargsex1.py---This Program will not execute as it is
def dispinfo(sno,sname,marks): # Function Def-1
print("\t{}\t{}\t{}".format(sno,sname,marks))
def dispinfo(eno,ename): # Function Def-2
print("\t{}\t{}".format(eno,ename))
def dispinfo(tno,tname,sub1,sub2): # Function Def-3
print("\t{}\t{}\t{}\t{}".format(tno,tname,sub1,sub2))
#main program
dispinfo(sno=10,sname="RS",marks=22.22) # Function Call-1
dispinfo(eno=100,ename="TR") # Function Call-2
dispinfo(tno=1000,tname="KVR",sub1="PYTHON", sub2="JAVA") # #
Function Call-3
==========================================================
#Program demonstrating Keyword Variable length Arguments
#kwdvarlenargsex2.py---This Program will execute as it is
def dispinfo(sno,sname,marks): # Function Def-1
print("\t{}\t{}\t{}".format(sno,sname,marks))

dispinfo(sno=10,sname="RS",marks=22.22) # Function Call-1

def dispinfo(eno,ename): # Function Def-2


print("\t{}\t{}".format(eno,ename))

dispinfo(eno=100,ename="TR") # Function Call-2

def dispinfo(tno,tname,sub1,sub2): # Function Def-3


print("\t{}\t{}\t{}\t{}".format(tno,tname,sub1,sub2))

dispinfo(tno=1000,tname="KVR",sub1="PYTHON", sub2="JAVA") # #
Function Call-3
Functions in Python
==========================================================
#Program demonstrating Keyword Variable length Arguments
#purekwdvarlenargsex1.py
def dispinfo( **k ):
print("-"*50)
for k,v in k.items():
print("\t{}-->{}".format(k,v))

print("-"*50)

#main program
dispinfo(sno=10,sname="RS",marks=22.22) # Function Call-1
dispinfo(eno=100,ename="TR") # Function Call-2
dispinfo(tno=1000,tname="KVR",sub1="PYTHON", sub2="JAVA") # #
Function Call-3
dispinfo(cid=1,cname="XR",Hobby1="Reading",
Hobby2="Practcing",Hobby3="Sleeping")
================================================
#Program for finding total marks of different students who are
studying in different class and securing in different subjects.
#purekwdvarlenargsex2.py
def findtotalmarks(sno,sname,cls,**submarks):
print("="*50)
print("Student Number={}".format(sno))
print("Student Name={}".format(sname))
print("Student Class Name={}".format(cls))
totmarks=0
for sn,sm in submarks.items():
print("\t{}--->{}".format(sn,sm))
totmarks=totmarks+sm
if(totmarks>0):
print("Total Marks={}".format(totmarks))
per=(totmarks / (len(submarks)*100))*100
print("Percentage={}".format(per))
print("="*50)
else:
print("Total Marks={}".format(totmarks))
print("Percentage={}".format(0))
print("="*50)

#main program
findtotalmarks(10,"Surya","X",Eng=50,Hindi=60,Telugu=67,Maths=60
,Sci=80,Soc=70)
findtotalmarks(20,"Pradip","XII",Mathematics=70,Physics=58,Chemi
stry=54)
findtotalmarks(30,"Manaiah","B.Tech(CSE)",CM=70,Python=60)
findtotalmarks(40,"Rossum","Research")
===============================================
Functions in Python
#purekwdvarlenargsex3.py
def disp(no,sname,*n,**hyd):
print("="*50)
print("\tNumber={}".format(no))
print("\tName={}".format(sname))
print("Variable Argument Values:")
for v in n:
print("\t{}".format(v))
print("Keyword Variable Argument Values:")
for k,v in hyd.items():
print("\t{}-->{}".format(k,v))
print("="*50)

#main program
disp(1,"RS",10,20,30,a=100,b=200)
disp(2,"TR",50,60,x=1,y=2,z=3)
disp(3,"MC",10,20,30,40,p=-1,q=-2,r=-3,k=-4)
===============================================
#purekwdvarlenargsex4.py
def disp(no,sname,*n,city="HYD",**hyd):
print("="*50)
print("\tNumber={}".format(no))
print("\tName={}".format(sname))
print("\tLiving City={}".format(city))
print("Variable Argument Values:")
for v in n:
print("\t{}".format(v))
print("Keyword Variable Argument Values:")
for k,v in hyd.items():
print("\t{}-->{}".format(k,v))
print("="*50)

#main program
disp(1,"RS",10,20,30,a=100,b=200)
disp(2,"TR",50,60,x=1,y=2,z=3)
disp(3,"MC",10,20,30,40,p=-1,q=-2,r=-3,k=-4)
disp(300,"MR",40,50,city="Bang")
disp(400,"MX",4,5,6,7,-8,city="USA",hobby="Playing",job="SE")
disp(99,"KV", 4,city="AP",district="PRAKASHAM",PINCODE=533369)
disp(99,"KV", 4, district="PRAKASHAM",PINCODE=533369,city="AP")
disp(99,"KV", 4, district="PRAKASHAM",PINCODE=533369)

==================x====================
Functions in Python

Global variables and Local variables

Local variables are those which are defined / used inside of function.
Local variable can be used for storing temporary result of function.
The values of Local variables can be used inside of same Function Definition
but not possible to access in other part of the program and in other
Function Definition.

Global variables are those which are used for representing common values
for multiple different function calls and saves the memory space.
Global variables must be defined before all function calls. So that we can
access the Global variable values in all the function definitions. Otherwise
we can’t access.

Syntax:
Var1=Val1
Var2=Val2
-------------
Var-n=Val-n

def functionname1(.....):
var22=val22
var23=val23
------------------
def functionname2(.....):
var32=val32
var33=val33
Here Var1, Var2… Var-n are called Global variable for functionname1() and
functionname2().
Here Var22, Var23… are called Local Variables for functionname1().
Here Var32, Var33… are called Local Variables for functionname2().
Functions in Python
Examples:
=============================================================
#globallocalvarex3.py
---------------------
def learnML():
sub1="Machine Learning" # here sub1 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub1,lang))
#print(sub2,sub3)---Error bcoz sub2 and subj3 are local
variables in other Functions

def learnDL():
sub2="Deep Learning" # here sub2 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub2,lang))
#print(sub1,sub3)---Error bcoz sub1 and subj3 are local
variables in other Functions
def learnIOT():
sub3="IOT" # here sub3 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub3,lang))
#print(sub1,sub2)---Error bcoz sub1 and subj1 are local
variables in other Functions
#main program
lang="PYTHON" # Global Variable
learnML()
learnDL()
learnIOT()
=================================================
#globallocalvarex4.py
----------------------
def learnML():
sub1="Machine Learning" # here sub1 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub1,lang))

def learnDL():
sub2="Deep Learning" # here sub2 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub2,lang))

def learnIOT():
sub3="IOT" # here sub3 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub3,lang))
Functions in Python
#main program
learnML()
learnDL()
learnIOT()
lang="PYTHON" # Global Variable --here we can' t access
Variable lang in learnML(), learnDL() and LearnIOT() bcoz It
is defined after Function Call.
===============================================
#globallocalvarex1.py
----------------------
lang="Python" # Here lang is called Global variable
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
learnDS()
learnML()
learnDL()
=================================================
#globallocalvarex2.py
----------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
lang="Python" # Here lang is called Global variable
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
Functions in Python
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
learnDS()
learnML()
learnDL()
============================================================
#globallocalvarex3.py
---------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()

def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()

def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
lang="Python" # Here lang is called Global variable
#main program
learnDS()
learnML()
learnDL()
=================================================================
#globallocalvarex4.py
----------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
Functions in Python
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
lang="Python" # Here lang is called Global variable
learnDS()
learnML()
learnDL()
================================================================
#globallocalvarex5.py
----------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()

def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()

def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
#learnDS() # We can't access 'lang' variable' value in
learnDS()
lang="Python" # Here lang is called Global variable
learnML() # We can access 'lang' variable' value in learnML()
and learnDL()
learnDL()
=================================================================
Functions in Python

Global key word

When we want modify the GLOBAL VARIABLE values inside of Function


Definition then global variable names must be preceded with 'global'
keyword otherwise we get "UnboundLocalError: local variable names
referenced before assignment"

Syntax:
-----------
var1 = val1
var2 = val2
var-n = val-n # var1, var2... var-n are called global variable names.
------------------
def fun1():
------------------------
global var1, var2... var-n
# Modify var1, var2.... var-n
--------------------------
def fun2():
------------------------
global var1, var2... var-n
# Modify var1, var2.... var-n
--------------------------
================================================================
Examples:
================================================================
#globalvarex1.py
----------------
a=10
def access1():
print("Val of a=",a) # Here we are accessing the global
variable 'a' and No Need to use global kwd.

#main program
access1()
---------------------------------------
Functions in Python
#globalvarex2.py
a=10
def access1():
global a # refering global Varaible before its updation
/ Modification
a=a+1 # Here we are modifying the global variable value
then we need to use
global keyword.
print("Val of a inside of access1()=",a) # 11
#main program
print("Val of a in main before access1():",a) # 10
access1()
print("Val of a in main after access1():",a) # 11
==============================================================
#globalvarex3.py
------------------
def update1():
global a,b # refering global Variables.
a=a+1 #updating global Variable a
b=b+1 #updating global Variable b
def update2():
global a,b # refering global Variables.
a=a*10 #updating global Variable a
b=b*10 #updating global Variable b

#main program
a,b=1,2 # here a and b are called Global Variables
print("Val of a={} and Value of b={} in main program before
update functions :".format(a,b))
# Val of a=1 and Value of b=2 in main program before update
functions :
update1()
print("Val of a={} and Value of b={} in main program after
update1():".format(a,b))
#Val of a=2 and Value of b=3 in main program after update1():
update2()
print("Val of a={} and Value of b={} in main program after
update2():".format(a,b))
#Val of a=20 and Value of b=30 in main program after update1():
================================================================

#globalkwdex1.py
-----------------
Functions in Python
a=10 # Here 'a' is called global Variables
def accessvalue1():
print("Val of a in accessvalue1() ={}".format(a))

def accessvalue2():
print("Val of a accessvalue2()={}".format(a))

#main program
accessvalue1()
accessvalue2()
==================================================================
#globalkwdex2.py
-----------------
a=10 # here 'a' is global Variable
def increment():
global a # refering global variable value
a=a+1
#main program
print("Val of a in main program before incrment()=",a) # 10
increment()
print("Val of a in main program after incrment()=",a) # 11
=================================================================
#globalkwdex3.py
----------------
a=10 # here 'a' is global Variable
b=20 # here 'b' is global Variable
def increment():
global a,b # refering global variable value
a=a+2
b=b+2
#main program
print("Val of a in main program before incrment()=",a) # 10
print("Val of b in main program before incrment()=",b) # 20
increment()
print("Val of a in main program after incrment()=",a) # 12
print("Val of b in main program after incrment()=",b) # 22
==================================================================
#globalkwdex4.py
----------------
a=2
b=3
def update1():
global a,b
a=a+1
b=b+1
def update2():
global a,b
a=a*10
b=b*10

#main program
print("Val of a in main program before update1()=",a) # 2
Functions in Python
print("Val of b in main program before update1()=",b) # 3
update1()
print("Val of a in main program after update1()=",a) # 3
print("Val of b in main program after update1()=",b) # 4
update2()
print("Val of a in main program after update2()=",a) # 30
print("Val of b in main program after update2()=",b) # 40
==================================================================

Global and Local variables and globals()

When we come across same global variable names and Local variable
name in same function definition then PVM gives preference for Local
variables but not for Global variables.
In this context, to extract/retrieve the value of global variables name
along with local variable, we must use globals() and returns an object of
<class, ‘dict’> and this object stores all global variable name as Keys and
global variable 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-n #var1, var2,…var-n are called Local Variables.
#Extract the Global Variable values.
Dictobj = globals()

globalval1 = dictobj[‘var1’] # or
Functions in Python
dictobj.get("var1") or
globals()['var1']
globalval2=dictobj['var2'] # or
dictobj.get("var2") or
globals()['var2']
==========================================================
Examples:
==========================================================
#globalsfunex3.py
-------------------
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================

#main program
operations()
Functions in Python
==================================================
Examples:
-----------------------
#Program for demonstrating globals()
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()[
'c']+globals()['d']
print(res)

#main program
operation()
=========================================================
#globalsfunex1.py
-------------------
a=10
b=20
c=30
d=40 # here 'a' 'b' 'c' and 'd' are called global Variables
def operation():
a=1
b=2
c=3
d=4 # here 'a' 'b' 'c' and 'd' are called local
Variables
print("val of a-local=",a)
print("val of b-local=",b)
print("val of c-local=",c)
print("val of d-local=",d)
print("val of a-global=",globals().get('a'))
print("val of b-global=",globals().get('b'))
print("val of c-global=",globals()['c'])
print("val of d-global=",globals()['d'])
res=a+b+c+d+globals().get('a')+globals().get('b')+global
s()['c']+globals()['d']
print("result=",res)
#main program
operation()
==========================================================

#globalsfunex2.py
------------------
Functions in Python
a=10
b=20
c=30
d=40 # here 'a' 'b' 'c' and 'd' are called global Variables
def fun1():
kvr=globals()
for k,v in kvr.items():
print("\t{}\t{}".format(k,v))
print("---------------------------------")
print("val of a=",kvr['a'])
print("val of b=",kvr['b'])
print("-----------OR----------------------")
print("val of a=",kvr.get('a'))
print("val of b=",kvr.get('b'))
print("-----------OR----------------------")
print("val of a=",globals().get('a'))
print("val of b=",globals().get('b'))
print("-----------OR----------------------")
print("val of a=",globals()['a'])
print("val of b=",globals()['b'])

#main program
fun1()
==========================================================

Anonymous Function or Lambda Functions

Anonymous Function are those, which does not contains the any name
explicitly.
The purpose of Anonymous function is that “To perform Instant
Operation”.
Instant Operations are those, which are used at that point of time and
no longer interested to use in further applications.
To define anonymous function, we use a keyword lambda and
Anonymous Function are also called Lambda Function.
Anonymous Function contains single executable statement but not
containing block of statements.
Anonymous Function returns the result automatically (no need to use
write return statement explicitly).
Functions in Python
Syntax: varname = lambda params-list : expression

Explanation:
Here “varname” is an object and itself act as function Name because
varname is an object of <class, ‘function’>.
Lambda is a keyword used for defining Anonymous Function.
params-list represents list of variable names used for Holding or storing
input values coming from Function Calls.
Expression represents single executable statement and it performs
Instant Operation and whose result returned automatically.
======================================
#Normal Function Definition and Function Call
-------------------------------------------------------------
Def sumop(a,b):
res1=sumop(10,20)
c=a+b
print(“sum=”,res1)
return c
------------------------------------------------------------------
#Anonymous Function Definition and Function call
-------------------------------------------------------------------
Sumop=lambda a,b: a+b
res1= sumop(100,200)
print(“sum=”,res1)
----------------------------------------------------------------------------
#Program for performing sum of two number by using Anonymous
Functions
#AnonymouseFunEx1.py
--------------------------------------------------------------
def sumop(a,b): # Normal Function
c=a+b
return c
addop=lambda k,v: k+v # Anonymous Function
#main program
print("type of sumop obj=",type(sumop)) # type of sumop obj=
<class 'function'>
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res1=sumop(a,b) # Normal Function Call
print("Sum=",res1)
Functions in Python
print("-----------------------------------------------------")
print("type of addop obj=",type(addop)) # type of addop obj=
<class 'function'>
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res2=addop(a,b) # Anonymous Function call
print("Sum=",res2)
======================================================================
#Program for performing Temporature conversions.
#AnonymouseFunEx2.py
---------------------------------------------
ft=lambda ct:(9/5)*ct+32 # Anonymous Function1
kt=lambda ct: ct+273 # Anonymous Function2

#main program
ct=float(input("Enter Temporatue in Celciou:"))
fttemp=ft(ct) # Anonymous Function call-1
print("Foreign Heat Temp({}
celcious)={}".format(ct,fttemp))
kttemp=kt(ct) # Anonymous Function call-2
print("Kelvin Temp({}
celcious)={}".format(ct,kttemp))
==========================================
#Program for performing finding biggest and smallest
among two numbers
#AnonymouseFunEx3.py
-----------------------------------------------------
findmaxval=lambda k,v : k if k>v else v
findminval=lambda k,v : k if k<v else v

#main program
a,b=float(input("Enter First
Value:")),float(input("Enter Second Value:"))

print("Max
Value({},{})={}".format(a,b,findmaxval(a,b)))
print("Min
Value({},{})={}".format(a,b,findminval(a,b)))
==================================================================
Functions in Python
#Program for performing finding biggest and smallest
among two numbers
#AnonymouseFunEx4.py
-----------------------------------------------------
findmaxval=lambda k,v : "Both Values are Equal" if
(k==v) else k if (k>v) else v
findminval=lambda k,v : "Both Values are Equal" if
(k==v) else k if (k<v) else v

#main program
a,b=float(input("Enter First
Value:")),float(input("Enter Second Value:"))
print("Max
Value({},{})={}".format(a,b,findmaxval(a,b)))
print("---------------------------------------")
a,b=float(input("Enter First
Value:")),float(input("Enter Second Value:"))
print("Min
Value({},{})={}".format(a,b,findminval(a,b)))
==========================================================
#write a python program which will accept a three
numerical values and find the biggest and smallest
among them
#AnonymouseFunEx5.py
-----------------------------------------------------
findmaxval=lambda k,v,r: "ALL Values are Equal" if
(k==v==r) else k if(v<k>r) else v if(k<v>r) else r
findminval=lambda k,v,r: "ALL Values are Equal" if
(k==v==r) else k if(v>k<r) else v if(k>v<r) else r

#main program
a,b,c=float(input("Enter First
Value:")),float(input("Enter Second
Value:")),float(input("Enter Third Value:"))
max1=findmaxval(a,b,c)
min1=findminval(a,b,c)
print("max({},{},{})={}".format(a,b,c,max1))
print("min({},{},{})={}".format(a,b,c,min1))
===================================================
Functions in Python
#write a python program which will accept list of
numerical values and find max and min by using
anonymous functions
#AnonymouseFunEx6.py
-----------------------------------------------------
maxv=lambda lst:max(lst)
minv=lambda lst:min(lst)

#main program
print("Enter List of Values Separated by Space:")
lst=[ float(val) for val in input().split()]
bv=maxv(lst)
print("max({})={}".format(lst,bv))
sv=minv(lst)
print("min({})={}".format(lst,sv))
Functions in Python

Special Function in Python

In Python Programming, we have 3 Special Functions, They are:

1) filter 2) map() 3) reduce()

1) Filter(): It is used for “Filtering out some element from list of elements
by applying to function”.

Syntax: varname = filter(functionName, iterable_object)

Explanation:
Here ‘varname’ is an object of type <class,’filter’> and we can convert into
any iterable object by using type casting functions.

‘funtionName’ represents either Normal function or Anonymous functions.


‘iterable_object’ represents sequence, list, set and dict types.

The execution process of filter() is that “Each value of iterable_object send


to functionName. If the function returns True then that element will be
filtered. If the function returns False then that element will be
neglected/not filtered”. This process will be continued until all elements of
iterable_object completed.
Functions in Python
Examples:
===========================================================
#Program for filtering Possitive Elements from list of
elements by using Normal Functions
#FilterEx1.py
--------------------------------------------------------------
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,-56,78,0,-45,-79,-34,56]
obj1=filter(positive,lst) # Filter() filtering Possitive
Values
print(obj1, type(obj1)) # <filter object at
0x000001F1246604C0> <class 'filter'>
pslist=list(obj1) # Converting filter object into list type
print("Original Elements=",lst)
print("Possitive Elements=",pslist)
obj2=filter(negative,lst) # Filter() filtering Negative
Values
print(obj2, type(obj2)) # <filter object at
0x000002B3ED927F10> <class 'filter'>
nstpl=tuple(obj2)
print("Negative Elements=",nstpl)

============================================================
#Program for filtering Possitive and Negative Elements from
list of elements by using Anonymous Functions

#FilterEx2.py

positive=lambda n: n>0 # Anonymous Function-1

negative=lambda x: x<0 # Anonymous Function-2


Functions in Python
#main program

print("Enter List of elements separated by space:")

lst=[int(val) for val in input().split()]

pslist=list(filter(positive,lst ) ) # [10, 20, -45, -23, -2,


12, -6, 78, 0, 23]

nslist=tuple(filter(negative,lst ) ) # [10, 20, -45, -23, -2,


12, -6, 78, 0, -23]

print("\nOriginal Elements=",lst)

print("Possitive Elements=",pslist)

print("Negative Elements=",nslist)
============================================================
#Program for filtering Possitive and Negative Elements from
list of elements by using Anonymous Functions
#FilterEx3.py
print("Enter List of elements separated by space:")
lst=[int(val) for val in input().split()]

pslist=list(filter(lambda n: n>0,lst ) ) # [10, 20, -45, -23,


-2, 12, -6, 78, 0, 23]

nslist=tuple(filter(lambda x: x<0,lst ) ) # [10, 20, -45, -


23, -2, 12, -6, 78, 0, -23]

print("\nOriginal Elements=",lst)
print("Possitive Elements=",pslist)
print("Negative Elements=",nslist)
==============================================================
#Program for filtering Odd and Even Elements from list of
elements by using Anonymous Functions and Normal Functions.
#FilterEx4.py
def even(n):
if n%2==0:
return True
else:
return False

odd=lambda x : x%2!=0 # Anonymous Function-1

print("Enter List of elements separated by space:")


lst=[int(val) for val in input().split()]
evenlist=list(filter(even,lst)) # Filter() with Normal Function
oddlist=list(filter(odd,lst)) # Filter() with Anonymous Function
print("\nOriginal Elements=",lst)
print("Even Elements=",evenlist)
print("Odd Elements=",oddlist)
==============================================================
Functions in Python
#write a python program which will accept line of text and
obtains list of vowels by using filter()
#FilterEx5.py
def cons(ch):
if ch not in ['a','e','i','o','u','A','E','I','O','U']
and ch.isalpha():
return True
else:
return False

#main program
line=input("Enter a line of text:") # Python3
print("\nGiven Line=",line)
vwlist=list(filter(lambda ch: ch in
['a','e','i','o','u','A','E','I','O','U'],line))
conslist=list(filter(cons,line))
print("Vowels List=",vwlist)
print("Number of Vowels=",len(vwlist))
print("Cons list=",conslist)
print("Number of consonats=",len(conslist))

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

2) Map(): It is used for obtaining new iterable object from existing iterable
object by applying old iterable object element to the function.

In the other word, map() is used for obtaining new list of elements from
existing list of element by applying old list element to the function.

Syntax: varname = map(functioName, iterable_object)

Explanation:
Here ‘varname’ is an object of type <class, map> and we can convert
into any iterable object by using type-casting functions.

‘functionName’ represents either Normal function or Anonymous


functions.

‘iterable_object’ represents sequence, list, set, and dict types.

The execution process of map() is that “ map sends every element of


iterable object to the specified function, process it and return the
modified value (result) and new list of element will be obtained”. This
prosses will be continued until all elements of iterable _object
completed.
Functions in Python
#Program for obtaining Square for every element of list by
using map() with Normal Function
#mapex1.py
--------------------------------------------------------------
def square(n):
return n**2

#main program
lst=[2,4,5,-3,6,7]
obj1=map(square,lst)
print(obj1,type(obj1)) # <map object at 0x00000218FF330310>
<class 'map'>
sqlist=list(obj1)
print("Original List=",lst)
print("Square List=",sqlist)
==============================================================
#Program for obtaining Square for every element of list by
using map() with Anonymous Function
#mapex2.py
--------------------------------------------------------------
print("Enter List of elements separated by space:")
lst=[int(val) for val in input().split()]
sqlist=list(map(lambda x: x**2,lst))
sqrtlist=list(map(lambda x: x**0.5,lst))
print("\nOriginal List=",lst)
print("Square List=",sqlist)
print("Square Root List=",sqrtlist)
==============================================================
#Program for obtaining new sal list from oldsal list by giving
10% hike by using map()
#mapex3.py
print("Enter List of elements separated by space:")
oldsal=[int(val) for val in input().split()]
newsal=list(map(lambda sal:sal+sal*10/100,oldsal ))
print("\nOld Salary List=",oldsal)
print("\nNew Salary List=",newsal)
==============================================================

3) Reduce() : reduce() is used for obtaining a single element/ result from


given iterable object by applying to a function.

Syntax: varname=reduce(functionName, iterable_object)

Here varname is an object of int, float, bool, complex, str Only.

The reduce() belongs to a pre-defined module called “functools”.


Functions in Python
Internal flow of reduce ():

Step1: reduce() select two first values of iterable object and place
them in first var and second var.

Step2: The functionName (lambda or Normal function) utilizes the


values of First var and second var applied to the specified logic and
obtains the result.

Step3: reduce() places the result of functionName in the first variable


and reduce() selects the succeeding element of iterable object and
places in second var.

Step4: repeat step2 and step3 until all element completed in iterable
object and return the result of first var.

Pictorial explanation/Flow of reduce ():

Examples:
========================================================
#Program for reading list of values and obtains sum by using
reduce()
#reduceex1.py
--------------------------------------------------------------
import functools
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
result=functools.reduce(lambda x,y: x+y,lst)
print("Sum({})={}".format(lst,result))
=============================================
Functions in Python
#Program for reading list of values and obtains sum by using
reduce()
#reduceex2.py
-----------------------------------------------------------
import functools
def sumop(x,y):
c=x+y
return c

#main program
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
result=functools.reduce(sumop,lst)
print("Sum({})={}".format(lst,result))
=======================================================
#write a python program which will accept list of names or
words and concatnet them
#reduceex3.py
--------------------------------------------------------------
import functools as k
print("Enter List of words separated by comma:")
lst=[str(val) for val in input().split(",")]
line=k.reduce(lambda a,b: a+" "+b, lst)
print("\nGiven words=",lst)
print("Concatination of words=",line)
========================================================
#write a python program which will accept list of values and
find max and min values by using reduce()
#reduceex4.py
--------------------------------------------------------------
import functools as k
print("Enter List of values separated by comma:")
lst=[int(val) for val in input().split(",")]
maxv=k.reduce(lambda a,b: a if a>b else b, lst)
minv=k.reduce(lambda a,b: a if a<b else b, lst)
print("\nmax({})={}".format(lst,maxv))
print("min({})={}".format(lst,minv))
========================================================
#write a python program which will accept list of values and
find max and min values by using reduce()
#reduceex5.py
-------------------------------------------------------------
import functools as k
print("Enter List of words separated by comma:")
lst=[str(val) for val in input().split(",")]
maxv=k.reduce(lambda a,b: a if a>b else b, lst)
minv=k.reduce(lambda a,b: a if a<b else b, lst)
print("\nmax({})={}".format(lst,maxv))
print("min({})={}".format(lst,minv))
========================================================
Functions in Python
#write a python program which will accept list of numericle
values and find squares for positive numbers and cubes for
negative numbers
#filtermapex.py
------------------------------------------------------------
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]

sqlist=list(map(lambda x: x**2,list(filter(lambda n:n>0,lst )


) ) )
cubeslist=list(map(lambda x: x**3,list(filter(lambda n:n<0,lst
) ) ) )
print("\nOriginal List:{}".format(lst))
print("Square list :{}".format(sqlist))
print("Cubes list :{}".format(cubeslist))
=============================================
#write a python program which will accept list of values find
sum of positive numericles and negative numericles
#reducefilterex.py
--------------------------------------------------------------
import functools as kvr
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
possum=kvr.reduce(lambda x,y:x+y, list(filter(lambda x : x>0,
lst)))
negsum=kvr.reduce(lambda x,y:x+y, list(filter(lambda x : x<0,
lst)))
print("Possitive Sum=",possum)
print("Negative Sum=",negsum)
=============================================================
#write a python program which will accept list of values
separated by space. Find sum of squares of positive numbers
and sum of square of negative numbers.
#reducemapfilterex.py
--------------------------------------------------------------
from functools import reduce
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
possqsum=reduce(lambda x,y:x+y, list(map(lambda x:
x**2,list(filter(lambda n: n>0,lst)))))
negsqsum=reduce(lambda x,y:x+y, list(map(lambda x:
x**2,list(filter(lambda x: x<0,lst)))))
print("\nSum of Squares of Possitive Numbers =",possqsum)
print("Sum of Squares of Negative Numbers =",negsqsum)
========================================================
Modules in Python
Index

 Purpose of Modules
 Definition of Module
 Types of Modules—a) Pre-defined Modules
b) Programmer-defined Modules
 Development Programmer-defined Modules
 Techniques for re-using the Modules
a) By using import statement (4-Syntaxes)
b) By using from… import statement (3-Syntaxes)
 Programming Examples
 Re-loading the Modules
 Programming Examples
Modules in Python
Modules in Python:

We know that functions concept makes us understand how to perform


operations and we can re-use within the same program but unable to re-use
the function across the program.

To re-use the functions and global variables across the programs, we must
use the concept of Modules.

Definition of Module: A Module is a collection of variables (global),


Functions and Classes.

Types of Modules: In Python programming, we have two types of Modules.


They are:

1) Per-defined or Built-in Modules


2) Programmer or user or custom-defined Modules.

1) Pre-defined or built-in Modules: These modules are developed by Python


Language Developers and they are available in Python Software (APIs) and
the are used Python programmers for dealing with Universal Requirement.

Examples: math, cmath, functools, sys, calendar, os, re threading, pickle,


random….etc.

Out of many pre-defined Modules, in Python programming one implicity pre-


defined module imported to every python program called “builtins”.

2) Programmer or user or custom-defined Modules: These Modules are


developed by Python Programmer and they are available in Python
Project and they are used by other Python programmers who are in
project development to deal with common requirements.

Examples: aop, mathsinfo, icici….etc.


Modules in Python

Development of Programmer-defined Module

To develop Programmer-Defined Modules, we must use the following steps:

Step-1: Define Variable (Global)


Step-2: Define Functions
Step-3: Define Classes

Number of approaches to re-use Modules

We know that A Module is a collection of variables, Functions and Classes.


To re-use the features (Variable Names, Function Names and Class
Names) of module, we have 2 approaches. They are
1) By using import statement
2) By using from.... import statement.
Modules in Python
1) By using import statement:
'import' is a keyword
The purpose of import statement is that "To refer or access the
variable names, function names and class names in current program".
we can use import statement in 4 ways.
Syntax-1: import module name
This syntax imports single module
Example:
import aop

-----------------------------------------------------------------------
Syntax-2:
import module name1, module name2....Module name-n
This syntax imports multiple modules
Example: import icici , aop, mathsinfo
--------------------------------------------------------------------------------------------
Syntax-3:
import module name as alias name

This syntax imports single module and aliased with another name
Example: import icici as i
import aop as a
import mathsinfo as m
--------------------------------------------------------------------------------------------
Modules in Python
Syntax-4:
import module name1 as alias name, module name2 as alias
name......module name-n as alias name
This syntax imports multiple modules and aliased with another names

Example: import icici as i, aop as a, mathsinfo as m

Hence after importing all the variable names, Function names and
class names by using "import statement" , we must access variable
names, Function names and class names w.r.t Module Names or alias
names.
Module Name.Variable Name
Module Name.Function Name
Module Name.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name
=======================================================================
3) By using from.... import statement.
-----------------------------------------------
Here "form" "import" are the key words
The purpose of from.... import statement is that " To refer or access
the variable names, function names and class names in current
program directly without writing module name."
we can use from.... import statement in 3 ways.
Syntax-1:
from module name import Variable Names,Function Names, Class
Names
This syntax imports the Variable Names,Function Names, Class Names
of a module.
Modules in Python
Example: from calendar import month
from aop import addop,subop
from mathinfo import pi,e
from icici import bname,loc,l simpleint
--------------------------------------------------------------------------------------------
Syntax-2:
from module name import Variable Names as alias name,Function
Names as alias name , Class Names as alias names.
This syntax imports the Variable Names, Function Names, Class
Names of a module with alias Names

Example: from calendar import month as m


from aop import addop as a,subop as s, mulop as m
from mathinfo import pi as p ,e as k
from icici import bname as b,loc as l , simpleint as si
-------------------------------------------------------------------
Syntax-3: from module name import *
This syntax imports ALL Variable Names, Function Names, Class
Names of a module.
This syntax is not recommended to use bcoz it imports required
Features of Module and also import un-interested features also
imported and leads more main memory space.

Example: from calendar import *


from aop import *
from mathsinfo import *
Hence after importing all the variable names, Function names and
class names by using "from ....import statement" , we must access
variable names, Function names and class names Directly without
using Module Names or alias names.

Variable Name
Function Name
Class Name
Modules in Python
Hence with "import statement” we can give alias name for module
names only but not for Variables Names, Function Names and Class
Names. Whereas with "from ... import statement" we can give alias
names for Variables Names, Function Names and Class Names but not
for Module Name.
=========================================X============================================
Examples:
-------------
#aop.py---file name and itself acts as module name
--------------------------------------------------------------
def sumop(a,b): # Function Def-1
c=a+b
print("sum({},{})={}".format(a,b,c))
def subop(a,b): # Function Def-2
c=a-b
print("sub({},{})={}".format(a,b,c))
def mulop(a,b): # Function Def-3
c=a*b
print("mul({},{})={}".format(a,b,c))
==========================================================
#Approach1.py

import aop

aop.sumop(10,20)
==========================================
#Approach2.py
import icici, aop
icici.simpleint()
aop.sumop(10,20)
==========================================================
#Approach3.py
i
import aop as a

a.sumop(10,20)
==========================================================
#Approach4.py
import icici as ic, aop as a
ic.simpleint()
a.sumop(10,20)
==========================================================
Modules in Python
#Approach5.py
from icici import bname, loc, simpleint
print("\nBank Name:{}".format(bname))
print("\nBank Location:{}".format(loc))
simpleint()
==========================================================
#Approach6.py
from icici import bname as bn, loc as l, simpleint as si
print("\nBank Name:{}".format(bn))
print("\nBank Location:{}".format(l))
si()
==============================================
#Approach7.py
from icici import *
print("\nBank Name:{}".format(bname))
print("\nBank Location:{}".format(loc))
simpleint()
==============================================
Modules in Python

Re-loading a modules in Python

To reload a module in python, we use a pre-defined function called reload (),


which is present in imp module and it was deprecated in favour of importlib
module.

Syntax: imp.reload(module name)


OR
Importlib.reload(module name) ----------- Recommended

Purpose/Situation:
reload () reload 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/update values/new version of previously loaded module then we use
reload().

Examples:
===================================
#shares.py---file name and acts as module name
def sharesinfo():
d={"IT":401,"Pharma":301,"Fin":371,"Auto":150}
return d
-------------------------------------------------------------------------
#sharesdemo.py
import time
import shares
import importlib #imp module deprecated in favour of importlib

def dispshares(d):
print("="*50)
print("\tShare Name\tShare Value")
print("="*50)
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("="*50)
Modules in Python
#main program
dt=shares.sharesinfo()
dispshares(dt)
print("Line-16-->PVM is going to sleep for 20 secs")
time.sleep(20) # PVM pause the execution
print("Line-18-->PVM is commig out of sleep ")
importlib.reload(shares)
dt=shares.sharesinfo()
dispshares(dt)
===============================================
Package in Python

Package in Python

The Function concept is used for performing some operation and


provides code re-usability within the same program and unable to
provide code re-usability across programs.

The Modules concept is a collection of variables, functions and classes


and we can re-use the code across the Programs provided Module name
and Main program present in the same folder but unable to provide
code re-usability across the Folders/Drives/Environments.

The Package concept is a collection of Modules.


The purpose of Packages is that to provide code re-usability across the
Folders/Drives/Environments.
Package in Python
Re-use the package: To re-use the modules of the packages across the
Folders/Drives/Environment, we have two approaches. They are:
1) By using sys module
2) By using PYTHONPATH Environmental Variable name

1) By using sys module:

Syntax: sys.path.append(“absolute path of package”)

Sys is pre-defined module.

Path is a predefined object/variable present in sys module


Append() is pre-defined function present in path and is used for locating
the package name of python(specify the absolute path).

Examples:
sys.path.append("D:\\python")
(or)
sys.path.append("D:\python")

2) By using PYTHONPATH Environmental Variable name:

PYTHONPATH is one of the Environment Variable, search for


Environment Variable.

Steps for setting:


Var Name : PYTHONPATH
Var Value : D:\python
Exception Handling in Python

Exception Handling in Python

Index

 Purpose of Exception Handling


 Type of Errors in Python
a) Compile Time Error
b) Logical Errors
c) Runtime error

 Define Exception.
 Define Exception Handling.
 Types of Exceptions.
a) Per-defined or Built-in Exceptions
b) Programmer/User/Custom defined Exceptions
 Handling Exceptions
 Keyword for Handling Exceptions
1) Try
2) Except
3) Else
4) Finally
5) Raise

 Syntax for Handling the Exceptions


 Programming Examples
 Development of Programmer-defined Exceptions
 Programming Examples
 ATM Case study with Exceptions
Exception Handling in Python

Exception Handling in Python

The purpose of Exception handling is that “To build ROBUST (strong)


Applications”.
To develop any real time application, we need to choose a programming
language during the Project/Application Development, we develop a
code, compile the code and execute the code. During this process, we
get some errors and they are classified into 3 types. They are:
a) Compile Time Error
b) Logical Error
c) Runtime Error

a) Compile Time Errors: These errors occurs during Compilation Process


( .py----> .pyc).
These errors occurs due to Syntaxes are not followed.
These errors solved by Programmers during Application development Time.

b) Logical Errors: These errors occurs during Execution or run time.


These errors occurs due to wrong representation of logic.
These error always generates wrong Result.
These errors solved by the programmer during application development
time.

c) Runtime Errors: These errors occurs during Execution or run time.


These errors occurs due to wrong or invalid input entered by the
application user or End user.

All runtime errors are by default generates technical error messages.


Which are understandable by the programmer but not by End Users.
Industries always recommends to generate User-Friendly error
messages by using Exception Handling.
Exception Handling in Python

Building Points to Exception Handling

1) When the application user enters invalid input then we get Runtime Errors.
(Invalid Input -----> Runtime Error)

2) Runtime errors always gives Technical error messages.


(Invalid Input ----> Runtime Error ----> Technical Error Message)

3) Definition of Exception: Every Runtime error is called Exception.


(Invalid Input ----> Runtime Error ----> Exception)
Hence Every Invalid Input gives Exception.

4) All Exceptions by-default generates Technical Error Messages which are


understandable by Programmer but not by End users. Industries ale=ways
recommends to generates User-friendly error messages by using
Exception Handling.

5) Definition of Exception Handling: The process of converting the Technical


error messages into User friendly error messages is called Exception
Handling.

6) When the exception occurs in python program, internally 3 steps takes


places, they are:
a) Program execution abnormally terminated.
b) PVM comes out from Program Flow.
c) By default PVM generates Technical Error Messages

7) In order to perform step (a), step (b) & step (c), internally PVM
creates an object of appropriate exception class.

8) When an exception occurs then PVM automatically creates an object


of appropriate exception class.

9) Hanse Every Exception is treated as an object of appropriate


exception class.
Exception Handling in Python

Types of Exception in Python

In Python Programming, we have two types of Exception. They are:


1. Pre-defined of built-in Exceptions
2. Programmer or user or custom defined Exception

1. Pre-defined or built-in Exceptions: These exception developed by


Python Language Developers and available in Python software
(Library) and used by all python programmer for dealing with
Universal Problems.

Some of the Universal Problems are:


1) Division by zero (ZeroDivisionError)
2) Invalid Number Format Conversion ( ValueError)
3) Invalid Type of Operation (TypeError)
4) Invalid Indices (IndexError)
5) Importing of wrong module name (ModuleNotFoundError)
6) Wrong attributes as w.r.t objectname(AttributeError)
…………..etc.

2. Programmer or user or Custom defined Exception: These exception


developed by the Python Language Programmers and available in the
Python Project and used by all other python programmers for dealing
with common problems.

Some of the common problems are:


1) Attempting to enter Invalid PIN in ATM applications.
2) Attempting to enter wrong User name and Password.
3) Attempting to withdraw more amount than existing
balance in account.
………… etc.
Exception Handling in Python

Handling the Exception in Python

Handling the exception in Python is nothing but converting Technical


Error messages into User-friendly Error messages.

To convert Technical error messages into User friendly Error messages,


in exception handling, we have 5 keywords, they are:

1. try 2. except 3. else 4. finally 5. raise

Syntax for handling the exception:

try:
block of statements
generating exception
except <exception-class-name-1>
black of statements
generating User-friendly Error Messages
except <exception-class-name-2>:
black of statements
generating User-friendly Error Messages
----------------------------------------------------------
----------------------------------------------------------
except <exception-class-name-n>:
black of statements
generating User-friendly Error Messages
else:
Block of statements recommended
Generate result
Finally:
Block of statements executes compulsorily
Irrespective exception occurs or not.
Exception Handling in Python
Explanation:

1. try block:
It is the block in which we write block of statements to generates
exceptions. In other words, which are all the statements generating
exception those statements must be written within the try block and
hence try block is called exception monitoring block.

When an exception occurs in try block, PVM comes out of try block and
execute appropriate except block.

Once PVM execute except block then PVM never goes to try block for
executing the rest of the statements.

Every try block must be immediately followed except block otherwise


we get SyntaxError.

Every try block must contain at least one except block and
recommended to write multiple except block for generating multiple
user-friendly error messages.

2. except block:

It is the block in where we write block of statements which generates


User-friendly Error Messages. In other words except block will supress
the Technical Error Messages into User-Friendly Error Messages. Hence
except block also called as exception processing block.

Note: Handling Exception = try block + except block.

Except block will execute when these is an exception in try block,

Even we write multiple except blocks, PVM will execute only one
appropriate except block depends on type of exception.
Exception Handling in Python
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 of statement in which we recommended to Display the


Result.

This block will execute when there is no exception in the try block.
Writing else block is optional.

The place of writing else block is that 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 which are


relinquishing (close, release, give-up or clean-up) the resources (files or
databases)

Finally block will execute compulsory.

Writing finally block is optional.

The place of finally block is after else block (if we write)

Examples:
#This Program accept two numerical values from KBD and find
div.
#Div1.py
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
#convert s1 and s2 into int type
a=int(s1) #------------------------------------------------X
b=int(s2) #------------------------------------------------X
c=a/b #-----------------------------------------------X
print("Div=",c)
==========================================================
Exception Handling in Python
#This Program accept two numerical values from KBD and find
div.
#Div2.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
#convert s1 and s2 into int type
a=int(s1) #-----------------------------------------X
b=int(s2) #-----------------------------------------X
c=a/b #----------------------------------------X
except ZeroDivisionError:
print("\nDON'T ENTER ZERO FOR DEN....")
except ValueError:
print("\nDon't enter strs , symbols and alpha-numerics")
else:
print("------------------------------------")
print("Val of a=",a)
print("Val of b=",b)
print("Div=",c)
print("------------------------------------")
finally:
print("\nI am from finally block")
==========================================================
Exception Handling in Python

Development of Programmer or User or Custom defined Exception

These exception developed by Python Language Programmers and


available in Python Project and used by all other python programmers
for dealing with common problems.

Some of the common problems are:


1) Attempting to enter Invalid PIN in ATM application.
2) Attempting to enter wrong user name and password.
3) Attempting to withdraw more amount than existing bal in acc.
--------- etc.

When an exception occurs, PVM create an object and to create an


object, PVM need an exception class. If the exception class present in
Python Library then that exception class is called Pre-defined exception
class. If the exception class not present in the Library than exception
class must be developed by programmer and it is known as Programmer
or User or Custom defined exception class.

Exception handling hierarchy chart


Exception Handling in Python

Steps for developing Programmer defined exception:

1. Choose the Programmer-defined class name.


2. The programmer- defined class must inherit from ‘Exception’ or
‘BaseException’ for obtaining exception handling properties
(Abnormal Termination, Generating Technical error message…etc)
3. Save the above development on the field name with an extention .py
(filename.py).

While we are developing any programmer-defined exception based


applications, Programmer must ensure 3 phases. They are:

1) Development of Programmer-defined Exception Class.


2) Development of Common Function and HITTING
programmer-defined exception.
3) The Program that handle the exception if exception occurs.

1) Development of Programmer-defined Exception Class.

Examples:
#kvr.py ------- file name and acts as module name
Class KvrDivisionError(Exception): pass

2) Development of Common Function and HITTING programmer-


defined exception.
Div.py --------file name and acts as module name
From kvr import KvrDivisionError
def division(a,b):
If(b=0):
Raise KvrDivisionError #hitting of generating exception
else:
return(a/b)
==========================================================
Exception Handling in Python
3) The program that handle the exception if exception occurs.

#divdemo.py
from Div import division
from kvr import KvrDivisionError
try:
a=int(input(“Enter First Value:”))
b=int(input(“Enter second Value:”))
res= division(a/b)
except KvrDivisionError:
print(“\nDon’t Enter Zero as Denominator”)
except ValueError:
print(“\nDon’t Enter strs, symbols and alpha-numerics”)
else:
print(“Div=”,res)
finally:
print(“I am from finally block”)

raise key word

raise keyword is used for hitting/raising/generating the exception


provided some condition must be satisfied.

Raised keyword always used inside of function definition only.

PVM uses raise keyword implicitly for hitting pre-defined exception


whereas programmer makes the PVM to use raise keyword explicitly for
hitting or generating programmer-defined exception.
Exception Handling in Python
Syntax: if (test cond):
raise < exception-class-name>

Syntax: def functionname (list of formal parms if any):


-----------------------------------------------------
-----------------------------------------------------
if (test cond):
Raise <exception-class-name>
-----------------------------------------------------
Examples:

from kvr import KvrDivisionError


def division(a,b):
if (b=0):
Raise KvrDivisionError
else:
return(a/b)
=========================================================
Files in Python
Index

 Purpose of Files.
 Types of Applications in the context of Files.
 Definition of File.
 Types of operations on Files:
a) Write Operation b) Read Operation
 Types of Files:
a) Text Files b) Binary Files
 Files Opening Modes:
1) r 2) w 3) a 4) r+ 5) w+ 6) a+ 7) x
 Syntax for Opening Files:
a) by using open()
b) by using ‘with open() as’
 Programming examples

 Pickling (object serialization) and Un-pickling (object


deserialization) Concept.
 Implementation of Pickling and un-pickling.
 Pickle module
 Programming Examples.

 os module
 Working with CSV files.
 csv module:
1) csv reader
2) csv writer
3) csv dict reader
4) csv dict writer
 Programming examples
 CSV in Pandas
 JSON FILES in Python
Files in Python
The purpose of Files in any programming language is that “To maintain
Data Persistency”.
The Process of storing the data permanently is called Data Persistency.

In the context of, we can develop two types of Applications, they are:
1) Non-Persistent Application
2) Persistent Application

In Non-Persistent Application development, we read the data from


keyboard, store in the main memory (RAM) in the form of Objects,
processed and whole result displayed on the Monitor.

Examples:
All our previous examples comes under Non-persistent Application.

We know that the data stored in the main memory is Temporary.


In persistent application development, we read the data from keyboard,
store in the main memory (RAM) in the form of Objects, Processed and
whose result stored permanently.
In Industries, we have two ways to store the data permanently,
they are:
1) By using files
2) By using DataBase Softwares( Oracle, MySQL, MongoDB, DB2,
PostgreySQL, SQL Server, SQLITE3…etc)

Data persistency by Files of Python

Def. of Files: A file is a collection of Records. Files Resides in Secondary


Memory. Technically, File name is a named location in secondary
memory. All the objects data of main memory becomes records in file of
secondary memory and records of secondary memory becomes the
object in main memory.

Def. of Stream: The Flow of data between object(s) of main memory


and Files of secondary memory is called Stream.
Files in Python

Operations on Files

On Files, we can perform 2 types of operations, they are:


1) Write Operation
2) Read Operation

1) Write Operation: The purpose of write operation is that “To transfer


Temporary data from main memory into files of secondary memory”.

Steps:
1. Choose the file name.
2. Open the file name in write mode.
3. Perform cycle of write operations.

While we are performing write operations, we get some exceptions,


they are:
a) FileExistError
b) IOError

2) Read Operation: The purpose of read operation is that “To read data
from file of secondary memory into object of main memory”.

Steps:
1. Chose the file name.
2. Open the file name in read mode.
3. Perform cycle of read operations.

While we are performing read operation, we get some exception. They


are:
a) FileNotFoundError
b) EOFError
Files in Python

Types of Files in Python

In Python Programming, we have two types of Files, they are:


1) Text File
2) Binary File

1) Text File: A text file is one which contains Alphabets, Digits and
Special Symbols.

In Python Programming a text file is denoted by a letter ‘t’.


By default a file is considered as text file.

Examples: .py , .java , .c , .cpp , .txt , .doc , .xlsx…etc.

2) Binary file: A binary file always contains data in the form of binary
data format.

In python programming, a binary file is denoted by a letter ‘b’.


Examples: images ( .jpg , jpeg , .png , .gif), audio and videos file , PDF
formats.
Files in Python

File opening Modes

The purpose of file opening modes is that “In which mode the files are
opened”. To perform any type of operation on the files, the files must
be opened in appropriate mode.

In Python Programming, we have 7 file opening modes. They are:

1. r mode: This mode is use for opening the file name in read mode . it
is one of the default file mode. If we open the file name in ‘r’ mode
and if the file does not exist then we get ‘FileNotFoundError’.

2. w mode: This mode is used to creating the file and opening the file in
write mode always. When we open NEW FILE in ‘w’ mode then new
file will be opened in write mode and data written from beginning of
the file always. When we open EXISTING FILE in ‘w’ mode then
existing data of the existing file OVERLAPPED with NEW DATA.

3. a mode: This mode is used to creating the file and opening the file in
write mode always. When we open NEW FILE in ‘a’ mode then new
file will be opened in write mode and data written from beginning of
the file always. When we open EXISTING FILE in ‘a’ mode the existing
file APPENEDED with NEW DATA.

4. r+ mode: This mode is also used for opening the file in ‘r’ mode and
perform read operation. After reading the data from file and latter
we can also perform write operation. When we open the file in ‘r+’
mode and if the file doen not exist then we get ‘FileNotFoundError’.
Files in Python
5. w+ mode: This mode is used for opening the file in write mode and
perform write operation always and latter additionally we can
perform read operation also. When we open NEW FILE in ‘w+’ mode
the new file will be opened in write mode and data written from
beginning of the file always and lattes we can read the data also.
When we open EXISTING FILE in ‘w+’ mode then existing data of the
existing file OVERLAPPED with NEW DATA and latter we can read the
data also.

6. a+ mode: This mode is used creating the file and opening the file in
write mode always and perform write operation First and Latter
additionally we can perform read Operation also. When we open
NEW FILE in ‘a+’ mode the new file will be opened in write mode and
data written from the beginning of the file always and later we can
perform read operation. When we open EXISTING FILE in ‘a+’ mode
then existing data of the existing file APPENDED with NEW DATA and
later we can perform read operation.

7. ‘x’ mode: This mode is used for creating the new file and opening
that file in write mode eXclusively. If we open existinf file in ‘x’ mode
then PVM generates ‘FileExistError’.

Pictorial Explanation of Object and Record:

-----------------------------------------------------------------------------------------------
Files in Python
Pictorial Explanation of read and write operation:

-----------------------------------------------------------------------------------------------
Pictorial Explanation of Persistent and non-persistent Application:
Files in Python

Opening the files in Python

In Python Programming, we have two approatches to open the fine.


They are:
1) By using open()
2) By using ‘with open() as’

1) By using open():

Syntax: varname = open (“FileName”, “File Mode”)

Explanation:
‘varname’ is an object pointing to the file and it is called File Pointer.
-Here ‘File Name’ represents Name of the File.
-Here ‘File Mode’ represents any File Opening mode ( r, w, a, r+, w+, a+,x)

Open() is pre-define function, which is used for opening the file in


specified file mode.
-Hence, when we open any file name by using open(), it is mandatory to
closed the file by using close(). In otherwords open() does not provide
‘auto-closabiliy Files’.

2) By using ‘with open() as’ :


Syntax: with open(“File Name” , “File Mode” ) as Varname:
-----------------------------------------------------------
-----------------------------------------------------------
Block of statement performs File Operations
-----------------------------------------------------------
-----------------------------------------------------------
------------------------------------------------------------------
---Block of statements-out of with Indentation----
------------------------------------------------------------------
Files in Python
Explanation:
-Here ‘with’ ‘as’ are the keywords.
-‘varname’ is an object pointing to the file and it is called file pointer.
-Here ‘File Name’ represents name of the file.
-Here ‘File Mode’ represents any file opening mode(r, w, a, r+, w+, a+, x)
-open() is pre-defined function, which is uses for opening the file in
specificed file mode.

-Hense the advantage of ‘with open() as’ approatch is that “auto-


closebility of file. In otherwords, as long as PVM executes indentation
Block of statements of ‘with open() as’ approach, file is active mode or
under open and once PVM comes out of ‘with open() as then PVM
closes the file “automatically”.
Files in Python

#Program for opening a file by using open()


#FileOpenEx1.py
try:
fp=open("stud.data")
except FileNotFoundError:
print("File Name does not exist")
else:
print("="*50)
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in Read
Mode:")
print("File Name=", fp.name)
print("File Mode=",fp.mode)
print("Is file readable=", fp.readable())
print("Is file writable=", fp.writable())
print("Is file closed=",fp.closed) # False
print("="*50)
finally:
print("\ni am from finally block")
fp.close() # we are closing the file manually
print("Is file closed=",fp.closed) # True
==========================================================
Files in Python
#Program for opening a file by using open()
#FileOpenEx2.py
try:
fp=open("stud.data","w")
except:
print("Some exception occurs")
else:
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in Write
Mode:")
print("="*50)
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in Read
Mode:")
print("File Name=", fp.name)
print("File Mode=",fp.mode)
print("Is file readable=", fp.readable())
print("Is file writable=", fp.writable())
print("Is file closed=",fp.closed) # False
print("="*50)
finally:
print("\ni am from finally block")
fp.close() # we are closing the file manually
print("Is file closed=",fp.closed) # True
=========================================================
#Program for opening a file by using open()
#FileOpenEx3.py
try:
fp=open("stud.data","a+")
except:
print("Some exception occurs")
else:
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in Write
Mode:")
print("="*50)
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in Read
Mode:")
print("File Name=", fp.name)
print("File Mode=",fp.mode)
print("Is file readable=", fp.readable())
print("Is file writable=", fp.writable())
print("Is file closed=",fp.closed) # False
print("="*50)
finally:
print("\ni am from finally block")
fp.close() # we are closing the file manually
print("Is file closed=",fp.closed) # True
==========================================================
Files in Python
#Program for opening a file by using open()
#FileOpenEx4.py
try:
fp=open("kvr1.data","x")
except FileExistsError:
print("File Name already exist")
else:
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in X Mode:")
print("="*50)
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in X
Mode:")
print("File Name=", fp.name)
print("File Mode=",fp.mode)
print("Is file readable=", fp.readable())
print("Is file writable=", fp.writable())
print("Is file closed=",fp.closed) # False
print("="*50)
finally:
print("\ni am from finally block")
fp.close() # we are closing the file manually
print("Is file closed=",fp.closed) # True
==========================================================
#Program for opening a file by using "with open() as"
#FleOpenEx5.py
with open("emp.data","w") as fp:
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in W Mode:")
print("="*50)
print("Type of fp=",type(fp)) # <class, 'TextIOWrapper'>
print("File Created and opened Successfully in W
Mode:")
print("File Name=", fp.name)
print("File Mode=",fp.mode)
print("Is file readable=", fp.readable())
print("Is file writable=", fp.writable())
print("Liner-12-->Is file closed=",fp.closed) # False
print("="*50)
print("\nI am from out of 'with open() as indentation block ")
print("Line-15-->Is file closed=",fp.closed) # True
==========================================================
Files in Python
#Program for opening a file by using "with open() as"
#FleOpenEx6.py
try:
with open("emp.data") as fp:
print("Type of fp=",type(fp)) # <class,
'TextIOWrapper'>
print("File Created and opened Successfully in W
Mode:")
print("="*50)
print("Type of fp=",type(fp)) # <class,
'TextIOWrapper'>
print("File Created and opened Successfully in W
Mode:")
print("File Name=", fp.name)
print("File Mode=",fp.mode)
print("Is file readable=", fp.readable())
print("Is file writable=", fp.writable())
print("Liner-12-->Is file closed=",fp.closed) #
False
print("="*50)
except FileNotFoundError:
print("File does not exist")
finally:
print("\ni am from finally block")
print("Is file closed=",fp.closed) # True
==============================================

Writing the data to the file

To write the data to the file, we have one pre-defined function in file
pointer object, They are:
1. write()

1. write(): This function is used for writing any type of data to file in the
form od str. If we have non-str data then convert into str type and
then write in to the file.
Syntax: filepointer.write(str data)
Files in Python
Examples:

#write a python program which will write different pepole


address to the file
#FileWriteEx1.py
with open("addr1.data","a") as fp:
fp.write("Travis Oliphant\n")
fp.write("A-B-3, Park End Side\n")
fp.write("Numpy Software Foundation\n")
fp.write("North America\n")
print("Data Written to the file--verify")
========================================================

Reading the data from the file

To read the data from the file, we have one pre-defined functions
present in file pointer object. They are:
1) read()
1) read() : This function is used for reading entire content of the file in
the form of str.
Syntax: varname = filepointer.read()
Here varname is an object of type <class, str>
------------------------------------------------------------------------------------------
Example: FileReadEx1.py

--------------------------------------------------------------
#write a python program which will read entire data from the
file----read()
#FileReadEx1.py
fname=input("Enter File Name:")
try:
with open(fname) as fp:
filedata=fp.read()
print("-"*40)
print(filedata)
print("-"*40)
except FileNotFoundError:
print("file does not exists")
------------------------------------------------------------------------------------------
Files in Python

Packing or object serialization and Un-packing or De-serialization

Pickling: Let us assume there exist an object which contains multiple


values, To save or write object data of main memory into the file of
secondary memory by using write() they transfer the value in the
form of value by value and it is one of the time consuming
process(multiple write operations).
To overcome this time consuming process, we must use the
concept of Pickling.

The advantage of pickling concept is that with single write operation, we


can save or write entire object data of main memory into the file of
secondary memory.

Definition of Pickling: The process of saving or transferring entire object


content of main memory into the file of secondary memory by
performing single write operation is called Pickling.
Pickling concept participate in write operation.

Steps for Implimenting Pickling Concept:


- Import pickling module, here pickle is one of the pre-defined module.
- Choose the file name and open it into write mode.
- Create an object with collection of values (Iterable object).
- use the dump() of pickle module. dump() save the content of any
object into the file with single write operation.

Syntax: pickle.dump(object, filepointer)

Note: Pickling concept always takes the file in binary format.


Files in Python

Un-pickling: Let us assume there exist a record with multiple values in a


file of secondary memory. To read or transfer the entire record content
from file of secondary memory, if we use read() then they read record
values in the form of value by value and it is one of the time consuming
process (multiple read operation)
To overcome this time consuming process, we must use the
concept of Un-pickling.

The advantage of Un-pickling is that with single read operation, we can


read entire record content from the file of secondary memory into the
object of main memory.

Definition of Un-pickling: The process of reading or transferring the


entire record content from file of secondary memory into the object of
main memory by performing single read operation is called Un-
pickling.
Un-pickling concept participates in read operation.

Steps for implementing Un-pickling con-


cept.
- import pickling module.
- Choose the file name and open it into read mode.
- Use the load() of pickle module. load is used for transferring or loading
the entire record content from file of secondary memory into object of
main memory.

Syntax: objname = pickle.load(filepointer)

Note: Un-pickling concept always takes the file in binary format.


Files in Python
Examples:
==========================================================
#write a python program which will read employee number,
employee name and employees data. save the employee data into
the file of secondary memory ----Program--(A)
#emppickex1.py
import pickle
with open("empinfo.data","ab") as fp:
noe=int(input("Enter how many employees data u have:"))
if(noe<=0):
print("{} is invalid Input".format(noe))
else:
for i in range(1, noe+1):
print("-"*50)
print("Enter {} Employee
Values:".format(i))
print("-"*50)
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
#create an empty list
lst=list()
#append the employee values to list object
lst.append(eno)
lst.append(ename)
lst.append(sal)
#save or dump list object data to the file
pickle.dump(lst,fp)
print("-"*50)
print("{} Employee Record Saved in a
file:".format(i))
==============================================
#write a python program which wiil read emp records from the
file----Program-B)
#empunpickex1.py
import pickle
try:
with open("empinfo.data","rb") as fp:
print("-"*50)
print("Empno\tName\tSalary")
print("-"*50)
while(True):
try:
record=pickle.load(fp)
for val in record:
print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File does not exist")
Files in Python
==============================================
#Write a python program which will accept student details such as
stdno stdname and marks and store the record in a file
#StudPick.py
import pickle,sys
with open("studinfo.data","ab") as fp:
while(True):
try:
print("-"*50)
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Studemnt Marks:"))
lst=list()
lst.append(sno)
lst.append(sname)
lst.append(marks)
pickle.dump(lst,fp)
print("\nStudent Data Saved in a File:")
print("-"*50)
while(True):
ch=input("Do want to insert another
student Data(yes/no):")
if(ch.lower()=="no"):
print("Thx for using this
program")
sys.exit()
if(ch.lower()=="yes") and
(ch.isalpha() ):
break
if(ch.isalnum()!="yes" or
ch.isdigit() or ch.space()) :
print("Plz learn
typing")

except ValueError:
print("Don't enter strs, symbols and alpha-
numerics for stno and marks")
==========================================================
Files in Python
#write a python program which wiil read student records from
the file----Program-B)
#studunpickex.py
import pickle
try:
with open("studinfo.data","rb") as fp:
print("-"*50)
print("Stno\tName\tMarks")
print("-"*50)
while(True):
try:
record=pickle.load(fp)
for val in record:

print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File does not exist")
==========================================================

OS Module

OS is one of the per-defined module. The purpose of os module is that


“To perform some OS (operating System) based operation.

Some of the OS based operations are:


1) Getting current working folder ---- getcwd()
2) Creating a folder ---- mkdir()
3) Creating folders Hierarchy ---- makedirs()
4) Remove a folder ---- rmdir()
5) Remove folders Hierarchy ---- removedirs()
6) List the files of folder ----- listdir()
7) Rename a folder ----- rename()

1) Getting current working folder --- getcwd(): To get the current


working folder, we use getcwd() of os module.

Syntax: varname = os.getcwd()


Files in Python
Example:
#program for getting current working folder ---getcwd()
#getcwdex.py
import os
cwdname=os.getcwd()
print("current working folder=",cwdname)
==========================================================
2) Creating a folder—mkdir(): To create a folder, we use mkdir() os
module.

Syntax: os.mkdir(“Folder Name”)

If the folder name already exist and if we attempt to create again then
we get FileExistsError as an exception. By using mkdir(), we can create
one folder at a time but not possible to create folders hierarchy (if we
do so we get FileNotFoundError)

Exapmles:
#Program for creating a folder
#mkdirex.py
import os
try:
os.mkdir("PYTHON")
print("Folder created successfully-verify")
except FileExistsError:
print("Folder already exist--try with another one")
except FileNotFoundError:
print("with mkdir(), we can't create Folders Hierarchy")
==========================================================
3) Creating folder Hierarchy--- makedirs(): To create folder hierarchy,
we use makedirs() os module.

Syntax: os.makedirs(“Folder Hierarchy”)

Here folder hierarchy respresents root folder, sub folder, sub-sub


folder...etc. If the folders hierarchy already exist and if we attempt to
create again then we get FileExistsError as an exception.
Files in Python
Examples:
#Program for Creating Folders Hierarchy
#makedirsex.py
import os
try:
os.makedirs("C:\INDIA\BANG\AMPT\INDIA")
print("Folders Hirerarchy created..")
except FileExistsError:
print("Folders Hirerarchy already exist--try with some
other")
==========================================================
4) Remove a folder---rmdir(): To remove a folder, we use rmdir() os
module.

Syntax: os.rmdir(“Folder Name”)

- If folder name does not exists then we get FileNotFoundError.


- rmdirs() can remove only one folder at a time but not able to remove
folder hierarchy at a time.
- rmdir() generates an exception called OSError when the folder
contains some sub folder or file names.

Examples:
#program for removing a folder
#rmdirex.py
import os
try:
os.rmdir("C:\PYTHON")
print("Folder Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folder is not empty-can't remove")
==========================================================
5) Remove Folders hierarchy --- removedir(): To remove folders
hierarchy represent root folder, sub-folder, sub-sub folder etc.

Syntax: os.remove(“Folder hierarchy”)

- Here folder hierarchy represents root folder, sub folder, sub-sub


folder..etc.
- If folder Hierarchy does not exists then we get FileNotFoundError.
Files in Python
- removedirs() generates an exception called OSError when the folders
hieraechy contains some sub-folder or file names.

Examples:
#program for removing a folders hierarchy
#removedirsex.py
import os
try:
os.removedirs("C:\INDIA\TS\AMPT\python")
print("Folders Hiearchy Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folders hierarhcy is not empty-can't remove")
==========================================================
6) List the files of folder--- listdir(): To list the files in a folder, we use
listdir().

Syntax: listobj = os.listdir(“Folder Name”)

If folder name does not exists then we get FileNotFoundError.

Examples:
#Program for listing the files in a folder
#listdirex.py
import os
try:
files=os.listdir("E:\PYTHON\FILES")
print("Number of files =",len(files))
for file in files:
print(file)
except FileNotFoundError:
print("File does not exists")
=========================================================
7) Rename a folder---rename(): To rename a folder, we use rename().

Syntax: os.rename(“Old Folder Name”, “New Folder Name”)

If old folder does not exist then we get FileNotFoundError.


Files in Python

Examples:
#Program for renaming a folder
#renamefolderex.py
import os
try:
os.rename("E:\PYTHON\FILESPROG","E:\PYTHON\FILESUPDATE”)

print("Folder renamed")
except FileNotFoundError:
print("Folder does not exists")
=========================================================
#program for removing a folder
#rmdirex.py
import os
try:
os.rmdir("C:\PYTHON")
print("Folder Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folder is not empty-can't remove")
==========================================================

Working with csv files in Python

csv stands for Comma Separeted Values.

A csv file is one of the simple file format used to store tabular data,
such as a spreadsheet or data (numbers and text) in plain text. Each line
of the csv file is a data record. Each record consists of one or more
fields, separated by commas.

Python provides an in-built module called csv to work with csv files.

There are two classes provided in this module for writing the data to csv
file, they are:

1) By using csv.writer class object.


2) By using csv.DictWriter class object.
Files in Python
1) By using csv.writer class object: The csv.writer class object is used to
insert data to the csv files.

To create an object of csv.writer class object, we use writer() and


present in csv module. “csv.writer” class object provides two functions
for writing to csv files file, they are:

a) writerow() b) writerows()

a) writerow(): This method writes a single row at a time. Field row can
be written using this method.
Syntax: csvwriteobj.writerow(fields rows/data rows)

b) writerows(): This method is used to write multiple rows at a time.


This can be used to writre rows list.
Syntax: csvwriterobject.writerows(data rows)
Here data rows can be list tuple set, frozenset only.

2) By using csv.DictWriter class object: The “csv.DictWriter” class object


is used to insert dict data to the csv flie.

To create an object of “csv.DictWriter” class object, we use


DictWriter() and present in csv module. “csv.DictWriter” class object
provides two Funtions for writing to csv.
a) writeheader() b) writerows()

a) writeheader(): writeheader() method is simply writes the first row of


your csv file using the pre-defined fieldnames.
Syntax: DictWriteobj.eriteheader()

b) writerows(): writerows() method simply writes all the values of


(Keys,Value) from dict object in the form of separate rows.

Note: it writes only the values(not keys).


Syntax: DictWriteObj.writerows(dictobject)
Files in Python

Reading the data from csv file

There are various ways to read a csv file that uses either the csv module
of the pandas library.

The csv module provides classes for reading information from csv file.
1) csv.reader 2) csv.DictReader

1) csv.reader(): This function is used for creating an object of csv.reader


class and help us to read the data records from csv file.
Syntax: csvreaderobj = csv.reader(filepointer)

2) csv.DictReader(): This function is used for creating an object of


“csv.DictReader” class and it help us to read the data from csv file
where it contains dict data(Key,Values).
Syntax: csvdictreaderobj = csv.DictReader(filepointer)

Examples:

# Python program to demonstrate writing to CSV File---


csv.writer--->writer()
#csvwriteex1.py
import csv
# field names
recfields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'CSE', '2', '9.0'],
['Sanchit', 'CSE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1'] ]

# name of csv file


csvfilename = "univ1.csv"
# writing data to csv file
with open(csvfilename, 'w') as fp:
Files in Python
# creating a csv writer object
csvwriter = csv.writer(fp)
# writing the fields
csvwriter.writerow(recfields)
# writing the data rows
csvwriter.writerows(rows)
print("\nCSV file Created and Verify")
==========================================================
# Python program to demonstrate to write single record
# writing single record to CSV file
#csvwriteex2.py
import csv
# data record of csv file
row = ['KVR', 'CSE', '2', '9.0']
# name of csv file
filename = "univ1.csv"
# writing to csv file
with open(filename, 'a') as fp:
# creating a csv writer object
cw = csv.writer(fp)
# writing the data row to the csv file
cw.writerow(row)
print("\nSingle Record Written to the CSV File:")
=======================================================
#Program for reading the data from CSV file by using csv
module----student.csv
#csvreaderex1.py
import csv
try:
with open("student.csv","r") as fp:
cr=csv.reader(fp)
for record in cr:
for val in record:
print("{}".format(val),end="\t")
print()
except FileNotFoundError:
print("File does not exist")
-----------------------------------------------------------------------------------------------
sno sname marks cname
10 RS 33.33 PSF
20 DR 22.22 BU
30 TR 11.11 NU
40 DT 44.44 OU
50 SR 33.22 JNTU
60 TE 66.44 HCU
70 UT 22.55 AU

=========================================================
Files in Python
#Program for reading the data from CSV file by using csv
module----student.csv
#csvreaderex2.py
import csv
try:
with open("univ1.csv","r") as fp:
cr=csv.reader(fp)
for record in cr:
for val in record:
print("{}".format(val),end="\t")
print()
except FileNotFoundError:
print("File does not exist")
-----------------------------------------------------------------------------------------------
Name Branch Year CGPA

Nikhil CSE 2 9

Sanchit CSE 2 9.1

Aditya IT 2 9.3

Sagar SE 1 9.5

Prateek MCE 3 7.8

Sahil EP 2 9.1

KVR CSE 2 9
=========================================================
#Program for reading the data from CSV file by using csv
module----student.csv
#csvreaderex3.py
import csv
try:
with open("univ2.csv","r") as fp:
dcr=csv.DictReader(fp)
print("-"*40)
for record in dcr:
for k,v in record.items():
print("\t{}-->{}".format(k,v))
print("-"*40)

except FileNotFoundError:
print("File does not exist")
-----------------------------------------------------------------------------------------------
Files in Python

name branch year cgpa

Nikhil COE 2 9

Sanchit COE 2 9.1

Aditya IT 2 9.3

Sagar SE 1 9.5

Prateek MCE 3 7.8

Sahil EP 2 9.1
=========================================================
#Program for reading the data from CSV file without using csv
module----student.csv
#noncsvex.py
try:
with open("student.csv","r") as fp:
csvfiledata=fp.read()
print(csvfiledata)
except FileNotFoundError:
print("File does not exist")
==========================================================
Files in Python

# importing the csv module


#csvdictwriteex2.py
import csv

# my data rows as dictionary objects


mydict =[ {'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil',
'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name':
'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya',
'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar',
'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name':
'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil',
'year': '2'} ]

# field names
csvfields = ['name', 'branch', 'year', 'cgpa']

# name of csv file


filename = "univ2.csv"

# writing to csv file


with open(filename, 'w') as fp:
# creating a csv dict writer object
dictwriter = csv.DictWriter(fp, fieldnames = csvfields)
# writing headers (field names)
dictwriter.writeheader()
# writing data rows
dictwriter.writerows(mydict)
print("\nDict Data Written to the csv file--verify")
===========================X==============================
Files in Python

Python DataBase Communication (PDBC)

Even we achived the Data Persistency by using Files, Files has the following
Limitations:
1. Files of any language does not contain security because Files are
unable to provide security in the form of User Name and
Password.
2. Files are unable to store large amount of data.
3. File are different from one OS to another OS (Files are OS
dependent)
4. Querying and Processing the data from Files is very Complex
because file data is organised w.r.t Indices and identifying the
indices is very complex.
5. Files does not contain Column Name (Except CSV Files)

To Overcome the Limitaions of files and to achive the Data Persistency, we


must use the concept of any RDBMS database Software(Oracle, MySQL,
MongoDB, DB2, SQL Server, PostgreySQL, SQLITE3……etc).

1. All RDBMS DataBase softwares provides Security because RDBMS


database software considers User Name and Password.
2. All RDBMS DataBase softwares stores large amount of data.
3. All RDBMS DataBase softwares are remains same on every types
of OSes (OS Indipendent).
4. Querying and Processing the data from All RDBMS DataBase
softwares is very simple because data of all RDBMS DataBase
softwares organised in the form of Tables with Column Names.
5. The Data Present in any RDBMS DataBase softwares organised in
the form of Tables with Column Names.
Files in Python

If Python Program wants to communicate with any RDBMS DB Softwares


then we must use a pre-defined module and such as pre-defined module
does not exists in Python software.

Some thirs Party software vendors (Ex: “Anthony Tuininga”) developed a


module for Python Programmer to communicate with RDBMS DB softwares
and placed in github and Third Party software modules must be installed.

To install any third-party softwares modules in python, we must use a tool


called pip and it is present in
C:\Users\ritik\AppData\Local\Programs\Python\Python310\Scripts folder.

Syntax: pip install module name (at any windows command prompt)

If Python Program want to communicate with Oracle DB, then we must


install cx_Oracle Module.

Examples: pip install cx_Oracle

==============================X==============================
Files in Python

If Python Program want to communicate with MySQL DB, then we must


install mysql-connector or mysql-connector-python Module.

Example: pip install mysql-connector


Example: pip install mysql-connector-python
==============================X==============================
Files in Python

Communication between Python and Oracle DB

In order to write python program to communicate with Oracle DB, we


must follow 6 steps:
1. Import cx_Oracle module
2. Python Program must get the connection from Oracle DB.
3. Create an object Cursor.
4. Python Program must prepare the query and execute the
query in Oracle DB.
5. Python program prosecco the result of the query.
6. Python program closes the connection.

Explanation:
1. Import cx_Oracle module: if a python program want to perform any
DB operation (insert, delete, update, read records…etc) then we must
import a pre-defined third-party module “cx_Oracle”.

We know that a module is a collection of variables, Function Name ad


Class Name.

Example: import cx_Oracle

2. Python Program must get the connection from Oracle DB: To do any
DB operations, First python program must get the connection from
Oracle.

To get any DB Operation, we use connect() which is present in cx_Oracle


module.
Syntax: varname = cx_Oracle.connect(“Connection URL”)
- Here connection URL represents:
“Username/Password@DNS/Serviceid” (OR)
“Username/Password@IPAddress/Serviceid”
Files in Python
- Here varname is an object of <class, cx_Oracle.Connection>
- Here “Username/Password” represents User name and Password of
Oracle DB. Ex: Username = system and Password = manager.
- Here DNS(Domain Naming Service) represents name of the Machine
where DB software installed. The default DNS is “localhost”.
- Here IPaddress (Internet Protocal Address) represents an address of
Physical Machine is 127.0.0.1 (Loop back address).
- Here “servicedid” represents on which name Oracle data base, we
use the following syntax at SQL Environment.

SQL> SELECT * FROM GLOBAL_NAME;


GLOBAL_NAME
--------------------
ORCL <-------------------------- service ID.

When we use /write Invalid Connection URL then we get


cx_Oracle.DatabaseError as an exception and must handle.

3. Create an object of Cursor: The purpose of creating an object of


cursor is that “To carry the Query fron Python program, handover to
DB and obtain Result from DB and gives to Python Program”.

To create an object of Cursor, we use cursor() which is present in


Connection Object.

Syntax: varname = conobj.cursor()


Here varname represents an object of <class,cx_Oracle.cursor>

4. Python Program must prepare the Query and Execute the Query in
Oracle DB: A Query is a statement or Request or Question to DB
doftware for obtaining data base results.

To execute the Query in any DB software, we use execute() which is


present in cursor object.
Files in Python
Syntax: cursorobj.execute(“Query”)
Here Query is ‘str’ type and in any DB software we have different
Queries (DDL, DML, DRL).

5. Python Program Prosess the result of the Query: After Executing DML
statements, the result of DML statements is present in cursor object.

To extract the result from cursor object , we use “rowcount” attribute of


cursor object. “rowcount” attributes gives number of update/delete/insert
in the DB.

After Executing DRL statement, the result of DRL statement is present in


cursor object. To extract cursor object, we have 3 functions in cursor
object, They are:
a) fetchone()
b) fetchmany (no.of records)
c) fetchall()

Types of Querys in Data Base Softwares:

In any database, we have 3 types of Queries, they are:


1. DDL (Data Definition Language) Queries.
2. DML (Data Manipulating Language) Queries.
3. DRL (Data Retrival Language) Queries.

1. DDL (Data Definition Language) Queries: The purpose of DDL Queries


is that “To deal with Physical Level of Database software such as
creation of Tables, altering column sizes, adding new Column etc”.

In any DB software, we have 3 Types of DDL queries, they are:


a) create b) alter c) drop
Files in Python
a) create: This Query is used for creating a table in Oracle DB.

Syntax: SQL> create table <table name> (col name1 database data type,
col name2 database data type,….col name-n database data type);

SQL> create table employee(eno number(2) primary key, ename


varchar2(10) not null, sal number(6.2) not null);

b) alter: This Query is used for alter the table structure such as
modifying (modify) the column sizes and adding (add) new columns.

Syntax1: SQL> alter table <table name> modify (existing col name1
database datatype…. Existing col name-n database data type);

Syntax2: SQL> alter table <table name> add (new col name1 database
datatype….new col name-n database data type);

Example: SQL> alter table employee add (cname varchar2(10) );


SQL> alter table employee modify (cname varchar2(15) );

c) drop: This query is used for remving the table from Database
software.

Syntax: SQL> drop table <table name> ;

Example: SQL> drop table employee;


==========================================================
Examples:
--------------
#Program for getting the connection from Oracle DB
#TestOracon.py
import cx_Oracle # Step-1
try:
kvrcon=cx_Oracle.connect("scott/tiger@localhost/orcl")
# Step-2
print("Type of kvrcon=",type(kvrcon))
print("Python program got connection from Oracle")
except cx_Oracle.DatabaseError as db:
print("Prob in database:",db)
Files in Python
=========================================================
#Program for getting the connection from Oracle DB
#TestOracon1.py
import cx_Oracle # Step-1
try:
kvrcon=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
# Step-2
print("Type of kvrcon=",type(kvrcon))
print("Python program got connection from Oracle")
except cx_Oracle.DatabaseError as db:
print("Prob in database:",db)
==========================================================
#Program for creating an object cursor
#Cursorex.py
import cx_Oracle
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
print("\nPython got connection from Oracle DB")
cur=con.cursor()
print("\nType of cur =",type(cur)) # Type of cur = <class
'cx_Oracle.Cursor'>
print("Python got an object of Cursor")
================================================================
#Program for creating a table in Oracle DB
#TableCreateEx1.py
import cx_Oracle # 1
try:
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#Step-4
tq="create table employee(eno number(2) primary key,
ename varchar2(10), sal number(8,2))"
cur.execute(tq)
print("Table Created Successfully in Oracle DB:")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)
================================================
#write a python program which will remove the the table from
oracle database
#TableDropEx.py
import cx_Oracle # 1
def tabledrop():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#step-4
cur.execute("drop table student")
print("Student Table droped / removed from Oracle
DB sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)
================================================
Files in Python
#TableDropDemo.py
from TableDropEx import tabledrop as td
td()
================================================
#Program for altering the by the means of adding new columns
to Employee Table
#TableAlterAdd.py
import cx_Oracle # 1
def aftercolumnAdd():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#step-4
aqa="alter table employee add(cname varchar2(10))"
cur.execute(aqa)
print("Employee altered sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)

#main program
aftercolumnAdd()
======================================
#Program for altering the column sizes of Employee Table
#TableAlterModi.py
import cx_Oracle # 1
def aftercolumnsizes():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#step-4
aqm="alter table employee modify(eno number(3),sal
number(9,2))"
cur.execute(aqm)
print("Employee altered sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)

#main program
aftercolumnsizes()
======================================
2. DML (Data Manipulating Language) Queries:
The purpose of DML operationa is that “To manipulate the table such as
inserting the records, deliting the records and updating the records”.

In RDBMS DB software, we have 3 types of DML operations. The are:


a) insert b) delete c) update
Files in Python

When we execute any DML operation through python program,we must


use commit() for permanent change/update/modification and to roll back
we use rollback(). Commit() and rollback() are present in connection
object.

a) Insert: This query is used for inserting a record in table of DB.

Syntax: SQL> insert into <table name> values(val1 for col1,val2 for
col2… val-n for col-n)

Example: SQL> insert into student values(20, ‘DR’, 33.45, ‘c’);


SQL> insert into student values(10, ‘RS’, 23.45, ‘PYTHON’);
Commit;

b) Delete: This Query is used for deleting a record.

Syntax1: delete from<table-name>


Syntax2: delete from<table-name> where coudition list;

Example: SQL> delete from student where sno= 70;

c) Update: The Query is used for updating the record values.

Syntax1: SQL> update <table-name> set col1= val1, col2= val2… col-n =
val-n;
Syntax2: SQL> update<table-name> set col1= val1, col2= val2… col-n=
val=n; where cond list;

Examples: SQL> update student set marks= marks+marks*0.02;


Examples: SQL> update student set marks= rks+marks*0.05,crs=’Django’
where sno=90;
Files in Python
Examples:
--------------
#write a python program which will insert a record in employee
table
#EmpInsertEx1.py
import cx_Oracle
def emprecordinsert():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
#prepare Query and execute
iq="insert into employee values
(70,'SV',4.5,'HCL') "
cur.execute(iq)
con.commit()
print("{} Employee Record Inserted
Successfully".format ( cur.rowcount) )

except cx_Oracle.DatabaseError as db:


print("Problem in Database:",db)

#main program
emprecordinsert()
==========================================================
Files in Python
To get the records from cursor object, we have 3 fuctions. They are :
1) Fetchone() 2) fetchmany(no. of records) 3) fetchall()

a) fetchone(): It used for obtaining one record at a time in the form of


tuple. If no records found then we this function returns None.

b) Fetchmany(): It is used for obtaining specified number of records.

Case-1: If specified number of record == 0 then this function obtains all


records.
Case-2: If specified number of record <= Total Number of gives specified
number of records.
Case-3: If specified number of record > Total Number of Record then
this function obtains all record.
Case-4: If specified number of record < 0 then this function never gives
any records.

c) Fectchall(): It is used for obtaining all the records from cursor object.
==========================================================
Examples:
-------------
#Program selecting or reading all the records from employee
table--fetchone()
#selectex1.py
import cx_Oracle
def selectrecords():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
cur.execute("select * from employee")
print("="*40)
while(True):
record=cur.fetchone()
if(record==None):
break
else:
for val in record:

print("{}".format(val),end="\t")
print()
Files in Python
print("="*40)

except cx_Oracle.DatabaseError as db:


print("Problem in Database:",db)
#main program
selectrecords()
==========================================================
#Program selecting or reading all the records from employee
table--fetchmany()
#selectex2.py
import cx_Oracle
def selectrecords():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
cur.execute("select * from employee")
records=cur.fetchmany(3)
print("="*40)
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("="*40)
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
#main program
selectrecords()
==========================================================
#Program selecting or reading all the records from employee
table--fetchall()
#selectex3.py
import cx_Oracle
def selectrecords():
try:

con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
cur.execute("select * from employee")
records=cur.fetchall()
print("="*40)
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("="*40)
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
#main program
selectrecords()
==========================================================
Files in Python

Communication between Python and MySQL

In order to write python program to communicate with MySQL


Database, we must follow 6 steps, they are:
1. Import mysql.connector module
2. Python program must get the connection from MySQL DB.
3. Create an object Cursor.
4. Python program must Prepare the Query and Execute the
Query in MySQL DB.
5. Python Program process the result of the Query.
6. Python program closes the connection.

Explanation:
1. Import mysql.connector module: If a python program want to
perform any DB operations(insert, delete, update record, read
records…etc) then we must import a pre-defined third party module
“myqsl-connector”.
We know that a module is a collection of Variables, Function Name and
Class Name.
Example: import my-conector

2. Python program must get the connection from MySQL DB: To do any
DB Operation, First python program must get the connection from
MySQL. To get the connection from any DB, we use connect()which is
present in mysql.connector module.

Syntax: varname = mysql.connector.connect(“Connection URL”)

Here connection URL represents: host=”DNS”, user=”User Name”,


Passwd= “passward”.
Con = mysql.connector.connect(host = “UNS”, user = “User Name”,
passwd= “passwprd”)
Files in Python
Examples: con=mysql.connector.connect(host=”localhost”, user=
“root”, passwprd= “passwd”.

Here IPAddress (Internet Protocal Address) represents an address of


Physocal Machine where DB software installed. The default IP address of
Every machine is 127.0.0.1 (loop back address).
When we use/write Invalid Connection URL then we get
mysql.connector.DatabaseError as an exception and must handle.

3. Create an object of Cursor: The purpose of creating an object of


cursor is that “To carry the Query from Python Program, handover to
Database aand obtains result from DB and Gives to Python Program”.

To create an object of cursor, we use cursor() which is present in


connection object.

Syntax: varname= cobobject.cursor()

Here varname represents an object of <class, mysql.connector.cursor>

4. Python program must Prepare the Query and Excecute the query in
MySQL DB: A Query is a statement or result or Question to database
software for obtaining data base results.

To execute the query in any DB software, we use execute() which is


present in cursor object.

Syntax: cursorobj.execute(“Query”)

Here Query is of type str and in any DB software we have different


Queries (DDL, DML, DRL).
Files in Python
5. Python Program process the result of the Query: After Executing DML
statement, the result of DML statement is present in cursor object,
To extract the result from cursor object, we use “rowcount” attribute
of cursor object. “rowcount” attribute gives number of updated/
delete/inserted in the DB.

After Executing DRL statements, the result of DRL statements is present


in cursor object.

To extract the form cursor object, we have 3 functions in cursor object,


they are:
a) Fetchone() b) fetchmany (no.of record) c) fetchall()

a) fetchone(): It used for obtaining one record at a time in the form of


tuple. If no records found then we this function returns None.

b) Fetchmany(): It is used for obtaining specified number of records.

Case-1: If specified number of record == 0 then this function obtains all


records.
Case-2: If specified number of record <= Total Number of gives specified
number of records.
Case-3: If specified number of record > Total Number of Record then
this function obtains all record.
Case-4: If specified number of record < 0 then this function never gives
any records.

c) Fectchall(): It is used for obtaining all the records from cursor object.
==========================================================
Files in Python

Examples:
#Program obtaining connection from MySQL
#TestMySqlcon.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd="root")
print("type of con=",type(con))
print("Python got connection from MySQL")
==========================================================
#Program creating an object of cursor
#TestMySqlCur.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd="root")
cur=con.cursor()
print("type of cur=",type(cur))
print("Python Program created an object of cursor")
==========================================================
#Program creating a data base in mysql on the name of batch6pm
#DatabaseCreate.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd="root")
cur=con.cursor()
#prepare qurey and execute
dcq="create database"
cur.execute(dcq)
print("Database created successfully in MySQL")
==========================================================
Files in Python
#Program creating a table in batch6pm database on the name of
employee
#TableCreate.py
import mysql.connector
try:
con=mysql.connector.connect(host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=con.cursor()
#prepare query and execute
tq="create table student (sno int primary key, sname
varchar(10) not null, marks float not null, cname varchar(10)
not null ) "
cur.execute(tq)
print("Table created in MySQL--Verify")
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)
==========================================================
Object Oriented Principle or features or concepts
in Python

Object Oriented Principles or Features or Concepts

In real time, To develop any project or application, we must choose a


programming landuage and is can satisfy two types of principles, they
are:
1. Procedure oriented principles. ------- C, Pascal, Cobol, 8086,Oracle7.3,
Python.
2. Object oriented Principles. -------- Python, c++, Java, .NET….

Even though, Python programming belongs to both Procedure and


Object Oriented Programming Language and internally every thingh is
treated as object.

“ Every Thing is an Object” OR Advantages of Object Oriented Principles:

1. Objects allows us to store large volume of Data (Platform


Independent)
2. The Data is visiting between two machine in the form of Ciphet Text
(Encripted Format). So that we can achive the Security.
Object Oriented Principle or features or concepts
in Python
3. The large volumn of data can be transferred between multiple
machines all at once in the form of object and obtains effective
communication.
4. With object we can build high effective re-usable Applications.
5. The data is always available around objects (Effecive memory uses)
and functions can operate on the objects.

List of object oriented Principles

To say a language is Object oriented, it has satisfy the following


Principles:
1. Classes
2. Objects
3. Data Encapsulation,
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing.

1. Classes:

The Purpose of classes concept is that “To develop Programmer-defined


Data Type and to develop any real time applications”.

The purpose of developing Programmer-Defined Data Type is “To


customize the data storage and Operations on the Data.”

To develop any programmer-defined data type by using classes concept,


we use a keyword called “class”.

Programatically all the class name developed by programmer are called


programmer-defined Data-type.
Object Oriented Principle or features or concepts
in Python

Even program in OOPs must starts with class concept, without classes
we can’t develop single program.

Definition of Class:
A class is a collection of Data members and methods. When we define a
class, memory spase is not created for Data Members and methods but
whose memory space created when we create an object w.r.t Class.

Syntax for defining a class in Pyhton:

class <clsname>:
class level data members
def instancemethod(self, list of formal parms if any):
---------------------------------------------------------------------
---------------------------------------------------------------------
Specify instance data members and perform specific oprations
---------------------------------------------------------------------
---------------------------------------------------------------------
@classmethod
def classmethod(cls,list of formal params if any):
--------------------------------------------------------------------
--------------------------------------------------------------------
Specify class level data members and perform common operations
--------------------------------------------------------------------
--------------------------------------------------------------------
@staticmethod
def staticmethod(list of formal params if any):
-------------------------------------------------------------------
-------------------------------------------------------------------
Perform utility / Universal Operations
-------------------------------------------------------------------
-------------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python

Objects in Python

When we defined a class, memory space is not created for Data


members and methods but whose memory is created when we created
an object w.r.t class name.

To do any Data processing, it is mandatory to create an object.

To create an object, there must exist a class definition otherwise we get


NameError.

Definition of Object:

Instance of a class is called object (Instance is nothing but allocation


sufficient memory space for the Data Members and Methods of a class).

Syntax for Creating Object: varname = class name()

Examples: create an object of Student


So= Student()

Example: create an object Employee


Eo = Employee()

Differences between Class and Objects:


Class:
1) A class is a collection of Data men=mbers and methods
2) When we defined a classs, memory space is not created for Data
members and Methoda and it can be treated as specification/model
for real time application.
Object Oriented Principle or features or concepts
in Python
3) Definition of a particular exists only once.
4) When we develop any program with OOPs principles, Class Definition
Loaded First in main memory only once.

Objects:
1) Instance of a class is called Object.
2) When we created an object, we get the memory space for Data
members and methods of Class.
3) W.r.t One class definition, we can create multiple objects.
4) We can create an object after loading the class definition otherwise
we get NameError.

Types of Data Members in class of Python

In a class of python, we can defined, two types of Data Members. They


are:
1. Instance Data Members.
2. Class Level Data Members.

1. Instance Data Members:

Instance Data Members are those, whose memory space is created


every time when an object is created and hence Instance Data members
are called Object Level Data Member.

Instance Data Members are always used for storing Specific Values.

Instance Data Members can be specified/defined in 3 ways. They are:


a) Through an Object
b) By using Instance Method
c) By using Constructors
Object Oriented Principle or features or concepts
in Python

Instance Data Members can be accessed w.r.t object name or self.

Objectname. Instance data member


Or
Self.instance data member

2. Class Level Data Members:

Class Level Data Member are those, whose memory space is created
only once irrespective of number of object are created.

Class Level Data Member are used for storing common values.

Class level data members can be specified/defined in 2 ways, they are:


a) Inside of Class Definition
b) Inside of Class level method

Class Level Data Member can be accessed either w.r.t class name or
Object name or self or cls.

classname.class Level Data Member


Or
Objectname.class level data member
Or
Cls.class level data member
Or
Self.class level data member
================================================================
Object Oriented Principle or features or concepts
in Python
#program for storing student number,name and marks
#studex2.py
class Student:pass # Here Student is called Programmer-
defined Data Type.

#main program
s1=Student()
s2=Student()
#Add the Instance data members to s1 (Through an Object)
s1.sno=10
s1.sname="RS"
s1.marks=22.22
#Add the Instance data members to s2(Through an Object)
s2.stno=20
s2.name="TR"
s2.marks=33.22
s2.cname="OUCET"
#display content of s1
print("-------------------------------------")
print("Content of s1 object:")
print("-------------------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("-------------------------------------")
#display content of s2
print("Content of s2 object:")
print("-------------------------------------")
print("Student Number:{}".format(s2.stno))
print("Student Name:{}".format(s2.name))
print("Student Marks:{}".format(s2.marks))
print("Student College:{}".format(s2.cname))
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#program for storing student number,name and marks
#studex3.py
class Student:pass # Here Student is called Programmer-
defined Data Type.

#main program
s1=Student()
s2=Student()
print("-----------------------------------------")
#Add the Instance data members to s1 (Through an Object)
print("Enter First Student details:")
print("-----------------------------------------")
s1.sno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
#Add the Instance data members to s2(Through an Object)
print("Enter Second Student details:")
print("-----------------------------------------")
s2.sno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
print("Content of s1 object:")
print("-------------------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("-------------------------------------")
#display content of s2
print("Content of s2 object:")
print("-------------------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#program for storing student number,name and marks
#studex4.py
class Student: # Here Student is called Programmer-defined
Data Type.
crs="PYTHON" # here crs is called Class Level Data
Member

#main program
s1=Student()
s2=Student()
print("-----------------------------------------")
#Add the Instance data members to s1 (Through an Object)
print("Enter First Student details:")
print("-----------------------------------------")
s1.sno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
#Add the Instance data members to s2(Through an Object)
print("Enter Second Student details:")
print("-----------------------------------------")
s2.sno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
print("Content of s1 object:")
print("-------------------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("Student Course:{}".format(s1.crs) ) # OR s1.crs
print("-------------------------------------")
#display content of s2
print("Content of s2 object:")
print("-------------------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("Student Course:{}".format(s2.crs) ) # OR s2.crs
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#CircleAreaPeri.py
class Circle:
PI=3.14

#main program
c=Circle()
c.r=float(input("Enter Radious:"))
c.ar=Circle.PI*c.r**2
c.pr=2*Circle.PI*c.r
print("----------------------------------")
print("Radious={}".format(c.r))
print("Area of Circle={}".format(c.ar))
print("Perimeter of Circle={}".format(c.pr))
print("----------------------------------")
==========================================================

Types of methods in a Class

In a class of Python, we can defined three types of methods, they are:


1. Instance Method
2. Class Level Method
3. Static Method

1. Instance method:

Instance methods are used for performing specific operations on the


data of object and hance always takes “self” as First Positional
Parameters for obtaining ID of Current Class object.

Syntax: def instancemethodname(self, list of formal parms):


---------------------------------------------------------------
-------specific operations on objects-----------------
---------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python

Instance method of a class must be accessed w.r.t object name or self:

Objectname.instancemethodname()
Or
Self.instancemethodname()

What is self:

Self is one of the implicit object used as a first formal parameter in the
definition of instance method.

The self contains ID or memory address or reference of current class object.

Self is applicable for objects only.

Self can be accessed inside of corresponding instance method definition


only but not accessed other part of the program.

2. Class Level Method:

Class level Methos are used for performing class level operations such
as specifying class level data members and perform operations on them
(if required).

Class level methods always takes “cls” as first positional parameters for
obtaining current class name.

Every class level method must be preceded with a pre-defined


decorator called @classmethod.

Syntax: @classmethod
def classlevelmethodname(cls, list of formal params)
----------------------------------------------------------------
--------common operation-------------------------------
----------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python
Every class level method can be accessed w.r.t class name or cls or
object name or self.
Classname.class level method name()
Or
Cls.class level method name()
Or
Objectname.class level method name()
Or
Self.class level method name()

What is cls:

Cls is one of the implicit object used as a first formal parameter in the
definition of class level method.

The cls contains name of current class.

Cls is applicable for class level data member and class level methods only.

Cls can be accessed inside of corresponding class level method


definition only but not possible to access other part of programm.

3. Static method:

Static method are those which are used for performing utility operation
or Universal Operation.

Static methods definition neither takes “self” nor takes “cls” but it takes
an object as parameter (if req) which belongs other classes.

Syntax: @staticmethod
Def staticmethodname (list of formal params if any):
---------------------------------------------------------------------
----------------Ulitity or Universal Operations-------------
---------------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python
Statics Methods must be accessed w.r.t class name or object name.
Classname.staticmethodname()
Or
Objectname.staticmethodname()
Examples:
-------------
#Program for reading student details from KBD and dispay by
using Classes and Objects
#InstMethodEx1.py--file name and acts module name
class Student:
def readstudvalues(self ):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))

#main program
s1=Student()
s2=Student()
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
=========================================================
Object Oriented Principle or features or concepts
in Python
#Program for reading two numerical values and find sum by
using Classes and Objects
#InstMethodEx2.py--file name and acts module name
class Sum:
def readvalues(self):
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
def sumop(self):
self.c=self.a+self.b
def dispvalues(self):
return self.a,self.b,self.c

#main program
s=Sum()
s.readvalues()
s.sumop()
res=s.dispvalues()
print("sum({},{})={}".format(res[0],res[1],res[2]))
========================================================
#Program for reading two numerical values and find sum by
using Classes and Objects
#InstMethodEx3.py--file name and acts module name
class Sum:
def readvalues(self): # Instance Method
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
self.sumop() # calling sumop() from readvalues()

def sumop(self): # Instance Method


self.c=self.a+self.b
self.dispvalues() # calling dispvalues() from
sumop()
def dispvalues(self): # Instance Method

print("sum({},{})={}".format(self.a,self.b,self.c))

#main program
s=Sum()
s.readvalues()
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx1.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"

def readstudvalues(self ): # Instance Method


self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))
print("Student Course1:{}".format(Student.crs1))
print("Student Course2:{}".format(Student.crs2))

#main program
Student.getcourse1() # calling Class Level Method
Student.getcourse2() # calling Class Level Method
s1=Student()
s2=Student()
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx2.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"

def readstudvalues(self ): # Instance Method


self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))
print("Student Course1:{}".format(Student.crs1))
print("Student Course2:{}".format(Student.crs2))

#main program
s1=Student()
s2=Student()
s1.getcourse1() # calling Class Level Method
s2.getcourse2() # calling Class Level Method
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx3.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
cls.getcourse2() # One class level can call
another class level method
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"

def readstudvalues(self ): # Instance Method


self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))
print("Student Course1:{}".format(Student.crs1))
print("Student Course2:{}".format(Student.crs2))
#main program
Student.getcourse1() # calling Class Level Method
s1=Student()
s2=Student()
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx4.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"

def readstudvalues(self ): # Instance Method


self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))
self.getcourse1() # One Instance Method can call
another class level method
self.getcourse2() # One Instance Method can call
another class level method
print("Student Course1:{}".format(Student.crs1))
print("Student Course2:{}".format(Student.crs2))
#main program
s1=Student()
s2=Student()
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#staticmethodex1.py
class Employee:
def readempvalues(self):
print("-"*50)
self.eno=int(input("\nEnter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)
class Student:
def readstudvalues(self):
print("-"*50)
self.sno=int(input("\nEnter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("\nEnter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
print("-"*50)

class Hyd:
@staticmethod
def dispobjvalues(kvr):
print("="*40)
for k in kvr.__dict__:
print("\t{}--->{}".format(k,
kvr.__dict__.get(k)))
print("="*40)

#main program
e=Employee() # create an object of Employee
s=Student() # create an object of Student
t=Teacher() # # create an object of Teacher
#Read the values for employee object
e.readempvalues()
#Read the values for Student object
s.readstudvalues()
#Read the values for teacher object
t.readteachervalues()
#Today i want to define single method, which will print / display any
type of object values--called static method
print("Employee Information")
Hyd.dispobjvalues(e)
print("Student Information")
Hyd.dispobjvalues(s)
print("Teacher Information")
Hyd.dispobjvalues(t)
==========================================================
Object Oriented Principle or features or concepts
in Python
#staticmethodex2.py
class Employee:
def readempvalues(self):
print("-"*50)
self.eno=int(input("\nEnter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)
class Student:
def readstudvalues(self):
print("-"*50)
self.sno=int(input("\nEnter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("\nEnter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
print("-"*50)
class Hyd:
@staticmethod
def dispobjvalues(kvr):
print("="*40)
for k in kvr.__dict__:
print("\t{}--->{}".format(k,
kvr.__dict__.get(k)))
print("="*40)
#main program
e=Employee() # create an object of Employee
s=Student() # create an object of Student
t=Teacher() # # create an object of Teacher
#Read the values for employee object
e.readempvalues()
#Read the values for Student object
s.readstudvalues()
#Read the values for teacher object
t.readteachervalues()
#Today i want to define single method, which will print /
display any type of object values--called static method
h=Hyd() # Object creation
print("Employee Information")
h.dispobjvalues(e)
print("Student Information")
h.dispobjvalues(s)
print("Teacher Information")
h.dispobjvalues(t)
==========================================================
Object Oriented Principle or features or concepts
in Python

Constructors in Python

The purpose of constructors is that “To initialize the object”. Initializing


the object is nothing but placing our own values in the empty object.

Definition of Constructor: A constructor is a special method which is


automatically or implicitly called by PVM during object creation and
whose purpose is to initialize the object without leaving the object
empty.

Syntax for Defining Constructor:

Def __init__(self, list of formal params if any):


-------------------------------------------------------
------Block of statements- initialization------
-------------------------------------------------------
Rules or properties of constructors:

1. The name of the constructor is def __init__(self)


2. The constructors automatically or impliciti called by PVM during
object creation.
3. Constructors should not return any value (it can return only Non value.
4. Constructors participates in Inheritance process.
5. Constructors can be Overriden (can re-defined).
Object Oriented Principle or features or concepts
in Python

Types of constructors in Python

In Python Programming, we have two types of Constructors, they are:


1. Default or Parametrer-less Constructor.
2. Parameterised Constructor.

1. Default or Parametrer-less Constructor:


A constructor is said to be Default iff it never takes any argument(s) or
Formal Param(s). The purpose of Default or Parameter-less constructor
is that “To initialize multiple object of same class with same values”.

Syntax: def __init__(self)


----------------------------------------------------
-----block of statement- initialization-----
----------------------------------------------------
Examples:
----------------
#DefConstEx1.py
class Test:
def __init__(self):
print("i am from Default Constructor:")
self.a=10
self.b=20
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))

#main program
t1=Test()
t2=Test()
t3=Test()
==========================================================
Object Oriented Principle or features or concepts
in Python
2. Parameterized Constructor:
A Constructor is said to be parameterised iff it always takes any
argument(s) or Formal param(s). The purpose of parameterised
constructor is that “To initialised multiple object of same class with
Different values”.

Syntax: def __init__ (self, list of formal params):


----------------------------------------------------
-----block of statement- initialization-----
----------------------------------------------------
Examples:
--------------
#ParamConstEx1.py
class Test:
def __init__(self,a,b):
print("i am from Parameterized Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))

#main progra m
t1=Test(10,20)
t2=Test(100,200)
t3=Test("RS","PYTHON")
==========================================================

Note:
In class of python, we can’t defined both default and parameterised
constructors because PVM can remember only latest constructor (due
to it’s interpretation process). We defined single constructor with
default parameter mechanism.
Object Oriented Principle or features or concepts
in Python
Example:
------------
#DefultParamConstEx1.py
class Test:
def __init__(self,a=1,b=2):
print("i am from Default /Parameterized
Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))

#main progra m
t1=Test() # Object Creation calls Default Constructor
t2=Test(100,200) # Object Creation calls Parameterized
Constructor
==========================================================
#ConstEx1.py
class Student:
def getstudvalues(self):
self.sno=10
self.sname="RS"

#main program
s=Student() # Object Creation---- i want place my own data
without leaving an object empty.
print(s.__dict__)
s.getstudvalues()
print(s.__dict__)
==========================================================
#ConstEx2.py
class Student:
def __init__(self):
print("I am from default constructor")
self.sno=10
self.sname="RS"

#main program
s=Student() # Object Creation---- i want place my own data
without leaving an object empty.
print(s.__dict__)
==========================================================
Object Oriented Principle or features or concepts
in Python
#ConstEx3.py
class Student:
def __init__(self,sno,sname):
print("I am from Parameterfized constructor")
self.sno=sno
self.sname=sname

#main program
s1=Student(10,"DR") # Object Creation---- i want place my own
data without leaving an object empty.
print(s1.__dict__)
s2=Student(20,"TR") # Object Creation---- i want place my own
data without leaving an object empty.
print(s2.__dict__)
==========================================================
#DefConstEx1.py
class Test:
def __init__(self):
print("i am from Default Constructor:")
self.a=10
self.b=20
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))

#main progra m
t1=Test()
t2=Test()
t3=Test()
==========================================================
#DefultParamConstEx1.py
class Test:
def __init__(self,a=1,b=2):
print("i am from Default /Parameterized
Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))

#main progra m
t1=Test() # Object Creation calls Default Constructor
t2=Test(100,200) # Object Creation calls Parameterized
Constructor
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program for can Factorial of agiven Number by using Classes
and Objects
#Fact.py
import sys
class Fact:
def __init__(self):
try:
self.n=int(input("Enter Value of n:"))
except ValueError:
print("Don't enter Strs, symbols and alpha-
numric")
sys.exit()
def calfact(self):
if(self.n<0):
print("{} is invalid
input:".format(self.n))
else:
f=1
for i in range(1,self.n+1):
f=f*i
else:
print("Factorial({})={}".format(self.n,f))

#main program
fo=Fact() # Object Creation---calls default constructor
fo.calfact()
==========================================================
#Program for can Factorial of agiven Number by using Classes
and Objects
#Fact1.py
class Fact:
def __init__(self):
self.n=int(input("Enter Value of n:"))
def calfact(self):
if(self.n<0):
print("{} is invalid
input:".format(self.n))
else:
f=1
for i in range(1,self.n+1):
f=f*i
else:
print("Factorial({})={}".format(self.n,f))
#main program
try:
fo=Fact() # Object Creation---calls default constructor
fo.calfact()
except ValueError:
print("Don't enter Strs, symbols and alpha-numric")
==========================================================
Object Oriented Principle or features or concepts
in Python
#ParamConstEx1.py
class Test:
def __init__(self,a,b):
print("i am from Parameterized Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))

#main progra m
t1=Test(10,20)
t2=Test(100,200)
t3=Test("RS","PYTHON")
==========================================================

Distructors in Python and Garbage Collector

We know that garbage collector is one of the in-built program in python,


which is running behind of every python program and whose role is to
collect un-used memory space and it improves the performance of
python based applications.

Every garbage collector program is internally running and calling


Destructor functions.

The distructor function name in python is def __del__(self).

The destructor always called by Garbage Collector when the program


excecution completed for de-allocation the memory space, whereas
constructor called by PVM implicitly when object is created for
initializing the object.

When the program excecution is completed, GC calls it’s own destructor


to de-allocated the memory space of objects present in program and it
is called automatic Garbage Collection.
Object Oriented Principle or features or concepts
in Python
Here, we have three programming conditions for calling GC and to make
the garbage collection to call destructor Functions.

a) By default (or) automatically GC calls destructor, when the program


excecution completed.

b) Make the object reference as None by Forcefully.


Syntax: objectname = None

c) Delete the object by using del by Forcefully.


Syntax: del objectname

Syntax: def __del__(self):


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

Garbage Collection:

Garbage collector contains a pre-defined module calles “gc”.

Here GC contains the following functions.


1) Isenabled()
2) Enable()
3) Disable()

GC is not under control programmer but it always maintained and


managed by OS and PVM.
Object Oriented Principle or features or concepts
in Python
Examples:
--------------
#destex1.py
class Student:
def __init__(self,sno,sname):
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=Student(20,"Umesh")
print("Program Execution Ended:")
# Here There is no destructor function in this program.
#But Garbage Collector is calling its own destructor for
eleiminating Memory space for all the object which are created
as part of our program.
# A Garbage Collector contains its own destructor. hence
Programmers Need not write programmer-defined destructor.
=========================================================
#destex2.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=Student(20,"Umesh")
print("Program Execution Ended:")
time.sleep(5)
#Here GC calls destructor automatically when the program
execution completed---This is called automatic Garbage
Collection.
=========================================================
Object Oriented Principle or features or concepts
in Python
#destex3.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
s1=None
time.sleep(5)
s2=Student(20,"Umesh")
s3=Student(30,"Rossum")
s4=Student(40,"Ritche")
print("Program Execution Ended:")
time.sleep(5)
#Here GC calls destructor automatically when the program
execution completed---This is called automatic Garbage
Collection.
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex4.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
s1=None # Forcefully calling GC
time.sleep(5)
s2=Student(20,"Umesh")
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
s2=None # Forcefully calling GC
time.sleep(5)
s3=Student(30,"Rossum")
print("No Longer Interested to maintain s3 object:")
time.sleep(5)
s3=None # Forcefully calling GC
time.sleep(5)
s4=Student(40,"Ritche")
print("No Longer Interested to maintain s4 object:")
time.sleep(5)
s4=None # Forcefully calling GC
time.sleep(5)
print("Program Execution Ended:")
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex5.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
del s1 # Forcefully calling GC
time.sleep(5)
s2=Student(20,"Umesh")
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
del s2 # Forcefully calling GC
time.sleep(5)
s3=Student(30,"Rossum")
s4=Student(40,"Ritche")
print("No Longer Interested to maintain s3 object and s4
object:")
time.sleep(5)
del s3 # Forcefully calling GC
del s4 # Forcefully calling GC
time.sleep(5)
print("Program Execution Ended:")
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex6.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print(id(s1),id(s2),id(s3))
print("Program Execution Ended:")
# Even we create three objects with Deep Copy Process, There
exist simgle memory space and all three objects points same
memory space. At the end of the program GC calls only once
destructor Function.
==========================================================
#destex7.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
del s1 # Forcefully calling GC
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
del s2 # Forcefully calling GC
print("Program Execution Ended:")
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex8.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")

#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
del s1 # Forcefully calling GC
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
del s2 # Forcefully calling GC
print("No Longer Interested to maintain s3 object:")
time.sleep(5)
s3=None # Forcefully calling GC
print("Program Execution Ended:")
==========================================================
#gcex1.py
import gc
print("Line--3: Is is GC Running=", gc.isenabled()) # True
print("This is Python Class")
print("Python developed by RS")
gc.disable()
print("Line No:7-->Is is GC Running=", gc.isenabled()) # False
print("Python is an oop lang")
gc.enable()
print("Line--10: Is is GC Running=", gc.isenabled()) # True
print("Python is Fun lang")
==========================================================
Object Oriented Principle or features or concepts
in Python
#gcex2.py
import time,gc
class Student:
def __init__(self,sno,sname): # Constructor called by PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating Memory
space:")

#main program
print("Program Execution Started:")
print("Line--13: Is is GC Running=", gc.isenabled()) # True
s1=Student(10,"Litun")
s2=Student(20,"Umesh")
gc.disable()
print("Line--17: Is is GC Running=", gc.isenabled()) # False
print("Program Execution Ended:")
time.sleep(5)
#Here GC calls destructor automatically when the program execution
completed---This is called automatic Garbage Collection.
==========================================================

Data Encapsulation and Data Abstraction

Data Encapsulation: The process of Hiding the confidential


information/data/methods from external programmers/end users is
called Data Encapsulation.

The purpose of Encapsulation concept is that “To Hide confidential


Information/features of Class (Data Members and Method)”.

Data Encapsulation can be applied in to levels. They are:


a) At Data Member Level
b) At Method Level

To implement Data Encapsulation in Python programming, the Data


Members, Method must be preseded with double underscore ( __ ).
Object Oriented Principle or features or concepts
in Python

Syntax1: ( Data Member Level )


Class <className>:
Def methodname(self):
Self.__data membername1= value1
Self.__data membername1= value1
-----------------------------------------------
Self.__data membernameN= valueN
OR
Syntax1: ( Data Member Level )
Class <className>:
Def __init__(self):
Self.__data membername1= value1
Self.__data membername1= value1
-----------------------------------------------
Self.__data membernameN= valueN

Syntax2: ( Method Level )


Class <className>:
Def __methodname(self):
Self.data membername1= value1
Self.data membername1= value1
-----------------------------------------------
Self.data membernameN= valueN
Examples1:
---------------
#account.py----file name and treated as module name
class Account:
def getaccountdet(self):
self.__acno=34567
self.cname="Rossum"
self.__bal=34.56
self.bname="SBI"
self.__pin=1234
self.pincode=4444444
#here acno,bal and pin are encapsulated
Object Oriented Principle or features or concepts
in Python
=========================================================
Example2:
--------------
#account1.py----file name and treated as module name
class Account1:
def __getaccountdet(self): # here __getaccountdet()
is made is encapsulated
self.acno=34567
self.cname="Rossum"
self.bal=34.56
self.bname="SBI"
self.pin=1234
self.pincode=4444444
==========================================================
Data Abstraction: The Process of retrieving / extracting essencial details
without considering hidden details is called Data Abstraction.
==========================================================
Example1:
--------------
#others.py---This Program access only cname,bname and pincode
only
from account import Account
ao=Account()
ao.getaccountdet()
#print("Account Number={}".format(ao.acno)) Not Possible to
access
print("Account Holder Name={}".format(ao.cname))
#print("Account Bal={}".format(ao.bal)) Not Possible to
access
print("Account Branch Name={}".format(ao.bname))
#print("Account PIN={}".format(ao.pin)) Not Possible to
access
print("Account Branch Pin Code={}".format(ao.pincode))
==========================================================
Object Oriented Principle or features or concepts
in Python
Example2:
--------------
#others1.py--here we can't access method itself. so that we
cant access Instance Data Members.
from account1 import Account1
ao=Account1()
#ao.getaccountdet()---can't access
#print("Account Number={}".format(ao.acno))
#print("Account Holder Name={}".format(ao.cname))
#print("Account Bal={}".format(ao.bal))
#print("Account Branch Name={}".format(ao.bname))
#print("Account PIN={}".format(ao.pin))
#print("Account Branch Pin Code={}".format(ao.pincode))
==========================================================
Note: we can’t apply Data Encapsulation on Constructors in Python but
whose Initializaed Data Member can be Encapsulated.
==========================================================
#Account1.py----file name and module name
class Account:
def __init__(self):
self.__acno=111 # encaspsulated
self.cname="Rossum"
self.__bal=5.5 # encaspsulated
self.__pin=4567 # encaspsulated
self.bname="SBI"
----------------------------------------------------------------------------------------------
#OthersProg1.py--------------------Data Abstraction process
from Account1 import Account
ac=Account()
print("Account Details")
print("-"*50)
#print("Account Number:{}".format(ac.__acno)) can't
access
print("Account Holder Name:{}".format(ac.cname))
#print("Account Balance:{}".format(ac.bal)) can't access
#print("Account pin:{}".format(ac.pin)) can't access
print("Account Branch Name:{}".format(ac.bname))
print("-"*50)
==========================================================
Object Oriented Principle or features or concepts
in Python
#Account2.py----file name and module name
class Account:
def getaccdetails(self):
self.__acno=111 # encaspsulated
self.cname="Rossum"
self.__bal=5.5 # encaspsulated
self.__pin=4567 # encaspsulated
self.bname="SBI"
----------------------------------------------------------------------------------------------
#OthersProg2.py---------------Data Abstraction process
from Account2 import Account
ac=Account()
ac.getaccdetails()
print("Account Details")
print("-"*50)
#print("Account Number:{}".format(ac.acno)) can't access
print("Account Holder Name:{}".format(ac.cname))
#print("Account Balance:{}".format(ac.bal)) can't access
#print("Account pin:{}".format(ac.pin)) can't access
print("Account Branch Name:{}".format(ac.bname))
print("-"*50)
==========================================================
#Account3.py----file name and module name
class Account:
def __getaccdetails(self): # encaspsulated
self.acno=111
self.cname="Rossum"
self.bal=5.5
self.pin=4567
self.bname="SBI"
-----------------------------------------------------------------------------------------------
#OthersProg3.py----------------Data Abstraction process
from Account3 import Account
ac=Account()
#ac.getaccdetails() can't access
print("Account Details")
print("-"*50)
"""print("Account Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
print("Account Balance:{}".format(ac.bal))
print("Account pin:{}".format(ac.pin))
print("Account Branch Name:{}".format(ac.bname))
print("-"*50)""" # can't access
==========================================================
Object Oriented Principle or features or concepts
in Python
#Account4.py----file name and module name
class Account:
def ______init__(self): # Not comes under Data
Encapsulation
self.acno=111
self.cname="Rossum"
self.bal=5.5
self.pin=4567
self.bname="SBI"
-----------------------------------------------------------------------------------------------
#OthersProg4.py-------------------Data Abstraction process
from Account4 import Account
ac=Account()
print("Object Created")
ac.______init__() # Not comes under Data Encapsulation
print("Account Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
print("Account Balance:{}".format(ac.bal))
print("Account pin:{}".format(ac.pin))
print("Account Branch Name:{}".format(ac.bname))
==========================================================

Inheritance

Inheritance is one of distinct features of OOPs.

The purpose of inheritance is that “To build re-usable Applications in


python object Oriented Programming”.

Definition of Inheritance: The process obtaining Data member, Methods


and Constructors (features) of one class into another class is called
Inheritence.

The class which is giving Data members, Methods and Constructors


(Features) is called sub or Derived or Parent Class.

The Inheritance concept always follows Logical (Virtual) memory


Management. This Memory Management says that “Neither we write
Source code nor Take Physical Memory Space”.
Object Oriented Principle or features or concepts
in Python
Advantages of Inheritence:

When we develop any inheritance based application, we get the


following advantages.

1. Application Development Time is Less.


2. Application Memory Space is Less.
3. Application Execution time is Fast/Less.
4. Application Performance is Enhanced (Improved)
5. Redundancy (Duplication) of the code is minimised.

Types of Inheritences:

A type of inheritance is a model/Paradigm, which make us to


understand how the features are In Herited from Base Class into
Derived Class.

In python programming, we have 2 types of inheritences, they


are:

1. Single Inheritence
2. Multi Level Inheritence
Object Oriented Principle or features or concepts
in Python

Inheriting the features of Base class(es) into Derived Class

To Inherit the features of Base Class into Derived Class, we use the
following Syntax:

Class <clsname-1>:
-------------------------------
-------------------------------
Class <clsname-2>:
-------------------------------
-------------------------------
---------------------------------------
Class <clsname-n>:
-----------------------------
-----------------------------
Class <clsname-n+1>(clsname-1,clsname-2,…clsname-n) :
-----------------------------
-----------------------------
Explanation:
Here clsname-1,clsname-2,…..clsname-n are called Base or Super Classes.
<clsname-n=1> is called Derived or Sub-class.

With this syntax all features of clsname-1,clsname-2,….clsname-n are


Inherited into <clsname-n+1> logically

When we develop any Inheritance application, it is always recommended to


create an object of Bottom Most Derived Class because it inherite all the
features of Intermediate Base Classes and top most base class.

For every clss in python, there exist a predefined implicite base class called
“object” because it provides Garbage Collection to all it’s sub classes.
Object Oriented Principle or features or concepts
in Python
Examples:
---------------
#InhProg1.py
class BC:
def getN(self):
self.n=float(input("Enter a number:"))

class DC(BC):
def square(self):
self.sq=self.n**2
def disp(self):
print("square({})={}".format(self.n,self.sq))

#main program
do1=DC()
do1.getN()
do1.square()
do1.disp()
===========================================================
#InhProg2.py
class BC:
def getN(self):
self.n=float(input("Enter a number:"))

class DC(BC):
def square(self):
self.sq=self.n**2
def disp(self):
self.getN() # Calling Base Class Instance Method
Name
self.square() # Calling Current Class Instance
Method Name
print("square({})={}".format(self.n,self.sq))

#main program
do1=DC()
do1.disp()
===========================================================
Object Oriented Principle or features or concepts
in Python

Metod Overriding in Python

Method Overriding = Method Heading is same + Method Body is Different.


OR
The process of re-defining the original method of base class into various
derived classes for performing defferent operations is called Method
Overriding.

To use Method Overriding in python program we must apply Inheritence


Principle.

Method Overriding used for implementating Polymorphism Principle.

Examples:
---------------
#methodoverex1.py
class Circle:
def draw(self): # original Method
print("Drawing Circle")

class Rect(Circle):
def draw(self): # overridden Method
print("Drawing Rect:")
super().draw()

class Square(Rect):
def draw(self): # overridden Method
print("Drawing Square:")
super().draw()

#main program
so=Square()
so.draw()
=============================================================
Object Oriented Principle or features or concepts
in Python
#teacher.py
class Teacher:
def readsub(self):
print("Teacher advises to read 2 hours")

class LazyStudent(Teacher):
def readsub(self):
print("LazyStudent never read at all")
class PerfectStudent(Teacher):
def readsub(self):
print(" Perfect Student 2hrs reading and
practicing")

ls=LazyStudent()
ls.readsub()
ps=PerfectStudent()
ps.readsub()
============================================================

Polymorphism in Python

Polymorphism is one of the distinct features of OOPs.

The purpose of Polymorphism is that “Efficient Utilization Memory Spaces


or Less Memory space is achieved”.

Def. of Polymorphism:
The process of representating “One Form in multiple Form” is called
polymorphism”.

The Polymorphism Principle is implemented(Bring into action) by using


“Method Overriding” feature of all OO Programming Languages.

In the definition of Polymorphism, “One Form” represents “Original


Method” and multiple forms represents Overridien Method.
Object Oriented Principle or features or concepts
in Python

A “Form” is nothing but existence of a Method. If the method is existing in


base class then it is called “Original Method (one form)” and if the method
existing derived class(es) then it is called “Overriden Method (Multiple
Form)”.

Number of approaches to call Original method/constructors from


Overridden methods/Constructors:

We have two approaches to call original method / constructors of base


class form overridden method / constructors of derived class. They are:
1. By using super()
2. By using Class name

1. By using super(): super() is one of th pre-defined function, which is used


for calling super class original method / constructor from overridden
method / constructors of derived class.

Syntax1: super().methodname(list of values if any)

Syntax2: super().__init__(list of values if any)

With super() we are able to call only one immediate base class method but
unable to call specified method of base class. To do this we must use clss
name approach.

2. By using class name: By using class name approach, we can call any base
class method/ constructor name from the context of derived class
method / constructor names.

Syntax1: ClassName.methodname(self,list of values if any)

Syntax2: ClassName.__init__(self, list of values if any)


Object Oriented Principle or features or concepts
in Python
Examples:
--------------
#ConstOverEx1.py
class Circle:
def __init__(self): # Original Constructor (One Form )
print("Drawing--Circle--DC")

class Rect(Circle):
def __init__(self): ## Overridden Constructor (Multiple
Forms)
print("Drawing--Rect--DC")

class Square(Rect):
def __init__(self): # Overridden Constructor (Multiple
Forms)
print("Drawing--Square--DC")

#main program
s=Square()
=============================================================
#MethodOverEx1.py
class Circle:
def draw(self): # Original Method (One Form )
print("Drawing--Circle")

class Rect(Circle):
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Rect")

class Square(Rect):
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Square:")

#main program
print("w.r.t Square")
s=Square()
s.draw()
=============================================================
Object Oriented Principle or features or concepts
in Python
#NonMethodOver.py
class Circle:
def draw1(self):
print("Drawing--Circle")
class Rect(Circle):
def draw2(self):
print("Drawing---Rect")

#main program
r=Rect()
r.draw1()
r.draw2()
===========================================================
#PolyEx1.py
class Circle:
def draw(self): # Original Method (One Form )
print("Drawing--Circle")
class Rect:
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Rect")
class Square(Circle,Rect):
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Square")
super().draw()
Rect.draw(self)

#main program
s=Square()
s.draw()
============================================================
#PolyEx2.py
class Circle:
def __init__(self): # Original Constructor (One Form )
print("Drawing--Circle")
class Rect:
def __init__(self): # Overridden Constructor (Multiple
Forms)
print("Drawing--Rect--DC")
class Square(Circle,Rect):
def __init__(self): # Overridden Constructor (Multiple
Forms)
print("Drawing--Square--DC")
Rect.__init__(self)
super().__init__()

#main program
s=Square()
=============================================================
Object Oriented Principle or features or concepts
in Python
#write a python program which will calculate area of different
figures by using polymorphism
#PolyEx3.py
class Circle:
def area(self,r):
print("-"*50)
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
print("-"*50)
class Square(Circle):
def area(self,s):
print("-"*50)
self.sa=s**2
print("Area of Square:{}".format(self.sa))
print("-"*50)
class Rect(Square):
def area(self,l,b=0):
print("-"*50)
self.ar=l*b
print("Area of Rect:{}".format(self.ar))
print("-"*50)
Circle.area(self,float(input("Enter Radious:")))
super().area(float(input("Enter Side:")))

#main program
r=Rect()
r.area(float(input("Enter Length:")),float(input("Enter
breadth:")) )
============================================================
Object Oriented Principle or features or concepts
in Python
#write a python program which will calculate area of different
figures by using polymorphism
#PolyEx4.py
class Circle:
def __init__(self,r):
print("-"*50)
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
print("-"*50)
class Square:
def __init__(self,s):
print("-"*50)
self.sa=s**2
print("Area of Square:{}".format(self.sa))
print("-"*50)
class Rect(Square,Circle):
def __init__(self,l,b=0):
print("-"*50)
self.ar=l*b
print("Area of Rect:{}".format(self.ar))
print("-"*50)
super().__init__(float(input("Enter Side:")))
Circle.__init__(self,float(input("Enter
Radious:")))

#main program
r=Rect(float(input("Enter Length:")),float(input("Enter
breadth:")))
============================================================
Regular Expressions in Python

Index

• Purpose of Regular Expressions in Python


• Definition of regular Expressions.
• Applications of regular Expression.
• Module Name for Regular Expression.
• Functions in “re” Module.
1) Finditer()
2) Findall()
3) Search()
4) Start()
5) End()
6) Group()
• Programming Examples
• Programmer-Defined Character Classes
• Programming Examples
• Quantifiers in Regular Expressions.
• Programming Examples
• Combined Programming Examples on Programmer, pre-defined and
Quantifiers.
Regular Expressions in Python

Regular Expressions in Python

Regular Expressions is a Programming Language Independent Topic.


The purpose of Regular Expressions in Python is that “To Validate the
given information according to Business requirements”.

Definition of Regular Expression:


A Regular Expression is one of the Serach Pattern which is a combination
of alphabates, digits and special symbols and it is used to search or
match oor find in the given data and obtains desired result.

Application of Regular Expressions:


1) Regular Expressions are used in Language Compilers and Interpreters
Development.
2) Regular Expressions are used in OS development.
3) Regular Expressions are used in Universal Protocols Development.
4) Regular Expressions are used in Editor and IDEs for search Pattern.
5) Regular Expressions used in Electronics Circuits designing….etc.

Module Name for Regular Expressions ( RegEx)

To Deal with Regular Expressions Programs, we must use a pre-defind


module called “re”.
“re” Module contains the following functions.
1) Finditer()
2) Findall()
3) Search()
4) Start()
5) End()
6) Group()
Regular Expressions in Python

1) Finditer(): This function is used for searching the “search-pattern” in


Given-Data iteratively and it returns table of entries which contains
start index, end index and matched value based on the search
pattern.

Syntax: varname = re.finder(“search-pattern”, “Given data”)


Here varname is an object of type <class, ‘Callable_Iterator’>

2) Group (): This function is used obtaining matched value by the finditer().
This function present in match class of “re” Module.

Syntax: varname = matchobj.group()

3) Start(): This function is used obtaining starting index of matched


value. This function present in matche class of “re” module.

Syntax: varname = matchobj.start()

4) End(): This function is used obtaining end index+1 of matched value.


This function present in match class of “re” Module.

Syntax: varname = matchobj.end()

5) Search (): This function is used for searching the search-pattern in


given data for first occurrence/ match only but not for other
occurrence/matchs.

If the search pattern found in given data then it returns an object of


match class which contains matched value and start and end index
values and it indicates search is successful.

If the search pattern not found in given data then it returns None which
is type <class, “Nonetype”> and it indicates search is unsuccessful.

Syntax: varname = re.search(“search-pattern”, “Given data”)


Here varname is an object of <class, ‘re.match’> or <class, ‘NoneType’>
Regular Expressions in Python

6) Findall(): This function is used for searching the search-pattern in


entire given data and find all accurences/matches and it returns all
the matched values in the form an object <class, ‘list’ > but not
returning start and end index value.

Syntax: varname = re.findall(“search-pattern”, “Given data”)


Here varname is an object of <class, ‘list’>

Examples:
---------------
#RegExpr1.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="Python"
lst=re.findall(sp,gd)
print("'{}' is found {} Times:".format(sp,len(lst)))
==========================================================
#RegExpr2.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="python"
matobj=re.search(sp,gd) # here matobj is an object of
<class , re.match>
if(matobj!=None):
print("\nSearch is Sucessful")
print("Start Index:{} End Index:{}
Value:{}".format(matobj.start(),matobj.end(),matobj.group()) )
else:
print("\nSearch is Not Successful")
==========================================================
#RegExpr3.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="ant"
obj=re.finditer(sp,gd) # Here obj is an object of <class
'callable_iterator'>
for m in obj:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(),m.group()))
==========================================================
Regular Expressions in Python

Programmer-Defined Character Classes

Programmer-defined character classes developed by programmer which


are used for preparing search pattern and it is used to search in given
data for finding desired result.

Syntax: “[ search pattern ]”

1) [abc] : Searching for either ‘a’ or ‘b’ or ‘c’ only.


2) [^abc ] : Searching for all except ‘a’ or ‘b’ or ‘c’ .
3) [A-Z] : Searching for Upper Case Alphabates.
4) [^A-Z] : Searching for all except Upper Case Alphabates.
5) [a-z] : Searching for Lower Case Alphabates.
6) [^a-z] : Searching for all except Lower Case Alphabates.
7) [0-9] : Searching for digits only.
8) [^0-9] : Searching for all except digits.
9) [A-Za-z] : Searching for Upper and Lower Case Alphabates.
10)[^A-Za-z] : Searching for all except Alphabates.
11) [A-Za-z0-9] : Searching for all Alpha-Numerics.
12)[^A-Za-z0-9] : Searching for all special symbols except Alpha-Numerics.
13)[A-Z0-9] : Searching for Uppercase alphabates and Digits.
14)[^A-Z0-9] : Searching for all except Uppercase alphabates and Digits.
15)[a-z0-9] : Searching for lowercase alphabates and digits.
16)[^a-z0-9] : Searching for all except lowercase alphabates and digits.
Regular Expressions in Python

Examples:
--------------
#RegExpr1.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="Python"
lst=re.findall(sp,gd)
print("'{}' is found {} Times:".format(sp,len(lst)))
===========================================================
#RegExpr2.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="python"
matobj=re.search(sp,gd) # here matobj is an object of
<class , re.match>
if(matobj!=None):
print("\nSearch is Sucessful")
print("Start Index:{} End Index:{}
Value:{}".format(matobj.start(),matobj.end(),matobj.group()) )
else:
print("\nSearch is Not Successful")
===========================================================
#RegExpr3.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="ant"
obj=re.finditer(sp,gd) # Here obj is an object of <class
'callable_iterator'>
for m in obj:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(),m.group()))
===========================================================
#RegExpr4.py
#Searching for either 'a' or 'b' or 'c' only
import re
mat=re.finditer("[abc]","cAKL5&@9HpaTbU*#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)
"""--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:b
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
#RegExpr5.py
#Searching for all except a' or 'b' or 'c'
import re
mat=re.finditer("[^abc]","cAKL5&@9HpaTbU*#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)

"""
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:K
Start Index:3 End Index:4 Value:L
Start Index:4 End Index:5 Value:5
Start Index:5 End Index:6 Value:&
Start Index:6 End Index:7 Value:@
Start Index:7 End Index:8 Value:9
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:11 End Index:12 Value:T
Start Index:13 End Index:14 Value:U
Start Index:14 End Index:15 Value:*
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
-----------------------------------------"""
==============================================================
#RegExpr6.py
#Searches for Upper Case Alphabets only
import re
mat=re.finditer("[A-Z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)
"""--------------------------------------------------
Start Index:1 End Index:2 Value:A
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:H
Start Index:10 End Index:11 Value:T
Start Index:12 End Index:13 Value:U
Start Index:14 End Index:15 Value:L
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
#RegExpr7.py
#Searches for all except Upper Case Alphabets
import re
mat=re.finditer("[^A-Z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:6 End Index:7 Value:9
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:11 End Index:12 Value:b
Start Index:13 End Index:14 Value:*
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
Start Index:19 End Index:20 Value:e
--------------------------------------------------
"""
==========================================================
#RegExpr8.py
#Searches for all lower Case Alphabets only
import re
mat=re.finditer("[a-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:11 End Index:12 Value:b
Start Index:19 End Index:20 Value:e
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr9.py
#Searches for all except lower Case Alphabets.
import re
mat=re.finditer("[^a-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:5 End Index:6 Value:K
Start Index:6 End Index:7 Value:9
Start Index:7 End Index:8 Value:H
Start Index:10 End Index:11 Value:T
Start Index:12 End Index:13 Value:U
Start Index:13 End Index:14 Value:*
Start Index:14 End Index:15 Value:L
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
--------------------------------------------------
"""
=========================================================
#RegExpr10.py
#Searches for all digits
import re
mat=re.finditer("[0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""

--------------------------------------------------
Start Index:2 End Index:3 Value:5
Start Index:6 End Index:7 Value:9
Start Index:16 End Index:17 Value:4
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr11.py
#Searches for all except digits
import re
mat=re.finditer("[^0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""

--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:H
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:10 End Index:11 Value:T
Start Index:11 End Index:12 Value:b
Start Index:12 End Index:13 Value:U
Start Index:13 End Index:14 Value:*
Start Index:14 End Index:15 Value:L
Start Index:15 End Index:16 Value:#
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python

#RegExpr12.py
#Searches for all alphabets
import re
mat=re.finditer("[A-Za-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""

--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:H
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:10 End Index:11 Value:T
Start Index:11 End Index:12 Value:b
Start Index:12 End Index:13 Value:U
Start Index:14 End Index:15 Value:L
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
--------------------------------------------------"""
==========================================================
#RegExpr13.py
#Searches for all except alphabets
import re
mat=re.finditer("[^A-Za-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:6 End Index:7 Value:9
Start Index:13 End Index:14 Value:*
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
--------------------------------------------------"""
=========================================================
Regular Expressions in Python
#RegExpr14.py
#Searches for all alphabets and Digits only(Except Special
Symbols)
import re
mat=re.finditer("[A-Za-z0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""

--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:5 End Index:6 Value:K
Start Index:6 End Index:7 Value:9
Start Index:7 End Index:8 Value:H
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:10 End Index:11 Value:T
Start Index:11 End Index:12 Value:b
Start Index:12 End Index:13 Value:U
Start Index:14 End Index:15 Value:L
Start Index:16 End Index:17 Value:4
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
--------------------------------------------------"""
==========================================================
#RegExpr15.py
#Searches for all special symbols except alphabets
import re
mat=re.finditer("[^A-Za-z0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:13 End Index:14 Value:*
Start Index:15 End Index:16 Value:#
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr16.py
#Searches for Space Character
import re
mat=re.finditer("\s","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:4 End Index:5 Value:
Start Index:11 End Index:12 Value:
--------------------------------------------------"""
==========================================================
#RegExpr17.py
#Searches for all except Space Character
import re
mat=re.finditer("\S","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:5 End Index:6 Value:@
Start Index:6 End Index:7 Value:K
Start Index:7 End Index:8 Value:9
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:b
Start Index:14 End Index:15 Value:U
Start Index:15 End Index:16 Value:*
Start Index:16 End Index:17 Value:L
Start Index:17 End Index:18 Value:#
Start Index:18 End Index:19 Value:4
Start Index:19 End Index:20 Value:Q
Start Index:20 End Index:21 Value:L
Start Index:21 End Index:22 Value:e
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr18.py
#Searches for all digits
import re
mat=re.finditer("\d","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:2 End Index:3 Value:5
Start Index:7 End Index:8 Value:9
Start Index:18 End Index:19 Value:4
--------------------------------------------------"""
==========================================================
#RegExpr19.py
#Searches for all except except digits
import re
mat=re.finditer("\D","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:
Start Index:5 End Index:6 Value:@
Start Index:6 End Index:7 Value:K
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:10 End Index:11 Value:a
Start Index:11 End Index:12 Value:
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:b
Start Index:14 End Index:15 Value:U
Start Index:15 End Index:16 Value:*
Start Index:16 End Index:17 Value:L
Start Index:17 End Index:18 Value:#
Start Index:19 End Index:20 Value:Q
Start Index:20 End Index:21 Value:L
Start Index:21 End Index:22 Value:e
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
#RegExpr20.py
#Searches for all except except digits
import re
mat=re.finditer("\w","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:6 End Index:7 Value:K
Start Index:7 End Index:8 Value:9
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:b
Start Index:14 End Index:15 Value:U
Start Index:16 End Index:17 Value:L
Start Index:18 End Index:19 Value:4
Start Index:19 End Index:20 Value:Q
Start Index:20 End Index:21 Value:L
Start Index:21 End Index:22 Value:e
--------------------------------------------------"""
==========================================================
Regular Expressions in Python

Pre-Defined Character Classes

Pre-Defined Character Classes are already Pre-defined in python


software which are used for preparing Search Pattern and it is used to
search in given data for finding desired result.

Syntax: “\search pattern”

1) \s : Searching for space character.


2) \S : Searching for all except space character.
3) \d : Searching for digits only. OR [0-9]
4) \D : Searching for all except digits. OR [^0-9]
5) \w : Searching for any word character (Alphabates and Digits)
OR [A-Za-z0-9]
6) \W : Searching for special symbols. OR [A-Za-z0-9]

Quantifiers in Regular Expressions

Quantifiers in Regular Expressions are used for searching number of


Occurrences of the specified value (alphabates or digits or special
symboles) used in search pattern to search in the given data and obtains
desired result.

1) “k” : It search for only one ‘k’ at a time.


2) “k+” : It search for either one ‘k’ more ‘k’s.
3) “k*” : It search for either zero ‘k’ or one ‘k’ and more ‘k’s.
4) “k?” : It search for either zero ‘k’ or one ‘k’.
5) “. ” : It search for all.
Regular Expressions in Python

Note:
\ddd or \d{3} : Searches for 3 Digits.
\dd.\dd : Searches for 2 integer values and 2 decimal values.
\d{2,4} : Searches for nin 2 Digit number and max 4 digit number.
[A-Za-z]+ : Searches one alphabet or mere alphabets.
\w+
[0-9]+ OR \d+

Examples:
--------------
#RegExpr21.py
#Searches for all special symbols
import re
mat=re.finditer("\W","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""

--------------------------------------------------
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:
Start Index:5 End Index:6 Value:@
Start Index:11 End Index:12 Value:
Start Index:15 End Index:16 Value:*
Start Index:17 End Index:18 Value:#
--------------------------------------------------
"""
==========================================================
#RegExpr22.py
#Searches for only 'k'
import re
mat=re.finditer("k","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
Regular Expressions in Python
"""

--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:2 End Index:3 Value:k
Start Index:3 End Index:4 Value:k
Start Index:5 End Index:6 Value:k
Start Index:6 End Index:7 Value:k
Start Index:7 End Index:8 Value:k
Start Index:9 End Index:10 Value:k
--------------------------------------------------
"""
==========================================================
#RegExpr23.py
#Searches for either one 'k' or more k's
import re
mat=re.finditer("k+","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""

--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:2 End Index:4 Value:kk
Start Index:5 End Index:8 Value:kkk
Start Index:9 End Index:10 Value:k
--------------------------------------------------
"""
==========================================================
#RegExpr24.py
#Searches for either zero k or one 'k' or more k's
import re
mat=re.finditer("k*","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
Regular Expressions in Python
"""

--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:1 End Index:1 Value:
Start Index:2 End Index:4 Value:kk
Start Index:4 End Index:4 Value:
Start Index:5 End Index:8 Value:kkk
Start Index:8 End Index:8 Value:
Start Index:9 End Index:10 Value:k
Start Index:10 End Index:10 Value:
Start Index:11 End Index:11 Value:
--------------------------------------------------"""
==========================================================
#RegExpr25.py
#Searches for all
import re
mat=re.finditer(".","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)

"""
--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:1 End Index:2 Value:v
Start Index:2 End Index:3 Value:k
Start Index:3 End Index:4 Value:k
Start Index:4 End Index:5 Value:v
Start Index:5 End Index:6 Value:k
Start Index:6 End Index:7 Value:k
Start Index:7 End Index:8 Value:k
Start Index:8 End Index:9 Value:v
Start Index:9 End Index:10 Value:k
Start Index:10 End Index:11 Value:v
--------------------------------------------------
"""
==========================================================
Multi Threading in Python
Index:
-----------
Purpose of Multi Threading

Types of Applications
a) Process Based Applications
b) Thread Based Applications

Development Thread Based Applications

Module Name for Thread Based Applications.

Number of approaches for Developing Thread Based Applications

Programming Examples
---------------------------------------------------------------------------------------
Synchronization in Threading (OR) Dead Concept in Threading
Implementation of Synchronization in Threading (OR) Dead Concept in
Threading

Lock class
a) acquire()
b) release()

Programming Examples
=======================================================
Multi Threading in Python
Multi-Threading in Python
========================================

The purpose of Multi-Threading is " To provide Concurrent Execution"

The concurrent execution is nothing but Simultaneous or Parallel


Execution.

The Advantage of Concurrent Execution is that always takes Less


Execution Time.

In the context of Programming Languages, we have 2 types of


Languages. They are
a) Process Based Applications
b) Thread Based Applications.

a) Process Based Applications:


---------------------------------------
Process Based Applications execution environment contains Single
Thread

Process Based Applications provides Sequential Execution

Process Based Applications Takes More Execution Time

Process Based Applications are treated as Heavy Weight Application.

Examples: C,CPP...etc
--------------------------------------------------------------------------------------------
b) Thread Based Applications.
-------------------------------------------------------------------------------------------
Thread Based Applications are those whose execution environment
contains Single Thread (by deafult) and allows us create Multiple
Threads programatically.
Multi Threading in Python
Thread Based Applications provides Sequential Execution (by default)
also provides Concurrent Execution programatically.

Thread Based Applications Takes Less Execution Time

Thread Based Applications are treated as Light Weight Application

Examples: Python, Java . C#.Net...etc

=========================================
Introduction to Thread Based Applications
=========================================
The purpose of multi-threading is that "To provide Concurrent /
Simultaneous execution / Paralllel Execution".

Concurrent Execution is nothing but executing the operations all at


once.

The advantage of Concurrent execution is that to get less execution


time.

If a Python Program contains multiple threads, then it is called Multi-


Threading program.
--------------------------
Def. of thread:
--------------------------
A flow of Control is called thread.

The purpose of thread is that "To Perform certain operation whose


logic developed in Functions / Methods concurrently."

By default Every Python contains Single Thread and whose name is


"Main Thread" and It provides Sequential Execution.

Programmatically, In a Python Program we can create multiple


sub/Child threads and whose purpose is that "To execute operations
Multi Threading in Python
whose logic is written in Functions / Methods Concurrently ".

Hence Programmatically a Python Program contains two types of


Threads. They are:
a) MainThread b) Sub / Child Threads

Main Thread is created / Initiated by PVM, when program execution


starts and the role of main Thread is to execute main program
statements and Monitor the execution status of Sub threads (if sub
threads present).

The Sub / Child Threads always executes operations whose logic is


written in Functions / Methods Concurrently ".
Multi Threading in Python
Examples:
--------------
Demo1.py
---------------------------------------------------------------------
import threading
tname=threading.current_thread().name
print("Default Name of thread=",tname)
print("This Multi Threadding class")
print("From ggn")
--------------------------------------------------

Demo2.py
-------------------
import threading
def hello():
print("\nLine-3--> am from hello()--executed
by",threading.current_thread().name)
def hi():
print("\nI am from hi()--executed by
",threading.current_thread().name)
def greet():
print("\nI am from greet()--executed by
",threading.current_thread().name)

#main program
print("\nLine-10-->Default Name of thread in main
program=",threading.current_thread().name)
hello()
print("\nLine-12-->Default Name of thread in main
program=",threading.current_thread().name)
hi()
print("\nLine-15-->Default Name of thread in main
program=",threading.current_thread().name)
greet()
print("\nLine-17-->Default Name of thread in main
program=",threading.current_thread().name)
------------------------------------------------------------
Multi Threading in Python
non-threadex1.py
---------------------
import time,threading
def squares(lst):
for i in lst:
print("{} executed by
square({})={}".format(threading.current_thread().name,i,i**2))
time.sleep(1)

def cubes(lst):
for i in lst:
print("{} executed by
cubes({})={}".format(threading.current_thread().name,i,i**3))
time.sleep(1)

#main program
bt=time.time()
print("\nDefault Name of thread in main
program=",threading.current_thread().name)
lst=[2,5,12,6,13,19,4,16]
squares(lst)
cubes(lst)
print("\nProgram execution Completed:")
et=time.time()
print("Exec Time by Non-Threading application:{}".format(et-bt))
----------------------------------------------------------------
#threadex1.py
----------------
import time,threading
def squares(lst):
for i in lst:
print("{} executed by
square({})={}".format(threading.current_thread().name,i,i**2))
time.sleep(1)
def cubes(lst):
for i in lst:
print("{} executed by
cubes({})={}".format(threading.current_thread().name,i,i**3))
time.sleep(1)

#main program
bt=time.time()
print("\nDefault Name of thread in main
program=",threading.current_thread().name)
lst=[2,5,12,6,13,19,4,16]
#create sub threads
t1=threading.Thread(target=squares,args=(lst,) ) # Thread-1
t2=threading.Thread(target=cubes,args=(lst,) ) # Thread-2
t1.start()
t2.start()
t1.join()
t2.join()
print("\nProgram execution Completed:")
et=time.time()
print("Exec Time by Threading Application:{}".format(et-bt))
----------------------------------------------------------------
Multi Threading in Python
threading module
===================================================
1) current_thread()
--------------------------
It is used for obtaining name of th thread
Syntax: threading.current thread().name

2) active count():
------------------------
This function is used for counting number of active threads
Syntax:- threading.active_count()
========================================================
threading contains two classes--- 1. Thread 2.Lock
======================================================
1. Thread class
---------------------------
1) Thread(target,args): This constructor is used for creating sub thread
and initlizing with which Function to exdcute(target) by the sub thread
and whgich parameters(args) to pass(if required)

Syntax:-
varname=threading.Thread(target=Functionname,args=(Val1,val2....Val-n))
Here varname is called an object of sub thread

2) start():
---------------
=>This function is used for dispatching the sub thread for executing
targeted Function .
=>Syntax:- subthreadobj.start()

3) join():
-------------
=>This function is used for making the sub threads to join with main
thread after sub threads completion.
Syntax: subthreadobj1.join()
subthreadobj2.join()
--------------------------
Multi Threading in Python
subthreadobj-n.join()
4) setName():
-----------------------
=>This function is used for setting the user-friendly name to the sub
thread.
=>This Function is deprecated on the name of "name" attribute
=>Syntax:- subthread.setName("str")
(OR)
subthread.name=str data Here str data represent sub thread name

Example: t1.setName("Raju") (OR) t1.name="Raju"

5) getName():
----------------------
This function is used forobtaining the thread name
This Function is deprecated on the name of "name" attribute

Syntax:- subthreadname=subthreadobj.getName()
(OR)
str data=subthread.name
# Here str data represent sub thread name

Example: tname=t1.getName()
(OR)
tname=t1.name
6) is_alive():
-----------------
This function returns true provded sub thread is under execution
otherwise it return False.

Syntax: subthreadname.is_alive()

Example: t1.is_alive()

8) run(self):
------------------
Multi Threading in Python
This function is used for defining the logic of Python program, which is
executed sub thread

This function automatically called through start()

This Function must be always overridden when we develop any thread


based application by using Sub Class of Thread class( By using Object
Oriented Approach with Inheritance )
Syntax:
class <clsname>(threading.Thread):
------------------------------------
------------------------------------
def run(self):

block of statements provides logic for thread


========================================================
Number of approaches to develop multithreading applications
=====================================================
In Python Programming, we have 3 approaches to develop multi
therading applications.

1. By using Functional Programming


2. By using Object Oriented Approach without Inheritance
3. By using Object Oriented Approach with Inheritance

1. By using Functional Programming


--------------------------------------------------------------------------------------------
Step-1: import threading module
Step-2: define a programmer-defined function(s)
Step-3: create sub thread(s)
Step-4: Dispatch the sub threads.

Examples:
-----------------
#Program generating 1 to n number after each very second by using
threads
#approachEx1.py
import time
import threading # step-1
Multi Threading in Python
def generate(): #step-2
n=int(input("Enter how many numbers u want to generate:"))
if(n<=0):
print("{} is invalid".format(n))
else:
print("-"*50)
print("Numbers within :{}".format(n))
print("-"*50)
for i in range(1,n+1):
print("Val of i=",i)
time.sleep(1)
print("-"*50)

#main program
t1=threading.Thread(target=generate) # step-3
t1.start()

-----------------------------------------------------------------------
2. By using Object Oriented Approach without Inheritance
-----------------------------------------------------------------------
Step-1: import-threading module
Step-2 Define Programmer-defined class
Step-3: defined Instance Method in Programmer-defined class
Step-4: create an object of Programmer-defined class
Step-5: create sub thread
Step-6: Dispatch the sub threads.
Examples:
-------------------
#Program generating 1 to n number after each very second by using
threads
#approachEx2.py
import time
import threading #Step-1
class Numbers: #Step-2
def generate(self,n): #Step-3
self.n=n
if(self.n<=0):
print("{} is invalid".format(self.n))
else:
print("-"*50)
print("Numbers within :{}".format(self.n))
print("-"*50)
for i in range(1,self.n+1):
print("Val of i=",i)
time.sleep(1)
print("-"*50)

#main program
n=Numbers() #Step-4
t1=threading.Thread(target=n.generate,args=(int(input("Enter a
number:")),)) #Step-5
t1.start() #Step-6
========================================================
Multi Threading in Python
3. By using Object Oriented Approach with Inheritance
--------------------------------------------------------------------------------------------
Step-1: import therading module
Step-2: Choose and defined Programmer-Defined Class
Step-3: The Programmer-Defined class must inherit from Thread class
of threading module
Step-4: The Programmer-Defined class must override run(self) of
Thread class
Step-5 : Create an object of The Programmer-Defined class, which is
the sub class of Thread class
Step-6: Dispatch the sub thread
Examples:
----------------
#Program generating 1 to n number after each very second by using
threads
#approachEx3.py
import threading ,time # Step-1
# Step-2 Step-3
class Numbers(threading.Thread):
def setvalue(self,n):
self.n=n
def run(self): # Step-4--->Overriding the run() of Thread class
of threading module
self.setvalue(int(input("Enter Value of n:")))
if(self.n<=0):
print("{} is invalid".format(self.n))
else:
print("-"*50)
print("Numbers within :{}".format(self.n))
print("-"*50)
for i in range(1,self.n+1):
print("Val of i=",i)
time.sleep(1)
print("-"*50)

#main program
n=Numbers() #Step-5----Sub thread creation only
print("Execution status of sub thread before =",n.is_alive())
n.start() # Step-6----dispatching sub thread
print("Execution status of sub thread after start=",n.is_alive())
=======================================================================

#write a python program which will print even numbers seprated by one
thread and odd no. seprated by one thread and voiwels in given line.

#EvenOddVowels.py
import threading,time
def evennumbers(n): # Functional Approach
if(n<=0):
print("{} is invalid".format(n))
else:
for i in range(2,n+1,2):
Multi Threading in Python
print("{}-->Generates Even
Number:{}".format(threading.current_thread().name,i))
time.sleep(0.75)

class Odd:
def oddnumbers(self,n): # Object Oriented Approach without using
Inheritance
if(n<=0):
print("{} is invalid".format(n))
else:
for i in range(1,n+1,2):
print("{}-->Generates Odd
Number:{}".format(threading.current_thread().name,i))
time.sleep(0.75)

class Vowels(threading.Thread):
def settext(self,line):
self.line=line
def run(self): # Object Oriented Approach without using
Inheritance
if (self.line.isspace() or len(self.line)==0):
print("Given String is empty:")
else:
for i in [ j for j in self.line if j.lower() in
['a','e','i','o','u'] ]:
print("{}-->Generates
Vowel:{}".format(threading.current_thread().name,i))
time.sleep(0.75)

#main program
v=Vowels() # Object Oriented Approach with Inheritance
line=input("Enter a line of text:")
v.settext(line)
n=int(input("Enter a Number:"))
et=threading.Thread(target=evennumbers,args=(n,)) # Functional
Approach
ot=threading.Thread(target=Odd().oddnumbers,args=(n,)) # Object
Oriented Approach without using Inheritance
et.start()
ot.start()
v.start()
=======================================================================
#Write a Python Program which will accept a line of text and display each
and every character after one second using thread

#CharGenApproachEx1.py----Functional Approach
------------------------------------------
import threading,time
def chargeneration(line):
if (line.isspace() or len(line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",line)
print("-"*50)
for ch in line.split():
print("\t\t{}".format(ch))
time.sleep(0.5)
print("-"*50)

#main program
Multi Threading in Python
t=threading.Thread(target=chargeneration,args=(input("Enter a line:"),))
t.start()
=======================================================================
#Write a Python Program which will accept a line of text and display
each and every character after one second using thread
----------------------------------------------------------------------
#CharGenApproachEx2.py----Object Oriented Approach without Inheritance
-------------------------------------------------
import threading,time
class CharGen:
def chargeneration(self,line):
self.line=line
if (self.line.isspace() or len(self.line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",self.line)
print("-"*50)
for ch in self.line.split():
print("\t\t{}".format(ch))
time.sleep(0.5)
print("-"*50)

#main program
t=threading.Thread(target=CharGen().chargeneration,args=(input("Enter a
line:"),))
t.start()
=======================================================================
#Write a Python Program which will accept a line of text and display
each and every character after one second using thread
---------------------------------------------------------------
#CharGenApproachEx3.py----Object Oriented Approach with Inheritance
-------------------------------------------------------------------
import threading,time
class CharGen(threading.Thread):
def run(self):
self.line=input("Enter a line of Text:")
if (self.line.isspace() or len(self.line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",self.line)
print("-"*50)
for ch in self.line:
print("\t\t{}".format(ch))
time.sleep(0.5)
print("-"*50)

#main program
cg=CharGen() # here cg is an object of CharGen Class and it is sub
thread
cg.start() # start() automatically calls run(), which as already
overridden in CharGen Class.
=======================================================================
Multi Threading in Python

Synchronization in Multi Threading


(OR)
Locking concept in Threading
================================================
When multiple threads are operating / working on the same
resource(function / method) then by default we get dead lock result
/ race condition / wrong result / non-thread safety result.

To overcome this dead lock problems, we must apply the concept of


Synchronization

The advantage of synchronization concept is that to avoid dead lock


result and provides Thread Safety Result.

In Python Programming, we can obtain synchronization concept by


using locking and un-locking concept.

--------------------------------------------------------------------------------------
Multi Threading in Python
Steps for implementing Synchronization Concept:
(OR)
Steps for avoiding dead lock
--------------------------------------------------------------------------------------
1) obtain / create an object of Lock class, which is present in threading
module.
Syntax:- lockobj=threading.Lock()

2) To obtain the lock on the sharable resource, we must use acquire()


Syntax: lockobj.acquire()

Once current object acquire the lock, other thread objects are made
wait until curent thread object releases the lock.

3) To un-lock the sharable resource/current object, we must use


release()

Syntax: lockobj.release()

Once current object releases the lock, other objects are permitted
into shrable resource. This process of aquiring and releasing the lock
will be continued until all the objects completed their execution.
========================================================
#nonlock-FunEx.py
-------------------
import threading,time
def table(n):
if(n<=0):
print("{} in valid input:".format(n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,n))
print("-"*50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
time.sleep(0.5)
print("-"*50)

#main program
t1=threading.Thread(target=table,args=(4,))
t2=threading.Thread(target=table,args=(14,))
t3=threading.Thread(target=table,args=(-9,))
t4=threading.Thread(target=table,args=(19,))
Multi Threading in Python
t1.start()
t2.start()
t3.start()
t4.start()
========================================================
#lock-FunEx.py
-------------------
import threading,time
def table(n):
L.acquire() # Get the lock
if(n<=0):
print("{} in valid input:".format(n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,n))
print("-"*50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
time.sleep(0.5)
print("-"*50)
L.release() # release the lock

#main program
#Create an object Lock class
L=threading.Lock() # Here L is an object of Lock class and it is
global variable
t1=threading.Thread(target=table,args=(4,))
t2=threading.Thread(target=table,args=(14,))
t3=threading.Thread(target=table,args=(-9,))
t4=threading.Thread(target=table,args=(19,))
t1.start()
t2.start()
t3.start()
t4.start()
=======================================================
#lock-OopExOnlyEx1.py (Without Inheritance)
----------------------------------------------
import threading,time
class Multable:
def table(self,n):
K.acquire() # Get the lock
self.n=n
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
K.release() # release the lock
Multi Threading in Python
#main program
#Create an object Lock class
K=threading.Lock() # Here K is an object of Lock class and it is
global variable
t1=threading.Thread(target=Multable().table,args=(4,))
t2=threading.Thread(target=Multable().table,args=(14,))
t3=threading.Thread(target=Multable().table,args=(-9,))
t4=threading.Thread(target=Multable().table,args=(19,))
t1.start()
t2.start()
t3.start()
t4.start()
====================================================================
#lock-OopExOnlyEx2.py (Without Inheritance)
----------------------------------------------
import threading,time
class Multable:
@classmethod
def getlock(cls):
cls.K=threading.Lock() # Here K is an object of Lock
class and it is Class Level Variable

def table(self,n):
self.K.acquire() # Get the lock
self.n=n
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
Multable.K.release() # release the lock

#main program
Multable.getlock()
t1=threading.Thread(target=Multable().table,args=(14,))
t2=threading.Thread(target=Multable().table,args=(8,))
t3=threading.Thread(target=Multable().table,args=(-16,))
t4=threading.Thread(target=Multable().table,args=(23,))
t1.start()
t2.start()
t3.start()
t4.start()
-----------------------------------------------------------------------
#nonlock-OopEx1.py (Without Inheritance)
--------------------------------------------
import threading,time
class Multable:
def table(self,n):
self.n=n
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
Multi Threading in Python
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)

#main program
t1=threading.Thread(target=Multable().table,args=(4,))
t2=threading.Thread(target=Multable().table,args=(14,))
t3=threading.Thread(target=Multable().table,args=(-9,))
t4=threading.Thread(target=Multable().table,args=(19,))
t1.start()
t2.start()
t3.start()
t4.start()
=======================================================================
#lock-OopExInhEx1.py (With Inheritance)
-------------------------------------------
import threading,time
class MulTable(threading.Thread):
K=threading.Lock() # Here K is an object of Lock class and it
is Class Level Variable
def setval(self,n):
self.n=n
def run(self):
MulTable.K.acquire()
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thre Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
MulTable.K.release()
#main program
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
t1.setval(4)
t2.setval(14)
t3.setval(-9)
t4.setval(19)
t1.start()
t2.start()
t3.start()
t4.start()
=======================================================================
Multi Threading in Python
#nonlock-OopEx2.py (With Inheritance)
---------------------------------------
import threading,time
class MulTable(threading.Thread):
def setval(self,n):
self.n=n
def run(self):
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)

#main program
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
t1.setval(4)
t2.setval(14)
t3.setval(-9)
t4.setval(19)
t1.start()
t2.start()
t3.start()
t4.start()
======================================================================
Numpy Module in Python

Index
• Purpose of Numpy
• How to use Numpy in Python
• Differences Traditional Python list and ndarray.
• What is ndarray
• Types of arraya: 1) 1-D 2) 2-D 3) N-D
• Number of Approaches to create an object of ndarray.
• Arithmetic Operations on ndarray in numpy.
• Statistical Operations on ndarray in numpy.
• Basic indexing & Slicing Operations on ndarray in numpy.
• Advanced Indexing Advanced Slicing Operations on ndarray in numpy.
• Copy and View on ndarray object in numpy.
• Selecting Elements or Filtering Elements from ndarray in numpy.
• Sorting and Searching Oprtations on ndarray.
Numpy Module in Python

Numpy

Introduction of Numpy:

Numpy stands for NUMerical Python.

Numpy is one of the pre-defined third party module / Library and


numpy module is not a pre-defined module in python Language.

To use numpy as a part of our python program, we must install numpy


module explicitly by using a tool called pip.

Syntax for installing any Module:


pip install module-name

Example: install numpy module


pip install numpy
To use numpy as part of our program, we must import module.
A numpy module is a collection of Variables, Functions and Classes.

History of Numpy:

Numpy was developed by studying existing module called “Numeri


Library” (Origin for development of numpy module)

The Numeric Library was developed by JIM HUNGUNIAN.

The Numeric Library was not able to solve complex maths calculations.

Numpy module developed by TRAVIS OLIPHANT.

Numpy Module developed in the year 2005.

Numpy Module developed in “C” and “Python” Language.


Numpy Module in Python

Advantages of using Numpy

Need of Numpy:

With the revolution of data science, date analysis librarys like Numpy,
SciPy, Scikit, Pandas, etc. have seen a lot of grouth. With a much easier
syntax than other programming languages, Python is the first choice
language for the data scientist.

Numpy provides a convenient and efficient way to handle the vast


amount of data. Numpy is also very convenient with Matrix Operations
and data reshaping. Numpy is fast which makes it reasonable to work
with a large set of data.

The advantages of Numpy Programming are:

1) With Numpy Programming, we can deal with array such 1-D, 2-D & N-D.
2) Numpy maintains minimum memory for large sets of data.
3) Numpy provides Fast in performing operation because internally it’s data
is available at same address.
4) Numpy performs array-oriented computing.
5) It efficiently implements the multidimentional arrays.
6) It perform scientific computations.
7) It is capable of performing reshaping the data stored in multidimentional
array.
8) Numpy provides many in-built functions for various complex
mathematical operations such as statistical, financial, trigonometric
operations etc.
Numpy Module in Python

Python Traditional list VS Numpy Module

Similarities of Python traditional list vs Numpy Module:


An object of list used to store multiple values of same type or different
type and both types (unique + duplicates) in single object.

In Numpy programming, the data is organised in the object of “ndarray”


which is one of the pre-defined class in Numpy Module. Hance an object of
ndarray can store same type or different type and both types (unique +
duplicates) in single object.

The objects of ndarray and list are mutable (changes can takes place).

Differences between Python traditional list vs ndarray object of Numpy


Module:

An object of list contains both homogeneous and heterogeneous values


where as an object of ndarray of Numpy can store only similar type of
values (even we store different values, internally they are treated as
similar type type by treating all values of type “object” ).

On the object of list, we can’t perform Vector Operations. Where as on the


object of ndarray, we can perform.

In large smpling of data, list based applications takes more memory space
whereas ndarray object takes less memory space.

List based application are not efficient because list object values takes
more time to extract or retrieve (they are available a different address)
where as Numpy based applications are efficient because of ndarray
object values takes less time to extract or retrieve (they are avalibale ar
same Address).

List object can’t perform complex matemetical operations where as an


object of ndarray can perform complex mathematical operations.
Numpy Module in Python

Number of approaches to create an object of ndarray

In numpy programming, we have 7 approaches to create an object of


ndarray. They are:
1) array() 2) arange() 3) zeros() 4) ones()
5) full() 6) eye() 7) identity

1) array(): This function is used for converting traditional Python object into
ndarray object.

Syntax: varname = numpy.array(object,dtype)

Here varname is an object of <class, ndarray>

Here array() is predefined function of numpy modele used for converting


traditional Python objects inot ndarray object.

Object represent s any traditional Python objects.

Dtype represents any numpy data type such as int8, int16, int32, float16,
float 32, float64, U64, U5….etc.

Examples:
--------------
>>> import numpy as np
>>> l1=[10,20,30,40,50,60]
>>> print(l1,type(l1))-----------------[10, 20, 30, 40, 50, 60] <class
'list'>
>>> a=np.array(l1)
>>> print(a,type(a))----------------[10 20 30 40 50 60] <class
'numpy.ndarray'>
>>> t=(10,20,30,40,50,60,70)
>>> print(t,type(t))--------------(10, 20, 30, 40, 50, 60, 70) <class
'tuple'>
>>> a=np.array(t)
>>> print(a,type(a))--------------[10 20 30 40 50 60 70] <class
'numpy.ndarray'>
>>> d1={10:1.2,20:4.5,30:6.7}
>>> a=np.array(d1)
>>> a----array({10: 1.2, 20: 4.5, 30: 6.7}, dtype=object)
-----------------------------------------------------------------------
Numpy Module in Python
>>> t=(10,20,30,40,50,60)
>>> a=np.array(t)
>>> a--------------array([10, 20, 30, 40, 50, 60])
>>> a.ndim------------1
>>> a.dtype----------dtype('int32')
>>> a.shape-------------(6,)
>>> b=a.reshape(3,2)
>>> c=a.reshape(2,3)
>>> b--------------
array([[10, 20],
[30, 40],
[50, 60]])
>>> c
array([[10, 20, 30],
[40, 50, 60]])
>>> print(b,type(b))
[[10 20]
[30 40]
[50 60]] <class 'numpy.ndarray'>
>>> print(c,type(c))
[[10 20 30]
[40 50 60]] <class 'numpy.ndarray'>
>>> b.ndim-------------2
>>> c.ndim------------2
>>> b.shape---------------(3, 2)
>>> c.shape-------------(2, 3)
>>> d=a.reshape(3,3)-------ValueError: cannot reshape array of size 6
into shape (3,3)
-----------------------------------------------------------------------
>>> t1=((10,20),(30,40))
>>> print(t1,type(t1))--------------((10, 20), (30, 40)) <class
'tuple'>
>>> a=np.array(t1)
>>> a
array([[10, 20],
[30, 40]])
>>> a.ndim----------2
>>> a.shape----------(2, 2)
-----------------------------------------------------------------------
>>> t1=( ((10,20,15),(30,40,25)),( (50,60,18),(70,80,35) ))
>>> print(t1,type(t1))
(((10, 20, 15), (30, 40, 25)), ((50, 60, 18), (70, 80, 35))) <class
'tuple'>
>>> a=np.array(t1)
>>> a
array([[[10, 20, 15],
[30, 40, 25]],

[[50, 60, 18],


[70, 80, 35]]])
>>> print(a)
[[[10 20 15]
[30 40 25]]

[[50 60 18]
[70 80 35]]]
Numpy Module in Python
>>> a.ndim
3

>>> a.shape
(2, 2, 3)
>>> b=a.reshape(4,3)
>>> b
array([[10, 20, 15],
[30, 40, 25],
[50, 60, 18],
[70, 80, 35]])
>>> c=a.reshape(3,4)
>>> c
array([[10, 20, 15, 30],
[40, 25, 50, 60],
[18, 70, 80, 35]])
>>> d=a.reshape(3,2,2)
>>> d
array([[[10, 20],
[15, 30]],

[[40, 25],
[50, 60]],

[[18, 70],
[80, 35]]])
>>> d[0]
array([[10, 20],
[15, 30]])
>>> d[1]
array([[40, 25],
[50, 60]])
>>> d[2]
array([[18, 70],
[80, 35]])
=============================================================
2) arange(): arrange() always create an object of ndarray in 1-D array only
but not possible to create directly 2-D and multi-dimentional arrays.

To xreate 2-D and multi-dimentional arrays, we must use reshape() or


shape attribute.

Syntax1: varname = numpy.arange(value)


Syntax2: varname = numpy.arange(start,stop)
Syntax3: varname = numpy.arange(start,stop,step)

Here varname is an object of <class, ndarray>


Numpy Module in Python

Syntax1: Creates an object of adarray with the values from 0 to value-1.


Syntax2: Creates an object of adarray with the values from start to stop-1.
Syntax3: Creates an object of adarray with the values from start to stop-1
with equal interval of value step.

Examples:
-------------
>>> import numpy as np
>>> a=np.arange(10)
>>> a-----------array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.ndim--------1
>>> a=np.arange(50,62)
>>> print(a,type(a))---[50 51 52 53 54 55 56 57 58 59 60 61] <class
'numpy.ndarray'>
>>> a.ndim------1
>>> a=np.arange(10,23,2)
>>> a-----array([10, 12, 14, 16, 18, 20, 22])
>>> a=np.arange(10,22,2)
>>> a--------array([10, 12, 14, 16, 18, 20])
>>> b=a.reshape(2,3)
>>> c=a.reshape(3,2)
>>> b-----
array([[10, 12, 14],
[16, 18, 20]])
>>> c
array([[10, 12],
[14, 16],
[18, 20]])
>>> b.ndim------ 2
>>> c.ndim------- 2
>>> b.shape-----(2, 3)
>>> c.shape-----(3, 2)
>>> l1=[ [[10,20],[30,40]], [[15,25],[35,45]] ]
>>> l1----------[[[10, 20], [30, 40]], [[15, 25], [35, 45]]]
>>> a=np.arange(l1)----------TypeError: unsupported operand type(s) for
-: 'list' and 'int'
=============================================================
3) zeros(): This function is used for buildind zero matrix either with 1-D or
2-D or N-D.

Syntax: varname = numpy.zeros(shape,dtype)

Here shape can be 1-D(number of zeros) or 2-D(Rows,Colms) or N-


D(number of matrices , number of rows, number of columns)
Numpy Module in Python

Examples:
-------------
>>> import numpy as np
>>> a=np.zeros(12)
>>> a-----------array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> a=np.zeros(12,dtype=int)
>>> a------------array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> a.reshape(3,4)
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> a.reshape(4,3)
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a.reshape(6,2)
array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]])
>>> a.reshape(2,6)
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])

>>> a.reshape(2,2,2,2)------ValueError: cannot reshape array of size 12


into shape (2,2,2,2)
>>> a.reshape(3,2,2)
array([[[0, 0],
[0, 0]],

[[0, 0],
[0, 0]],

[[0, 0],
[0, 0]]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])
Numpy Module in Python
>>> a.reshape(2,2,3)
array([[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]]])
-----------------------------------------------------------------------
>>> import numpy as np
>>> a=np.zeros((3,3),dtype=int)
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((2,3))
>>> a
array([[0., 0., 0.],
[0., 0., 0.]])
>>> a=np.zeros((2,3),int)
>>> a
array([[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((3,2,3),dtype=int)
>>> a
array([[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]]])
>>> print(a,type(a))
[[[0 0 0]
[0 0 0]]

[[0 0 0]
[0 0 0]]

[[0 0 0]
[0 0 0]]] <class 'numpy.ndarray'>
=============================================================
4) ones(): This function is used for building ONEs matrix either with 1-D or
2-D or N-D.

Syntax: varname = numpy.ones(shape, dtype)

Here shape can be 1-D (number of zeros) or 2-D (Rows,Colms) or N-D


(number of matrices , number of rows, number of columns).
Numpy Module in Python

Examples:
-------------
>>> import numpy as np
>>> a=np.ones(10)
>>> print(a,type(a))----------[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] <class
'numpy.ndarray'>
>>> a=np.ones(10,dtype=int)
>>> print(a,type(a))-------------[1 1 1 1 1 1 1 1 1 1] <class
'numpy.ndarray'>
>>> a.shape-----------(10,)
>>> a.shape=(5,2)
>>> a
array([[1, 1],
[1, 1],
[1, 1],
[1, 1],
[1, 1]])
>>> a.ndim-------------- 2
>>> a.shape------------ (5, 2)
>>> a.shape=(2,5)
>>> a
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
>>> a.shape----------------------(2, 5)
>>>
>>> a=np.ones((3,4),dtype=int)
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> a=np.ones((4,3),dtype=int)
>>> print(a,type(a))
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]] <class 'numpy.ndarray'>
>>> a.shape----------(4, 3)
>>> a.shape=(3,2,2)
>>> a
array([[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]]])
Numpy Module in Python
>>> a=np.ones((4,3,3),dtype=int)
>>> a
array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],

[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],

[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],

[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]])

>>> a[0][0][0]-----------1
>>> a[0,0,0]-----------1
>>> a[0][0,0]------------1
=============================================================
5) full(): This is function is used building a matrix by specifying fill value
either 1-D or 2-D or N-D.

Syntax: varname = numpy.full(shape, fill_value,dtype)

Varname is an object of <class, numpy.ndarray>


Here shape can be 1-D (number of zeros) or 2-D (Rows,Colms) or N-D
(number of matrices , number of rows, number of columns).

Examples:
--------------
>>> a=np.full(3,1)
>>> a---------array([1, 1, 1])
>>>print(type(a))--------<class,numpy.ndarray>
>>> a=np.full(3,9)
>>> a------------array([9, 9, 9])
>>> a=np.full(6,8)
>>> a-------------array([8, 8, 8, 8, 8, 8])
>>> a.shape=(3,2)
>>> a
array([[8, 8],
[8, 8],
[8, 8]])
>>> a=np.full(6,9)
>>> a----------array([9, 9, 9, 9, 9, 9])
>>> a.reshape(2,3)
array([[9, 9, 9],
[9, 9, 9]])
Numpy Module in Python
>>> a=np.full((3,3),9)
>>> a
array([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])
>>> a=np.full((2,3),6)
>>> a
array([[6, 6, 6],
[6, 6, 6]])
>>> a.reshape(3,2)
array([[6, 6],
[6, 6],
[6, 6]])
>>> a=np.full((3,3,3),7)
>>> a
array([[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],

[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],

[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]]])
=============================================================
6) eye(): This function is used for building identity matrix or unit matrix.

Syntax: varname = numpy.eye(N, M=None, K=0, dtype)

Here N represents number of Rows.


Here M represents number of Columns

If we don’t represent M value then N value will be taken as M value and


prepared Square Unit Matrix.

Here K represents Principle diagonal element. If K=0 then it always points


principle diagonal.

If K=-1, -2, -3,…-n represents Bellow Principle Diagonal elememts.


If K= 1, 2, 3,…n represents Above Principle Diagonal elememts.
Numpy Module in Python

Examples:
--------------
>>> import numpy as np
>>> #varname=numpy.eye(N,M=None,K=0,dtype
>>> a=np.eye(3)
>>> print(a,type(a))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] <class 'numpy.ndarray'>
>>> a=np.eye(3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(4,3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]
[0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,k=-1,dtype=int)
>>> print(a,type(a))
[[0 0 0 0]
[1 0 0 0]
[0 1 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-1,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-2,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]] <class 'numpy.ndarray'>
Numpy Module in Python
>>> a=np.eye(5,6,k=-3,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-4,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=1,dtype=int)
>>> print(a,type(a))
[[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=2,dtype=int)
>>> print(a,type(a))
[[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]
[0 0 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=3,dtype=int)
>>> print(a,type(a))
[[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]
[0 0 0 0 0 0]
[0 0 0 0 0 0]] <class 'numpy.ndarray'>
=============================================================
7) identity(): This function always build Identity or unit matrix.

Syntax: varname = numpy.identity (N, dtype)

Here N represents either we can take Rows or Columns and PVM takes as
NXN Matrix (Square Matrix – Unit or Identity)
Numpy Module in Python

Examples:
--------------
>>> import numpy as np
>>> a=np.identity(3,dtype=int)
>>> print(a,type(a))-------------
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.identity(5,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]] <class 'numpy.ndarray'>
=============================================================

Numpy (Arithmatic Operations)

On objects of ndarray, we can apply all types of arithmetic Operations.


To perform arithmetic Operations on the objects of ndarray in numpy
programming, we use the following functions.

a) add() b) subtract() c) multiply() d) dot() or matmul() e) divide()


f) floor_divide() g) mod() h) power()

All the arithmetic functions can also be perform w.r.t arithmetic Operators.

a) add(): This function is used for adding elements of ndarrayobj1,


ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.add(ndarrayobj1, ndarrayonj2)


Numpy Module in Python

Examples:
-------------
>>> l1=[ [10,20],[30,40] ]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.add(a,b)
>>> c
array([[11, 22],
[33, 44]])
-----------------------------------------------------------------------
>>> x=np.array([[1,2,3],[4,5,6]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> y=np.array([4,4,4])
>>> y
array([4, 4, 4])
>>> z=x+y
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> z=np.add(x,y)
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> k=np.array([[2,3],[4,5]])
>>> k
array([[2, 3],
[4, 5]])
>>> kvr=np.add(x,k)----ValueError: operands could not be broadcast
together with shapes (2,3)
(2,2)
-----------------------------------------------------------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=a+b # we used operator + instead of add()
>>> c
array([[11, 22],
[33, 44]])
Numpy Module in Python

=============================================================
b) subtract(): This function is used to subtracting elements of ndarrayobj1,
ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.subtract(ndarrayobj1, ndarrayobj2)

Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.subtract(a,b)
>>> c
array([[ 9, 18],
[27, 36]])
-----------------------------------
>>> d=a-b # we used operator - instead of subtract()
>>> d
array([[ 9, 18],
[27, 36]])
============================================================
c) multiply(): This function is used for performing element-wise
multiplicaton of ndarrayobj1, ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.multiply(ndarrayobj1, ndarrayobj2)

Examples:
--------------
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
Numpy Module in Python
>>> c=np.multiply(a,b)
>>> c
array([[ 5, 12],
[12, 12]])
-----------------------------------------------
>>> e=a*b # we used operator * instead of multiply()
>>> e
array([[ 5, 12],
[12, 12]])
=============================================================
d) dot() or matmul(): This function is used for performing actual matrix
multiplication of ndarrayobj1, ndarrayobj2 and result can be displayed.

To perform Matirx Multiplication, we use dot()

Syntax: varname = numpy.dot(ndarrayobj1, ndarrayobj2)


Varname = numpy.matmul(ndarrayobj1, ndarrayobj2)

Examples:
-------------
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> d=np.dot(a,b)
>>> d
array([[13, 12],
[31, 30]])

(OR)

>>> d=np.matmul(a,b)
>>> d
array([[13, 12],
[31, 30]])
=============================================================
Numpy Module in Python

e) divide(): This fuction is used for preforming element-wise division of


ndarrayobj1, ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.divide(ndarrayobj1, ndarrayobj2)

Examples:
--------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.divide(a,b)
>>> c
array([[10., 10.],
[10., 10.]])
---------------------------------------------------------------
>>> d=a/b # we used operator / instead of divide()
>>> d
array([[10., 10.],
[10., 10.]])
=============================================================
f) floor_divide(): This function is used for performing element-wise floor
division of ndarrayobj1, ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.floor_divide(ndarrayobj1, ndarrayobj2)

Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.floor_divide(a,b)
>>> c
array([[10, 10],
[10, 10]])
---------------------------------------------------------------
Numpy Module in Python
>>> d=a//b # we used operator // instead of floor_divide()
>>> d
array([[10, 10],
[10, 10]])
============================================================
g) mod(): This function is used for performing element-wise modulo
division of ndarrayobj1, ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.mod(ndarrayobj1, ndarrayobj2)

Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.mod(a,b)
>>> c
array([[0., 0.],
[0., 0.]])
-----------------------------------------------------------------------
=>We can also do with operator %
>>> e=a%b
>>> e
array([[0, 0],
[0, 0]], dtype=int32)
============================================================
Numpy Module in Python

h) power(): This function is used for performing element-wise exponential


of ndarrayobj1, ndarrayobj2 and result can be displayed.

Syntax: varname = numpy.power(ndarrayobj1, ndarrayobj2)

Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>>c=np.power(a,b)
>>>print(c)
array([[ 10, 400],
[ 27000, 2560000]],
--------------------------------------------
>>> f=a**b # Instead of using power() we can use ** operator
>>> f
array([[ 10, 400],
[ 27000, 2560000]], dtype=int32)
=============================================================

Numpy (Statistical Operation)

On th object of ndarray, we can perform the following Operations:


a) amax() b) amin() c) mean() d) medial() e) var() f) std()

These Operations we can perform on the entire matrix and we can also
perform on column-wise(axis=0) ans row-wise(axis=1).
Numpy Module in Python

a) amax(): This functions obtains maximum element of the entire matrix.

Syntax1: varname = numpy.amax(ndarrayobject)


Syntax2: varname = numpy.amax(ndarrayobject, axis=0)
Obtains max elements on the basis of columns.
Syntax3: varname = numpy.amax(ndarrayobject, axis=1)
Obtains max elements on the basis of Rows.

Examples:
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> max=np.amax(A)
>>> cmax=np.amax(A,axis=0)
>>> rmax=np.amax(A,axis=1)
>>> print("Max element=",max)-----------Max eleemnt= 4
>>> print("Column Max eleemnts=",cmax)---Column Max eleemnts= [4 4 3]
>>> print("Row Max eleemnts=",rmax)---Row Max eleemnts= [3 4 4]
============================================================
b) amin(): This function obtains minimum element of the entire matrix.

Syntax1: varname = numpy.amin(ndarrayobject)


Syntax2: varname = numpy.amin(ndarrayobject, axis=0)
Obtains min elements on the basis of columns.
Syntax3: varname = numpy.amin(ndarrayobject, axis=1)
Obtains min elements on the basis of Rows.
Examples:
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> min=np.amin(A)
>>> cmin=np.amin(A,axis=0)
>>> rmin=np.amin(A,axis=1)
>>> print("Min eleemnt=",min)---Min eleemnt= 1
>>> print("Column Min eleemnts=",cmin)---Column Min eleemnts= [1 2 1]
>>> print("Row Min eleemnts=",rmin)---Row Min eleemnts= [1 1 2]
=============================================================
Numpy Module in Python

c) mean(): This function used for calculate mean of the total matrix elements.

The formula for mean = (sum of all elements of matrix)/ total number of
elements.

Syntax1: varname = numpy.mean(ndarrayobject)


Syntax2: varname = numpy.mean(ndarrayobject, axis=0)
Obtains mean of elements on the basis of columns.
Syntax3: varname = numpy.mean(ndarrayobject, axis=1)
Obtains mean of elements on the basis of Rows.
Examples:
--------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> m=np.mean(A)
>>> cm=np.mean(A,axis=0)
>>> rm=np.mean(A,axis=1)
>>> print("Mean=",m)---------Mean= 2.4444444444444446
>>> print("Column Mean=",cm)-----Column Mean= [2.66666667 2.66666667 2. ]
>>> print("Row Mean=",rm)---Row Mean= [ 2. 2.33333333 3. ]
=============================================================
d) median(): This function is used for calculating / obtaining medial of entire
matrix elements.

Median as nothing but sorting the given data in ascending order and select
middle element.

If the number sorted elements are odd then center or middle element
become median.

If the number sorted elements are even then center or middle element of
two elements, add them and divide by 2 and that result becomes median.
Numpy Module in Python

Syntax1: varname = numpy.median(ndarrayobject)


Syntax2: varname = numpy.median(ndarrayobject, axis=0)
Obtains median of elements on the basis of columns.
Syntax3: varname = numpy.median(ndarrayobject, axis=1)
Obtains median of elements on the basis of Rows.
Examples:
--------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> md=np.median(A)
>>> cmd=np.median(A,axis=0)
>>> rmd=np.median(A,axis=1)
>>> print("Median=",md)----Median= 2.0
>>> print("Column Median=",cmd)---Column Median= [3. 2. 2.]
>>> print("Row Median=",rmd)------Row Median= [2. 2. 3.]
>>> l1=[[2,3],[4,1]]
>>> A=np.array(l1)
>>> print(A)
[[2 3]
[4 1]]
>>> md=np.median(A)
>>> cmd=np.median(A,axis=0)
>>> rmd=np.median(A,axis=1)
>>> print("Median=",md)---Median= 2.5
>>> print("Column Median=",cmd)---Column Median= [3. 2.]
>>> print("Row Median=",rmd)---Row Median= [2.5 2.5]
=============================================================
e) var(): Variance = sqrt(mean-xi) / total number of elements.
Here ‘ xi ’ represents each elements of matrix.

Syntax1: varname = numpy.var(ndarrayobject)


Syntax2: varname = numpy.var(ndarrayobject, axis=0)
Obtains varience of elements on the basis of columns.
Syntax3: varname = numpy.var(ndarrayobject, axis=1)
Obtains varience of elements on the basis of Rows.
Numpy Module in Python

Examples:
--------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)----Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556
0.88888889
0.66666667]
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556
0.66666667]
============================================================
f) std(): standard deviation = sqrt(var)

Syntax1: varname = numpy.std(ndarrayobject)


Syntax2: varname = numpy.std(ndarrayobject, axis=0)
Obtains std. dev of elements on the basis of columns.
Syntax3: varname = numpy.std(ndarrayobject, axis=1)
Obtains std. dev of elements on the basis of Rows.
Examples:
-------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)---Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556
0.88888889
0.66666667]
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556
0.66666667]
-----------------------------------------------------------------------
Numpy Module in Python

>>> sd=np.std(A)
>>> csd=np.std(A,axis=0)
>>> rsd=np.std(A,axis=1)
>>> print("std=",sd)---std= 1.0657403385139377
>>> print(" column std=",csd)--- column std= [1.24721913 0.94280904
0.81649658]
>>> print("Row std=",rsd)--Row std= [0.81649658 1.24721913 0.81649658]
=================================X=====================================

NOTE:
----------
>>> import statistics
>>> l=[10,20,10,30,40,10,50,10]
>>> statistics.mode(l)
10
>>> l=[10,20,10,30,40,10,50,10,20,20,20]
>>> statistics.mode(l)
10
>>> l=[20,10,10,30,40,10,50,10,20,20,20]
>>> statistics.mode(l)
20
>>> statistics.multimode(l)
[20, 10]
>>> l=[20,10,10,30,40,10,50,10,20,20,20,10]
>>> statistics.multimode(l)
[10]
>>>
=============================================================

Numpy (Basic Indexing)

If we want to access single element of 1-D, 2-D and N-D arrays we must use
the concept of Basic Indexing.

Accessing Single Element 1-D array:

Syntax: ndarraynem [index]

Here ‘index’ can be either +ve or –ve.


Numpy Module in Python

Examples:
>>> a=np.array([10,20,30,40,50,60])
>>> a
array([10, 20, 30, 40, 50, 60])
>>> a[0]
10
>>> a[3]
40
============================================================
Accessing single Element of 2-D:

Syntax: ndarrayobj [row index, column index]

Examples:
>>>import numpy as np
>>> a=np.array([10,20,30,40,50,60])
>>> b=a.reshape(2,3)
>>> b
array([[10, 20, 30],
[40, 50, 60]])
>>> b[0,0]
10
>>> b[0,1]
20
>>> b[1,2]
60
=============================================================
Accessing single Element of 3-D:

Syntax: ndarrayobj [index of matrix, row index, column index]

Examples:
>>> a=np.array([10,20,30,40,50,60,70,80])
>>> b=a.reshape(2,2,2)
>>> b
array([[[10, 20],
[30, 40]],

[[50, 60],
[70, 80]]])

>>> b[0,0,0]-----------10
>>> b[-1,0,0]---------50
>>> b[-2,1,1]---------40
============================================================
Numpy Module in Python

Numpy (Indexing and Slicing Operations of 1-D, 2-D and 3-D array)

1-D array slicing:

Syntax: 1dndarray [begin:end:step]

Examples:
-------------
>>> a=np.array([10,20,30,40,50,60,70])
>>> a------------array([10, 20, 30, 40, 50, 60, 70])
>>> a[::-1]-----------array([70, 60, 50, 40, 30, 20, 10])
>>> a[::]-----------array([10, 20, 30, 40, 50, 60, 70])
============================================================
2-D array slicing:

Syntax: ndarrayobj[ i , j ]
Here ‘ i ’ represents row index.
Here ‘ j ’ represents column index.
Syntax: 2darrayobj[row index, column index]
Syntax: 2darrayobj[begin:end:step , begin:end:step]

Examples:
--------------
>>> a=np.array([[10,20,30],[40,50,60]])
>>> a
array([[10, 20, 30],
[40, 50, 60]])
>>> a[0,0]
10
>>> a[0:,0:1]
array([[10],
[40]])
>>> a[0:,1:2]
array([[20],
[50]])
>>> a[1:,:]
array([[40, 50, 60]])
=============================================================
Numpy Module in Python

3-D array Slicing:

Syntax: 3dndarrayobj [ i , j , k]
Here ‘ i ’ represents which 2-D matrix (Matrix number---0 1 2 3 …)
Here ‘ j ’ represents which rows in that 2-D matrix.
Here ‘ k ’ represents which column in that 2-D matrix.
OR
3dndarrayobj [ matrix index, row index, column index]
OR
3dndarrayobj [ begin:end:step , begin:end:step , begin:end:step ]

Examples:
-------------
>>> lst=[ [ [1,2,3],[4,5,6],[7,8,9] ],[
[13,14,15],[16,17,18],[19,20,21] ] ]
>>> print(lst)
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[13, 14, 15], [16, 17, 18], [19,
20, 21]]]
>>> arr2=np.array(lst)
>>> print(arr2)
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]

[[13 14 15]
[16 17 18]
[19 20 21]]]
>>> arr2.ndim
3
>>> arr2.shape
(2, 3, 3)
>>> arr2[:,:,0:1]
array([[[ 1],
[ 4],
[ 7]],

[[13],
[16],
[19]]])
>>> arr2[:,:,:1]
array([[[ 1],
[ 4],
[ 7]],

[[13],
[16],
[19]]])
Numpy Module in Python
>>> arr2[: , 0:2, 1:3]
array([[[ 2, 3],
[ 5, 6]],

[[14, 15],
[17, 18]]])
>>> arr2[: , :2, 1:]
array([[[ 2, 3],
[ 5, 6]],

[[14, 15],
[17, 18]]])
=============================================================

Numpy (Advanced Indexing)

If we want to access multiple elements, which are not in order (arbitrary


elements) of 1D, 2D and N-D arrays we must use the concept of Advanced
Indexing.

If we want to access the elements based on some condition then we can’t


use basic indixing and basic slicing operatons. To fullfill such type of
requirements we must use advanced indexing.

Accessing Multiple Arbitary Elements (1D):

Syntax: ndarray [x]

Here ‘x’ can be either ndarray or list which represents required indexes of
arbitrary elements.

Examples:
--------------
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
#access 10 30 and 80 elements
# here indexes of 10 30 and 80 are 0 2 7
>>>lst=[0,2,7] here [0,2,7] are indexes of 10 30 and 80
>>> indexes=np.array(lst) # here lst converted into ndarray object
>>> print(indexes)---------[0 2 7]
Numpy Module in Python
>>> print(a[indexes])--------------[10 30 80]
(OR)
>>> ind=[0,2,7] # prepare the list of indexes of arbitray
elements(10,30,80) of ndarray and pass to ndarray
>>> print(a[ind]) -----------[10 30 80]

Examples:
---------------------
Q1-->Access 20 30 80 10 10 30
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
>>> ind=[1,2,7,0,0,2] # [1,2,7,0,0,2] are the indexes of 20 30 80 10 10
30
>>> print(a[ind])----------------[20 30 80 10 10 30]
===========================================================
Accessing Multiple Arbitary Elements (2D):

Syntax: ndarrayobj [ [row index] , [column index] ]

Examples:
-------------
>>>import numpy as np
>>>mat=np.array([ [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16] ] )
>>> print(mat)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

Q1) Access the principle diagnal elements 1 6 11 16

Ans:- mat[ [0,1,2,3],[0,1,2,3] ]


=>When the above statement is executed, The PVM takes internally as
mat[ (0,0), (1,1), (2,2),(3,3) ]-------- 1 6 11 16

>>> mat[ [0,1,2,3],[0,1,2,3] ]-----------array([ 1, 6, 11, 16])

Q2) Access the elements 6 14


Ans: mat[ [1,3] , [1,1] ]
=>When the above statement is executed, The PVM takes internally as
mat[ (1,1),(3,1) ]

>>> mat[[1,3],[1,1]]-----------array([ 6, 14])


=============================================================
Numpy Module in Python

Accessing Multipe Arbitary Elements (3D):

Syntax: ndarray [ [ index of 2Dmatrix] , [row indexs] , [column index] ]

Examples:
--------------
>>>import numpy as np
>>>l1=[ [ [1,2,3,4],[5,6,7,8],[9,10,11,12] ],[
[13,14,15,16],[17,18,19,20],[21,22,23,24] ] ]
>>>mat3d=np.array(l1)
>>>print(mat3d)
>>> print(mat3d)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
>>> mat3d.ndim
3
>>> mat3d.shape
(2, 3, 4)
----------------------------------------
Q1) Access the elements 1 14 24
Ans:- mat3d[ [0,1,1], [0,0,2], [0,1,3] ]

When the above statement is executed, Internally PVM takes as follows.


=>mat3d[ (0,0,0),(1,0,1),(1,2,3) ]-Gives-->1 14 24

Q1) Access the elements 10 16


>>> mat3d[[-2,-1],[-1,-3],[-3,-1]]----------array([10, 16])
====================================================
OR
====================================================
>>> l1=[ [ [1,2,3,4],[5,6,7,8],[9,10,11,12] ],[
[13,14,15,16],[17,18,19,20],[21,22,23,24] ] ]
>>> a=np.array(l1)
>>> a
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],

[[13, 14, 15, 16],


[17, 18, 19, 20],
[21, 22, 23, 24]]])
>>> #ndarrayobj[ [MatrixIndex],[Row Index],[Col Index] ]---Syntax
>>> #ndarrayobj[ [MatrixIndex],[Row Index],[Col Index] ]
>>> #access 1,8,13,20
>>> matind=(0,0,1,1)
>>> rowind=(0,1,0,1)
>>> colind=(0,3,0,3)
>>> a[matind,rowind,colind]
Numpy Module in Python
array([ 1, 8, 13, 20])
>>> a[ [0,0,0,1,1,1],[0,1,2,0,1,2],[0,1,2,0,1,2] ]
array([ 1, 6, 11, 13, 18, 23])
===========================X==========================================

a=np.array([10,20,30,40,50,60,70,80,15,25,35,45,55,65,75,85])
print(a)

a.shape=(2,2,2,2)
print(a)
[[[[10 20]
[30 40]]

[[50 60]
[70 80]]]

[[[15 25]
[35 45]]

[[55 65]
[75 85]]]]

#access 10 from a---4-D


a[0][0][0][0]------------10
# access 10 and 40 from a---4D
a[[0,0],[0,0],[0,1],[0,1]]----array([10, 40])
# access 60,55 and 15 from a---4D
a[ [0,1,1],[1,1,0],[0,0,0],[1,0,0] ]----array([60, 55, 15])
============================================================

Numpy (Selecting the elements based on condition)

OR (Creating Filter Directly from ndarray)

To select any element from ndarray object, we have two approaches.


They are :

Prepare Boolean Array (It contains True or False). True represents condition
satisfied and False reperesents Condition not satisfied.

Syntax: varname = ndarrayobject with condition


Here varname called Boolean array.
Numpy Module in Python

Pass the Boolean Array to the ndarray object, so that we can get those
elements from ndarray which satisfies with the entry True (or) we can get
those elements from ndarray corresponding True entries of Boolean array.

Syntax: ndarray [Boolean Array]

Approach-1:
In this approach, we directly pass Boolean array values to the ndarray for
getting required elements based on condition.

Syntax: ndarray [ ndarrayobject with condition ]

Examples:
-------------
-----------------------------
Q1) Select the Possitive Elements from ndarray
>>> import numpy as np
>>> l=[10,21,-34,23,-45,30,-40]
>>> print(l)--------------[10, 21, -34, 23, -45, 30, -40]
>>> a=np.array(l)
>>> a------------array([ 10, 21, -34, 23, -45, 30, -40])
>>> b=a>0 # Boolean Array
>>> print(b)----[ True True False True False True False]
>>> a[b]-------array([10, 21, 23, 30])
===================OR=========================
>>> a[ a>0 ]-----------array([10, 21, 23, 30])
-------------------------------------------------------------------
Q2) Select the Negative Elements from ndarray
>>> l=[10,21,-34,23,-45,30,-40]
>>> a=np.array(l)
>>> a---------- array([ 10, 21, -34, 23, -45, 30, -40])
>>> b=a<0 # Boolean Array
>>> b---- array([False, False, True, False, True, False,
True])
>>> a[b]------- array([-34, -45, -40])
=================OR=============
>>> a[a<0]-------------- array([-34, -45, -40])
-----------------------------------------------------------------------
Q3) Select the Even and Odd Elements from ndarray
>>> a=np.array([11,20,33,31,41,47,46,12,13])
>>> a------------------array([11, 20, 33, 31, 41, 47, 46, 12, 13])
>>> a[a%2==0]-----------------array([20, 46, 12])
>>> a[a%2!=0]-----------------array([11, 33, 31, 41, 47, 13])
-----------------------------------------------------------------------
Numpy Module in Python
>>> a=np.array([10,20,30,40,50,60,70,80,90])
>>> b=a.reshape(3,3)
>>> b
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
#Get Multiples of 3
>>> m3=(b%3==0)
>>> m3 #----------------------Boolean array
array([[False, False, True],
[False, False, True],
[False, False, True]])
>>> b[m3]--------------------------array([30, 60, 90])
======================OR===========================
>>> b[b%3==0]-------------------array([30, 60, 90])
============================================================

Numpy Sorting Array

Sorting is nothing arranging the elements in an ordered sequence.


Ordered sequence is any sequence that has an order corresponding to
elements, like numeric or alphanumerical, ascending or decending.
The Numpy ndarray object has a function called sort(), than will sort a
specified array.

Examples:
-------------
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr)) # [0 1 2 3]
----------------------------------------------------
import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr)) # ['apple' 'banana' 'cherry']
-----------------------------------------------------
import numpy as np
arr = np.array([True, False, True])
print(np.sort(arr)) # [False True True]
-------------------------------------------------------
Sorting a 2-D Array
--------------------------------------------------------
If you use the sort() method on a 2-D array, both columns and Rows of
nd array will be sorted.
-------------------
Numpy Module in Python
Examples:
-------------------
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
#output
[[2 3 4]
[0 1 5]]
-----------------------------------------------------------------------
a=np.array([110, 20, -30, 40, 50, 160, 7, 8, 90])
print(a)

np.sort(a)-----------array([-30, 7, 8, 20, 40, 50, 90, 110,


160])
np.sort(a)[::-1]-----array([160, 110, 90, 50, 40, 20, 8, 7, -
30])
a.shape=(3,3)
a-------------------------------array([[110, 20, -30],
[ 40, 50, 160],
[ 7, 8, 90]])

np.sort(a,axis=0) # ColumnWise
array([[ 7, 8, -30],
[ 40, 20, 90],
[110, 50, 160]])
-----------------------------------------------------------
print(a)
array([[110, 20, -30],
[ 40, 50, 160],
[ 7, 8, 90]])

np.sort(a,axis=1) # Row Wise


array([[-30, 20, 110],
[ 40, 50, 160],
[ 7, 8, 90]])
=============================================================

Numpy array Copy Vs View

The difference between Copy and Vies:

The main difference between a copy and a view of an array is that the copy
is a new array, and the view is just a view of the original array.

The copy owns the data and any changes made to the copy will not affect
original array, and any changes made to the original array will not affect the
copy. Modification are independent (Like Shallow Copy).
Numpy Module in Python

Syntax: varname = ndarrayobj . copy()


OR
Ndarrayobj2 = numpy.copy(ndarrayobj1)

The view does not own the data and any changes made to the view will
affect the original array, and any changes made to the original array will
affect the view.

Syntax: varname = ndarrayobj . view()

Copy:

Examples:
--------------
# Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [1 2 3 4 5]

-----------------------------------------------------------------------
NOTE: The copy SHOULD NOT be affected by the changes made to the
original array.
-----------------------------------------------------------------------

VIEW:

Example
-------------
#Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [42 2 3 4 5]
-----------------------------------------------------------------------
NOTE : The view SHOULD be affected by the changes made to the original
array.
-----------------------------------------------------------------------
Numpy Module in Python
# Make Changes in the VIEW:
------------------
Example
------------------
# Make a view, change the view, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr) # [31 2 3 4 5]
print(x) # [31 2 3 4 5]
-----------------------------------------------------------------------
=>In the case append() , view() does not reflect the changes
=============================================================
Pandas Module in Python

Series

It is one-Dimensional Labled Array Capable of Storing / Holding


Homogenious data of any type (Integer, String, float,..Python Objects etc).
The Axis Labels are collectively called Index.

Pandas series is nothing but a column values in excel sheet.

Pandas series values are Mutable.

Pandas series contains Homogenious Data (Internally even we store


different type values, they are treated as object type).

Creating a Series:
A Series object can be created by using the following Syntax:

Syntax: varname = pandas.Series(object, index, dtype)

Explanation:
Here varname is an object of <class, pandas.core.series.Series>

Pandas is a module name. Series() is a predefined function in pandas


module and it is used for creating an object of Series class.

‘object’ can either int, float, complex, bool, str, bytes, byesarray, range, list,
ndarray, dict,… etc…(but not set data type because they are un-orderd).

‘index’ represents the positional values of present Series object. The default
value of index starts from 0 to n-1, here ‘n’ represents total values in Series
object. Programatically we can give our own Index Value.

‘dtype’ represents data type (Ex: int32, int64, float64,…etc)

Examples: Create a series for 10 20 30 40 50 60


Pandas Module in Python

----------------------------------------------------------------------
>>> import pandas as pd
>>> import numpy as np
>>> lst=[10,20,30,40,50,60]
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 20
2 30
3 40
4 50
5 60
dtype: int64 <class 'pandas.core.series.Series'>
----------------------------
>>> lst=[10,20,30,40,50,60]
>>> s=pd.Series(lst,dtype=float)
>>> print(s,type(s))
0 10.0
1 20.0
2 30.0
3 40.0
4 50.0
5 60.0
dtype: float64 <class 'pandas.core.series.Series'>
------------------------------------------------------------------
>>> lst=["Rossum","Gosling","Travis","MCKinney"]
>>> a=np.array(lst)
>>> a ------array(['Rossum', 'Gosling', 'Travis', 'MCKinney'],
dtype='<U8')
>>> print(a, type(a))--['Rossum' 'Gosling' 'Travis' 'MCKinney'] <class
'numpy.ndarray'>
>>> s=pd.Series(a)
>>> print(s,type(s))
0 Rossum
1 Gosling
2 Travis
3 MCKinney
dtype: object <class 'pandas.core.series.Series'>
----------------------------------------------------------------------
>>>lst=[10,"Rossum",34.56,"Author"]
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 Rossum
2 34.56
3 Author
dtype: object <class 'pandas.core.series.Series'>
-----------------------------------------------------------------------

Creating an Series object with Programmer-defined Index


Pandas Module in Python
-----------------------------------------------------------------------
>>> lst=[10,"Rossum",34.56,"Author"]
>>> print(lst)--------[10, 'Rossum', 34.56, 'Author']
>>> s=pd.Series(lst,index=["Stno","Name","Marks","Desg"])
>>> print(s)
Stno 10
Name Rossum
Marks 34.56
Desg Author
dtype: object
>>> print(s["Stno"])-------10
-----------------------------------------------------------------------
>>> lst=["Rossum","Gosling","Travis","MCKinney"]
>>> s=pd.Series(lst,index=[100,200,300,400])
>>> print(s,type(s))
100 Rossum
200 Gosling
300 Travis
400 MCKinney
dtype: object <class 'pandas.core.series.Series'>
-----------------------------------------------------------------------
Creating a Series object from dict:
---------------------------------------------
A dict object can be used for creating a series object.
If we use dict object in Series() then keys can be taken as Series data.

Examples:
-------------
>>> import pandas as pd
>>> d1={"sub1":"Python","sub2":"Java","sub3":"Data
Science","sub4":"ML"}
>>> print(d1)--{'sub1': 'Python', 'sub2': 'Java', 'sub3': 'Data
Science', 'sub4': 'ML'}
>>> s=pd.Series(d1)
>>> print(s)
sub1 Python
sub2 Java
sub3 Data Science
sub4 ML
dtype: object
>>> d2={"RS":2.3,"JG":1.2,"MCK":4.5,"TOLI":2.4}
>>> print(d2)---{'RS': 2.3, 'JG': 1.2, 'MCK': 4.5, 'TOLI': 2.4}
>>> s=pd.Series(d2)
>>> print(s)
RS 2.3
JG 1.2
MCK 4.5
TOLI 2.4
dtype: float64

=============================================================
Pandas Module in Python

DataFrame in Pandas

A Data Frame is 2-Dimentional Data Structure to organised the data.

In otherwords a DataFrame organises the data in the Tabular Format,


which is nothing but Collection of Rows and Columns.

The Columns of DataFrame can be Different DataType or Same DataType.


The size of DataFrame can be mutable.

Number of approaches to create DataFrame

To Create an object of data frame, we use predefined data frame() which


is present in pandas module and returns an object of Data Frame class.
We have 5 ways to create an object of data frame. They are:

a) by using list/tuple.
b) By using dict.
c) By using Series.
d) By using ndarray of numpy.
e) By using CSV Files (comma separated Values).

Syntax for creating an object of DataFrame in Pandas:

Varname = pandas.DataFrame(object, index, columns, dtype)

Explanation:

‘varname’ is an object of <class, ‘pandas.core.dataframe.DataFrame’>

‘pandas.DataFrame()’ is a pre-defined function present in pandas module


and it is used to create an object of DataFrame for storing Data sets.
Pandas Module in Python

‘object’ represents list or tuple or dict or Series or ndarray or csv files.

‘index’ represents Row index and whose default indexing starts from
0, 1, n-1 where n is number of columns.

‘dtype’ represents data type of values of Column value.

a) Creating an object of DataFrame by using list/tuple.


-------------------------------------------------------
>>>import pandas as pd
>>>lst=[10,20,30,40]
>>>df=pd.DataFrame(lst)
>>>print(df)
0
0 10
1 20
2 30
3 40
------------------------------------
lst=[[10,20,30,40],["RS","JS","MCK","TRV"]]
df=pd.DataFrame(lst)
print(df)
0 1 2 3
0 10 20 30 40
1 RS JS MCK TRV
--------------------------------------------
lst=[[10,'RS'],[20,'JG'],[30,'MCK'],[40,'TRA']]
df=pd.DataFrame(lst)
print(df)
0 1
0 10 RS
1 20 JG
2 30 MCK
3 40 TRA
--------------------------------------------------
lst=[[10,'RS'],[20,'JG'],[30,'MCK'],[40,'TRA']]
df=pd.DataFrame(lst, index=[1,2,3,4],columns=['Rno','Name'])
print(df)

Rno Name
1 10 RS
2 20 JG
3 30 MCK
4 40 TRA
-------------------------------------------
tpl=( ("Rossum",75), ("Gosling",85), ("Travis",65),
("Ritche",95),("MCKinney",60) )
df=pd.DataFrame(tpl, index=[1,2,3,4,5],columns=['Name','Age'])
print(df)
Name Age
1 Rossum 75
2 Gosling 85
3 Travis 65
4 Ritche 95
5 MCKinney 60
Pandas Module in Python
-----------------------------------------------------------------------
b) Creating an object DataFrame by Using dict object
--------------------------------------------------------------------
When we create an object of DataFrame by using Dict , all the keys
are taken as Column Names and Values of Value are taken as Data.
-----------------
Examples:
-----------------
>>> import pandas as pd
>>>
dictdata={"Names":["Rossum","Gosling","Ritche","McKinney"],"Subjects":[
"Python","Java","C","Pandas"],"Ages":[65,80,85,55] }
>>> df=pd.DataFrame(dictdata)
>>> print(df)
Names Subjects Ages
0 Rossum Python 65
1 Gosling Java 80
2 Ritche C 85
3 McKinney Pandas 55
>>> df=pd.DataFrame(dictdata,index=[1,2,3,4])
>>> print(df)
Names Subjects Ages
1 Rossum Python 65
2 Gosling Java 80
3 Ritche C 85
4 McKinney Pandas 55
----------------------------------------------------------------------
c) Creating an object DataFrame by Using Series object
----------------------------------------------------------------------
>>> import pandas as pd
>>> sdata=pd.Series([10,20,30,40])
>>> df=pd.DataFrame(sdata)
>>> print(df)
0
0 10
1 20
2 30
3 40
>>>
sdata=pd.Series({"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]})
>>> print(sdata)
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
dtype: object

>>> df=pd.DataFrame(sdata)
>>> print(df)
0
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
Pandas Module in Python

>>> ddata={"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]}
>>> df=pd.DataFrame(ddata)
>>> print(df)
IntMarks ExtMarks
0 10 80
1 20 75
2 30 65
3 40 50
-----------------------------------------------------------------------
d) Creating an object DataFrame by Using ndarray object
----------------------------------------------------------------------
>>> import numpy as np
>>> l1=[[10,60],[20,70],[40,50]]
>>> a=np.array(l1)
>>> df=pd.DataFrame(a)
>>> print(df)
0 1
0 10 60
1 20 70
2 40 50
>>> df=pd.DataFrame(a,columns=["IntMarks","ExtMarks"])
>>> print(df)
IntMarks ExtMarks
0 10 60
1 20 70
2 40 50
-----------------------------------------------------------------------
e) By using CSV File(Comma Separated Values)
-----------------------------------------------------------------
import pandas as pd1
df=pd1.read_csv("C:\rtkdemo\stud.csv")
print("type of df=",type(df)) #type of df= <class
'pandas.core.frame.DataFrame'>
print(df)
--------------------- OUTPUT--------------------
stno name marks
0 10 Rossum 45.67
1 20 Gosling 55.55
2 30 Ritche 66.66
3 40 Travis 77.77
4 50 KVR 11.11
===========================================================
Python DateTime Module
==========================

Python Dates:
--------------------------------
A date in Python is not a data type of its own, but we can import a module named datetime to work with d
ates as date objects.
========================================================
Creating Date Objects:
--------------------------------------------------
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
=====================================================
The strftime() Method:
------------------------------------------------------
The datetime object has a method for formatting date objects into readable strings.

The method is called strftime(), and takes one parameter, format, to specify the format of the returned stri
ng:
=========================================================
Ex1.py
-------
import datetime
x = datetime.datetime.now()
print(x)
--------------------------------------------------------------------
Ex2.py
---------
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
--------------------------------------------------------------------------------------------------------------------------------------
Ex3.py
------------
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
---------------------------------------------------------------------
Ex4.py
--------------
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
---------------------------------------------------------------------
Ex5.py Weekday, short version
-------------------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%a"))
---------------------------------------------------------------
Ex6.py Weekday, full version
--------------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%A"))
-------------------------------------
Ex7.py Weekday as a number 0-6, 0 is Sunday
-------------------------------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%w"))
--------------------------------------------------------
Ex8.py Day of month 01-31
------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%d"))
---------------------------------------
Ex9.py Month Name Short Version
------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%b"))
------------------------------
Ex10.py Month Name Full Version
----------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%B"))
-------------------------------------------
Ex11.py Month as Number 01-12
-----------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%m"))
----------------------------------------------
Ex12.py Year short version
----------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%y"))
--------------------------------------
Ex13.py Year Full Version
--------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%Y"))
-------------------------------------------
Ex14.py AM/PM
------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%p"))
------------------------------------------
Ex15.py To disp a calendar for the month
----------------------------------------------------
# Python program to display calendar of
# given month of the year
# import module
import calendar

yy = 2023
mm = 10

# display the calendar


print(calendar.month(yy, mm))
-----------------------------------------------------------------
Ex16.py
---------------------------
# Python code to demonstrate the working of
# calendar() function to print calendar

# importing calendar module


# for calendar operations
import calendar

# using calendar to print calendar of year


# prints calendar of 2018
print ("The calendar of year 2023 is : ")
print (calendar.calendar(2023))
------------------------------------------------------------------
===================================X===============================
================================
JSON file
================================
=>JSON is a lightweight data format for data interchange which can be easily read and written by humans
, easily parsed and generated by machines. It is a complete language-independent text format. To work w
ith JSON data, Python has a built-in module called json.
=================================================
Parse JSON (Convert from JSON to Python)
-------------------------------------------------------------------------------------
json.loads() method can parse a json string and converted into Python dictionary.
Syntax:
dictobj=json.loads(json_string)

Examples:
---------------------
# Python program to convert JSON to Python
import json
# JSON string
employee = ’ {"id":"09", "name": "Rossum", "department":"IT"} ’
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict)
--------------------------------------------------------------------------------------------------------------------------
Python--- read JSON file
--------------------------------------------------------------------------------------------------------------------------
=>json.load() method can read a file which contains a JSON object.
Consider a file named
employee.json which contains a JSON object.
Syntax:
json.load(file_object)
------------------------------------------------------------------------------------------------------
Ex1:
-----
import json
# JSON string
employee = ’{"id":"09", "name": "Rossum", "department":"IT"}’
print(employee,type(employee))
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict,type(employee_dict))
------------------------------------------------------------------------
Ex2:
------
import json
# JSON string
employee = ’ {"id":"09", "name": "Rossum", "department":"IT"} ’
print("Json String data=",employee)
# Convert string to Python dict
employee_dict = json.loads(employee)
print("Dict Data=",employee_dict)
for k,v in employee_dict.items():
print("{}-->{}".format(k,v))
---------------------------------------------------------------------------------
Ex3:
----------
# Python program to write JSON to a file
#JsonWrite.py
import json
# Data to be written
dictionary ={
"name" : "Rossum",
"rollno" : 56,
"cgpa" : 8.6,
}
with open("C:\\Users\\ritik\\OneDrive\\Desktop\\jsonfile.json","w") as fp:
json.dump(dictionary, fp)
print("Data written to file--verify")
------------------------------------------------------------------------------------------
Ex4:
------------
# Python program to read json file
#JsonRead.py
import json
# Opening JSON file
try:
fp = open("C:\\Users\\ritik\\OneDrive\\Desktop\\jsonfile.json")
# returns JSON object as a dictionary
data = json.load(fp)
# Iterating through the json list
for i,j in data.items():
print("{}--->{}".format(i,j))
except FileNotFoundError:
print("Json File does not exist")
------------------------------------------------------------------------------------

You might also like