0% found this document useful (0 votes)
26 views457 pages

Python by K V Rao - NareshIT HYD

The document provides an overview of Python, including its history, versions, and features. It outlines various real-time applications of Python, such as web development, gaming, artificial intelligence, and data analysis. Additionally, it details Python's characteristics, including its simplicity, open-source nature, and dynamic typing, along with a discussion on data types and variable usage.

Uploaded by

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

Python by K V Rao - NareshIT HYD

The document provides an overview of Python, including its history, versions, and features. It outlines various real-time applications of Python, such as web development, gaming, artificial intelligence, and data analysis. Additionally, it details Python's characteristics, including its simplicity, open-source nature, and dynamic typing, along with a discussion on data types and variable usage.

Uploaded by

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

Python

By K V Rao

NareshIT

Ameerpet, Hyderadad

MYTHRI XEROX
ALL SOFTWARE INSTITUTE MATERIALS AVAILABLE
{ ADD:GAYATHRI NAGAR,SAP STREET,BEHIND HUDA MYTHRIVANAM,AMEERPET}

CELL.7036303535,7995810201

{GOODS ONCE SOLD WILL NOT BE TAKEN BACK}


*PYTHON SOFTWARE*
********************************************

Real Time Applications of Python

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

1) Web Applications Development ---- >


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

1 manojalladi23@[Link]
Getting started with Python
=>History of Python
=>Versions of Python
=>Downloading Process of Python

=>History of Python
=>Python Programming language foundation stone lay in the year 1980.
=>Python Programming language implementation started in the year 1989.
=>Python Programming language officially released in the year 1991 Feb 21.
=>Python Programming language developed By GUIDO VAN ROSSUM.
=>Python Programming language developed at CWI Institute in Nether lands.
=>ABC programming language is the Predecessor of Python Programming language.

=>Versions of Python
=>Python Programming contains two Versions. They are
1) Python 2.x----- Here x ---> 1 2 3 4 5 6 7 -----outdated---
2) Python 3.x----> here x 1 2 3 4 5 4 6 7 8 9 10
=>Python 3.x does not contain backward compatibility with Python 2.x
=>To down load Python 3.x software, we use [Link]
=>Python Software and its updating are maintained by a Non-Commercial Organization called
“Python Software Foundation (PSF)”

Python Programming Inspired from


=>Python Programming Inspired from 4 programming language

1) Functional Programming from C


2) Object Oriented Programming from CPP
3) Scripting Programming from PERL
4) Modular Programming from Modulo3

2 manojalladi23@[Link]
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
5. Interpreted Programming
6. High Level Programming
7. Robust (Strong)
8. Both Procedural and Object Oriented Programming
9. Extensible
10. Embedded
11. Supports Third party APIs---Numpy, Pandas, Scipy, Scikit, matplotlib

1. Simple
=>Python is one of the Simple Programming Language bcoz 3 technical factors.
They are

1) Python Provides Rich Set of APIs (Libraries). So that Python Programmers can Re-Use the
pre-defined Code without writing our own code.
Def of API (Application Programming Interface):

=>An API is a collection of MODULES.


=>A MODULE is a Collection of FUNCTIONS, VARIABLES and CLASSES
Examples: - math, cmath, calendar, random, date time....etc

2) Python Programming Provide In-Built Garbage Collection Facility. So that Garbage Collector
Collects Un-Used Memory Space and Improves Performance of Python Based Applications.
=>Definition of Garbage Collector:

=>A Garbage Collector is one of the in-Built Python Backgrounds which are running behind of
Regular Python Program and whose role is to collect un-used memory and improves the
Performance Python Based Applications.
=>hence Garbage Collector takes about automatic Memory management.

3) Python Provides User-Friendly Syntaxes. So That Python Programmer can develop Error-Free
Programs in limited span of time.

3 manojalladi23@[Link]
2. Freeware and Open Source

Freeware:-

=>If we download any software Freely from Original Source then it is called Freeware.
=>Since we download Python Software Freely from [Link] and hence Python is one of
the Freeware.

Open Source:

=>When we download the python software and whose standard name is "CPYTHON".
=>In Later days, some vendors came forward and Customized CPYTHON for their in house
tools development and such customized versions of CPYTHON and python software is one of
the Open Source and such customized versions of CPYTHON are called Python Distributions.

=>Some of Python Distributions are

1) JPYTHON or JYTHON --- >Used to run Java Based Applications


2) IRON PYTHON or IPYTHON-->Used to run C#.NET Applications
3) RUBY PYTHON --- >Used to run Ruby Based Applications
4) Micro Python-- >Used to develop Micro controller Applications.
5) Stack less Python --- >Used to develop Concurrency Based Applications.
6) PYPY------>Just for using JIT Compiler ... etc

3. Platform Independent
=>Platform is nothing Type of OS Being Used to run the Program/ Application.
=>" A Language is said by Platform Independent if and only if who’s application or programs
runs on every OS"
=>Python is one of the Platform Independent bcoz In Python Programming Execution
Environment "ALL VALUES STORED IN THE FORM OF OBJECTS and Objects is
Independent from OS ".

4. Dynamically Typed Programming


=>In General we have two types of Programming Languages. They are
1) Static Typed Programming language
2) Dynamically Typed Programming language

1) Static Typed Programming language:


=>In This Programming languages, we Must declare the variables by using Data Types
otherwise we get Compile Time Errors
Examples: C, CPP, JAVA, .NET etc

4 manojalladi23@[Link]
2) Dynamically Typed Programming language

=>In This Programming languages, 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
OBJECTS, there exists CLASSES.

5. Interpreted Programming
=>When we develop any python program, we must give some file name with an extension .py
(File [Link]).
=>When we execute python program, two processes taken place internally
a) Compilation Process
b) Execution Process.
=>In COMPILATION PROCESS, The python Source Code submitted to Python Compiler and
It reads the source Code, Check for errors by verifying syntaxes and if no errors found then
Python Compiler Converts into Intermediate Code called BYTE CODE with an extension .pyc
([Link]). If errors found in source code then we error displayed on the console.
=>In EXECUTION PROCESS, The PVM reads the Python Intermediate Code (Byte Code) and
Line by Line and Converted into Machine Under stable Code (Executable or binary Code) and It
is read by OS and Processer and finally Gives Result.
=>Hence In Python Program execution, Compilation Process and Execution Process is taking
place Line by Line conversion and it is one of the Interpretation Based Programming Language.

5 manojalladi23@[Link]
Definition of PVM (Python Virtual Machine)
=>PVM is one program in Python Software and whose role is to read LINE by LINE of Byte
Code and Converted into Machine Under stable Code (Executable or binary Code)

6. High Level Programming


=>In general, we have two types of Programming languages. They are
a) Low Level Programming Languages.
b) High Level Programming Languages.

a) Low Level Programming Languages:


=>In These Programming Languages, we represent the data in lower level data like Binary, Octal
and Hexa decimal and this type data is not by default understanble by Programmers and end
users.

Examples: - a=0b1111110000111101010---binary data


b=0o23 ---- octal
c=0xface --- Hexa Decimal

b) High Level Programming Languages.


In These Programming Languages, Eeve we represent the data in lower level data like Binary,
Octal and Hexa decimal , the High Level Programming Languages automatically converts into

6 manojalladi23@[Link]
Decimal number System data, which is understanble by Programmers and end-users and python
is one High Level Programming Language.

Example: Python

7. Robust (Strong)
=>Python is one of the Robust Programming language bcoz of Python provides
“Exception Handling “Facility.

Exception: - Every Runtime Error is called Exception


All exceptions by default give technical Error Messages

Exception Handling: - The Process of Converting Technical Error Messages into


User-friendly Error Messages is known as Exception Handling
=>In Real Time Project, to do the above process of we use Exception handling to make real
projects as Robust.

NOTE:

In Real Time Application development, to develop any project, choose certain programming
language.
=>Using that programming language, we develop, compile and execute and during process, we
get various types of Errors.
1) Compile Time Errors (due to syntaxes are not followed) .py ----- >.pyc
2) Logical Errors------- (due to wrong representation of Logic--exertion time)

3) Runtime Errors:
Runtime Errors are those which are occurring during implementation level.
Runtime Errors occurs due invalid input entered by End User / Application user

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


----Invalid PIN
---Invalid Amount --- etc

Python program for validation of Name or Place or thing

Enter Ur Name: KVR--valid


Enter Ur Name: 123 -- Invalid
Enter Ur Name: 123abc--invalid
Enter Ur Name: #4abc%^&*--Invalid
Enter Ur Name: -------------- invalid
7 manojalladi23@[Link]
9. Extensible
=>The Python programming giving its programming facilities to other languages and hence
Python is one of the extensible Programming language.

10. Embedded
=>Python Programming can call other languages coding segments for fastest execution

Example: Python code can call C programming Code.

11. Supports Third party APIs---Numpy, Pandas, Scipy, Scikit, matplotlib


=>The traditional Python Programming Projects efficiency increased by Third party APIs like
numpy, pandas, matplotlib, scipy, scikit..Etc

=>To use Third party APIs, we must install them by using a tool called
PIP PIP3 PIP3.10

Data Representation
=>Data Representation in Python Programming is nothing storing the data in main memory of
computer.
=>To store the data in main memory of computer, we need three things. They are
a) Literals or Values
b) Identifiers or Variables
c) Data Types

a) Literals or Values:
=>Literals are the values entered by Programmer or end user or application user to real time
applications. They are classified into.
1) Integer Literals (Ex: stno, HTNO, empno, adhar card no.....etc)
2) Float Literals (Ex: Marks, percentage, gdp of India ...etc)
3) String Literals (Ex: Names, Places, Description ... etc)
4) Boolean Literals (Examples: True False)
5) Date Literals .... etc

b) Identifiers or Variables:

=>Once the application user enters the data from Key board to program, it is the responsibility of
Programmer to store data in the form of Literals or variables
=>hence all Literals or Values or Data must store in main memory in the form of Identifiers or
Variables otherwise we can't process the data.

8 manojalladi23@[Link]
Examples: >>> a=10
>>> b=20
>>> c=a+b
>>> print (a, b, c) ---------------- 10 20 30

=>Def. of Variable:

=>A Variable is an Identifier, whose values are changing or Varying during the execution of the
Program.

Rules for using Variables in Python


. =>To use variables in python programming, we have the following rules.

1) The Variable Name is combination of Alphabets, Digits and Special Symbol (_).
2) The Variable Name must starts with either Alphabet or Special Symbol Under
Score (_).
Examples: 123sal=4.5 --- invalid
-Sal=56.56 -- invalid
Sal=5.6 --- valid
_Sal=67.89--valid
sal123=6.7--valid
sal12_=7.8--valid
name="Rossum" -- valid
_=46 --- valid
3) Within Variable Name, special symbols are not allowed exception underscore (_).

Examples: emp$sal=5.6---invalid
Emp-sal=5.6---invalid
emp Sal=6.7--invalid
emp_sal=6.7-- valid
_emp_sal_ibm=7.8--valid
Sal=34 -- valid
Sal#emp=56------valid bcoz the symbol # is used in python as
commenting Symbol.

4) No Keywords to be used Variables Names (Keywords are reserved words which will have
some special meaning to the language compilers).

Examples:
If=34 --- invalid
Else=5.6 -- invalid
if1=34--valid

9 manojalladi23@[Link]
_else=5.6--valid
Int=23---valid---bcoz all the class names are not keywords
5) 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


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

I ) Fundamental Category Data Types


1. int
2. float
3. bool
4. complex
II ) Sequence Categery Data Types
1. str
2. bytes
3. bytearray
4. range
III) List Categery Data Types ( Collections Data Types or Data Structures)
1. list
2. tuple
IV) Set Categery Data Types( Collections Data Types or Data Structures)
1. set
2. frozenset
V) Dict Categery Data Types
1. dict
VI) None Type Categery Data Type
1. NoneType

I ) Fundamental Categery Data Types

=>The purpose of Fundamental Categery Data Types is that " To store Single Value".
=>We have 4 Data Types inFundamental Categery . They are
1) int
2) float
3) bool
4) complex

10 manojalladi23@[Link]
1) int
=>'int' is one of the pre-defined class and treated as Fundatamental Data Type.
=>the purpose of int data type is that " To store Integral Values or whole Numbers or Integer
Values ( Numbers without decimal values)
Examples: empno
adhar cardno
stno
htno..etc

Examples:

Python Instructions Output

>>> a=100
>>> print(a) 100
>>> print(type(a)) ------------------------- <class 'int'>
>>> print(id(a)) ---------------------------- 2601493466448
>>> b=23
>>> print(a, type(a), id(a))------------ 100 <class 'int'> 2601493466448
>>> print(a,type(a))
999999999999999999999999999999999999999999999999999999999999999999999999999999
9999999999999999999999999999999999999999999999 <class 'int'>

=>The int data can also store Various Numbers Systems Values.
=>In Python Programming, we have 4 types Numbers Systems. They are
a) Decimal Number System
b) Binary Number System
c) Octal Number System
d) Hexa Decimal Number System

a) Decimal Number System:


=>It is the default numbers
=>The digits in Decimal Number Systemare
Digits: 0, 1,2,3,4,5,6,7,8,9------Total Digits - 10
=>Base of Decimal Number System is 10
=>Python Programming by default follows Decimal Number System

b) Binary Number System:


=>The digits in Binary Number System are
Digits: 0, 1------Total Digits - 2
=>Base of Binary Number is 2
=>In Python Programming, To store Binary System Data, Binary Values must be preceded with
either 0b or 0B.

11 manojalladi23@[Link]
=>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 understanable by End User / Progarmmer.

Examples:

>>> a=0b1010
>>> print(a, type(a)) ----------- 10 <class 'int'>
>>> a=0B1111
>>> print(a) ----------15
>>> a=0b10102 ----- SyntaxError: invalid digit '2' in binary literal
>>>bin(10) ---------------Ob1010

c) Octal Number System:


=>The digits in Octal Number System are
Digits: 0, 1, 2 3 4 5 6 7 ------Total Digits --8
=>Base of Octal Number System is 8
=>In Python Programming, To store Octal Number System Data, Octal Number Values 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 Octal data into Decimal
Number System Value , which is understanable by End User / Progarmmer.

12 manojalladi23@[Link]
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
>>>Oct(23) ----------- Oo27

d) Hexa Decimal Number System:


=>The digits in Hexa Decimal Number System are
Digits: 0,1,2,3,4,5,6,7,8,9
A(=10) B(=11) C(=12) D(=13) E(=14) F(=15)------Total Digits - 16
=>Base of Hexa Decimal Number System is 16
=>In Python Programming, To store Hexa Decimal Number System Data, Hexa Decimal
Number Values must be preceded with either 0x or 0X.
=>Syntax: varname=0x Hexa Decimal data
OR
varname=0X Hexa Decimal Data

=>Even we store Hexa Decimal data, The Python Programming Converts Hexa Decimal data
into Decimal Number System Value , which is understanable by End User / Progarmmer.

13 manojalladi23@[Link]
>>> a=0xAC
>>> print(a, type(a)) ----------- 172 <class 'int'>
>>> a=0XBEE
>>> print(a,type(a)) -----------3054 <class 'int'>
>>> a=0xFACE
>>> print(a,type(a)) -----------64206 <class 'int'>
>>> a=0xACC
>>> print(a,type(a)) -------------2764 <class 'int'>
>>> a=0xFACER ---------- SyntaxError: invalid hexadecimal literal
>>> a=0XBEER ---- SyntaxError: invalid hexadecimal literal
>>>Hex(172) ------------ OxAC

2) float

=>'float' is one of the pre-defined class and treated as fundamental data type.
=>The purpose of float data type is that " To store Real Constant Values or
floating point values (Numbers with decimal places) "
Examples: 3.14
98.46
0.9999. etc

=>float data type does not support Binary , Octal and Hexa Decimal Number
System and it supports only default number system called Decimal Number System.
=>float data type supports Scientific Notation ( Mantisa e Exponent ) and whose advantage is
taking Less memory space for Larger Normal Floating Point Values

14 manojalladi23@[Link]
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 in decimal integer literals are not permitted
3) bool

=>'bool' is one of the pre-defined class and treated as Fundamental data type.
=>The purpose of bool data is that "To store True o False ( Logical Value )"
=>Internally The value of True is considered as 1 and False considered as 0.
=>Here True and False are the Keywords and Values for bool data type. So that we can't assigne
values to True and False

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

15 manojalladi23@[Link]
>>> 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

4. complex

=>'complex' is one of the pre-defined class and treated as Fundamental Data Type.
=>The purpose of complex data type is that to store Complex Values(Imaginary Values).
=>The General Format Complex of Numbers is shown bellow.

a+bj or a-bj

=>Here 'a' is called "Real Part "


=>Here 'b' is called "Imaginary Part"
=>here 'j' is represents sqrt(-1)
=>The type of Real and Imginary Parts are by default belongs "float"
=>To Extract Real Part from Complex Object we use "real" attribute / Variable of complex
object.
Syntax: [Link] ----> gives real part of complex number
=>To Extract Imaginary Part from Complex Object we use "imag" attribute / Variable of
complex object.
Syntax: [Link] ----> gives imaginary part of complex number

Examples:

>>> a=2+3j
>>> print(a,type(a)) ---------------- (2+3j) <class 'complex'>
>>> a=-4-5j
>>> print(a,type(a))----------------------(-4-5j) <class 'complex'>
>>> a=2.3+4.5j

16 manojalladi23@[Link]
>>> print(a,type(a)) ----------------- (2.3+4.5j) <class 'complex'>
>>>
>>> a=2+3j
>>> print([Link]) --------------------2.0
>>> print([Link]) ------------------ 3.0
>>> b=2.3+4j
>>> print([Link]) ---------------- 2.3
>>> print([Link]) ------------ 4.0
>>> a=4j
>>> print([Link]) ----------- 0.0
>>> print([Link]) -------- 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

II ) Sequence Categery Data Types

=>The purpose of Sequence Categery Data Types is that "To Organize or Store Sequence of
Values".
=>We have 4 data types in Sequence Categery. They are

1. str
2. bytes
3. bytearray
4. range
1. str

=>'str' is one of the pre-defined class in sequence data type


=>The purpose of 'str' data type is that " To store sequnece or collection of Character(s) or
Special Symbols or digits within single Qutes or double quotes or tripple single quotes or tripple
double Quotes."

=>Types of Strings:

=>In Python, we have two types of Strings. They are


1) Single Line String Data
2) Multi Line String Data

17 manojalladi23@[Link]
[Link] Line String Data
=>Single String data must be enclosed within Single Quotes or Double Quotes only

=>Syntax: strobj= " Single Line String Data "


(OR)
strobj= ' Single Line String Data '

Examples:

>>> s1="Python Program "


>>> print(s1,type(s1))--------------------------Python Program <class 'str'>
>>> s2='Pythin is an oop lang'
>>> print(s2,type(s2)) ------------------------ Pythin is an oop lang <class 'str'>
>>> s3="K"
>>> print(s3,type(s3)) ----------------------- K <class 'str'>
>>> s4='K'
>>> print(s4,type(s4)) ----------------------- K <class 'str'>
>>> s5="$#%^&@!"
>>> print(s5,type(s5)) ----------------------- $#%^&@! <class 'str'>
>>> s6="123456"
>>> print(s6,type(s6)) ------------------------- 123456 <class 'str'>

Note That Single Quotes and Double quotes can Organize 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
>>> s2='Pythin is an oop lang
Error Name --- >SyntaxError: unterminated string literal (detected at line

1) Multi Line String Data

=>Multi Line String data must be enclosed within Tripple Single Quotes or Tripple Double
Quotes only
=>Syntax: strobj= " " "
String Data -1
String Data -2

String Data -n """


(OR
=>Syntax: strobj= ' ' '
String Data -1
String Data -2

18 manojalladi23@[Link]
String Data -n ' ' '

=>here Tripple Single Quotes or Tripple Double Quotes can be both Single and Multi Line
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'>

19 manojalladi23@[Link]
1. str

Index:

=>Purpose of str
=>Types of Strs
=>Memory Management of str
=>Operations on str
a) Indexing
b) Slicing
strobj[start:stop]
strobj[start: ]
strobj[ : stop]
strobj[ : ]
strobj[start:stop:step]------- 5 rules

Operations on str data (part-1)


.
=>On str data, we can perform 2 types of operations. They are

1. Indexing
2. Slicing

20 manojalladi23@[Link]
1) Indexing:

=>The process of obtaning a Single Character from Given Str object is called Indexing.
=>Synbax:- strobj[ Index ]
=> Here Index represents 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

>>> 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 Operations, we have 5 Syntaxes. They are

Syntax-1: strobj[BEGIN : END ]


=>This Syntax obtains range of Characters from BEGIN Index 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

21 manojalladi23@[Link]
(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'

Syntax-2: strobj[BEGIN : ]

=>In This Syntax , we have BEGIN Index and Not specified END Index.
=>Syntax Give Range of Characters from BEGIN Index to Last Character
(OR)
=>Syntax Give Range of Characters 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 Give Range of Characters from First Character (Initial Positive Index) to END

22 manojalladi23@[Link]
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 did'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 Intial Index) and Last Character Index as END Index.
=>This Syntax Gives Total Str Sata.

Examples:

>>> s="PYTHON"
>>> print(s)----------------- PYTHON
>>> print(s[:]) ---------------- PYTHON
>>> print(s[0:]) --------------PYTHON
>>> print(s[:6]) ------------PYTHON
NOTE: All the above Stnaxes 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 eithet +Ve or -Ve or Both
2) If STEP Value is +VE Then PVM Takes Range of Characters from BEGIN Index to
END
Index-1 in Forward Direction provided BEGIN < END Index
3) If STEP Value is -VE Then PVM Takes Range of Characters from BEGIN Index to
END
Index+1 in Backward Direction provided BEGIN > END Index
4) In Forward Direction, If END Index is 0 then we nerver get any output ( ' ')
5) In backward Direction, If END Index is -1 then we nerver get any output ( ' ')

23 manojalladi23@[Link]
Examoles:
>>>s=”PYTHON”
>>> s[Link] ------------ 'PTO'
>>> s[Link] ------------ '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[Link]-1] ----------- ''
>>> s[Link]-1] ----------- 'NOH'
>>> s[::-1] -------------- 'NOHTYP'
>>> s[::-2] -------------- 'NHY'
>>> s[-1:-6:-1] --------- 'NOHTY'
>>> "PROG"[::-1] ----- 'GORP'
>>> "PROG"[::-1][::] -- 'GORP'
>>> "PROG"[::-1][::-1] ---- 'PROG'
>>> s="PYTHON"
>>> s[:0:-1]------------------- 'NOHTY'
>>> s[:0:1] ''
>>> s[:-1:-1] ''
>>> s="MADAM"
>>> s==s[::-1]
True
>>> "LIRIL"=="LIRIL"[::-1] >>>True

Type Casting Techniques in Python


=>The purpose of Type Casting Techniques is that "To Convert One Possible type of value
into another Possible type 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 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

24 manojalladi23@[Link]
>>>a=1.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'>

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'>
25 manojalladi23@[Link]
>>> b=int(a) --------- ValueError: invalid literal for int() with base 10: 'PYTHON'
2) float()

=>float() is used converting One Possible type of Value into float type value.
=>Syntax:- varname=float( int / bool / complex / str)

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

26 manojalladi23@[Link]
>>> 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="[Link]" # Pure String ---- Not Possible
>>> print(a,type(a)) ------ [Link] <class 'str'>
>>> b=float(a) --- ValueError: could not convert string to float: '[Link]'

3) bool()

=>bool() is used converting One Possible type of Value into bool type value.
=>Syntax:- varname=bool( int / float / complex / str)
=>ALL NON-ZERO VALUES 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))

27 manojalladi23@[Link]
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'>

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

28 manojalladi23@[Link]
>>> 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'>

Special Point

>>> a=""
>>> print(a,type(a))
<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))
False <class 'bool'>

4) complex()

=>complex() is used converting One Possible type of Value into complex type value.
=>Syntax:- varname=complex( int / float / bool / str)

Examples: int type value into complex type ---->Possible

>>> a=12
>>> print(a,type(a))

29 manojalladi23@[Link]
12 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))
(12+0j) <class 'complex'>

Examples: float type value into complex type --- >Possible

>>> a=12.34
>>> print(a,type(a))
12.34 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))
(12.34+0j) <class 'complex'>

Examples: bool type value into complex type ---->Possible

>>> a=True
>>> print(a,type(a))
True <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))
(1+0j) <class 'complex'>
>>> a=False
>>> print(a,type(a))
False <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))
0j <class 'complex'>

Examples:

>>> a="12" # int str into complex ---- Possible


>>> print(a,type(a))
12 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))
(12+0j) <class 'complex'>
>>> a="12.45" #float str into complex ----Possible
>>> print(a,type(a))
12.45 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))
(12.45+0j) <class 'complex'>
*****************************************************************
>>> a="True" # bool str ---- Not Possible
>>> print(a,type(a))

30 manojalladi23@[Link]
True <class 'str'>
>>> b=complex(a) ----- ValueError: complex() arg is a malformed string
*****************************************************************
>>> a="2+3.5j" # complex str into complex --- Possible
>>> print(a,type(a))
2+3.5j <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))
(2+3.5j) <class 'complex'>
*****************************************************************
>>> a="PYTHON" # pure str ---- Not Possible
>>> print(a,type(a)) ---------PYTHON <class 'str'>
>>> b=complex(a) ------- ValueError: complex() arg is a malformed string

5) str()

=>str() is used for converting all types of Values into str type value.
=>Syntax:- varname=str( int / float / bool / complex)

Examples:

>>> a=12
>>> print(a,type(a))
12 <class 'int'>
>>> b=str(a)
>>> b
'12'
>>> a=12.34
>>> print(a,type(a))
12.34 <class 'float'>
>>> b=str(a)
>>> b
'12.34'
>>> a=True
>>> print(a,type(a))
True <class 'bool'>
>>> b=str(a)
>>> b
'True'
>>> a=2+3j
>>> print(a,type(a))
(2+3j) <class 'complex'>
>>> b=str(a)
>>> b
'(2+3j)'
>>> a="2+3j"

31 manojalladi23@[Link]
>>> print(a,type(a))
2+3j <class 'str'>
>>> b=str(a)
>>> b
'2+3j'

Int Float Bool Complex Int Float Bool Complex Pure


str str str str str
Int + + + - + - - - -
Float + + + - + + - - -
Bool + + + + + + + + +
complex + + + + + + - + -

Mutability and Immutability

Mutability:

=>A Mutable object is one which allows to modify / update its Value / Content at Same
Address.

Examples:

list , set, dict ... etc

Immutability:

=>An Immutable object is one which will satify the following properties.
a) Modification / Updation Not possible at Same address
( If at all the value modfied then the modified value placed in new memory address)

b)Immutable objects never allows / supports Item Assigment.

Examples: int, float, str, tuple, frozenset ... etc

2. bytes [0-255(256-1) & -1 to -5]


=>'bytes' is one of the pre-defined class and treated as sequence data type.
=>The purpose of bytes data type is that " To Organize sequence of Possitive Numerical
Integer Values ranges from (0,256) i.e it stores values from 0 to 255 (256-1) only ".
=>For Storing the elements in an object of bytes, there is no symbolic notation. But we can
convert other type of objects 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.

32 manojalladi23@[Link]
=>An object of bytes belongs to immutable bcoz bytes' object does not support item
assignment
=>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

3. bytearray
=>'bytearray' is one of the pre-defined class and treated as sequence data type.
=>The purpose of bytearray data type is that " To Organize sequence of Possitive Numerical
Integer Values ranges from (0,256) i.e it stores values from 0 to 255 (256-1) only ".
=>For Storing the elements 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().

33 manojalladi23@[Link]
Syntax: varname=bytearray(object)
=>On the object of bytearray, we can perform Both Indexing and Slicing Operations.
=>An object of bytearray belongs to mutable bcoz bytearray object supports item assignment
=>An object of bytearray maintains Insertion Order( Nothing but whichever order, we insert the
data, in the same order elements will be displayed)

Note: The Functionality of bytearray is extactly similar to bytes but an object 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
>>> 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)
...

34 manojalladi23@[Link]
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 terated as sequence data type.
=>The purpose of range data type is that "To store sequence of Numerical Integer values
with Equal Interval Value. "
=>On the object of range , we can perform both Indexing and Slicing Operations.
=>an object of range belongs to immutable bcoz range' object does not support item
assignment (bcoz it becomes problem in range of values with interval)
=>range data type contains 3 syntaxes. They are

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=range(Begin, End)
This syntax generates range of values from Begin to End-1.

Examples:

>>> r=range(20,26)

35 manojalladi23@[Link]
>>> print(r,type(r))
range(20, 26) <class 'range'>
>>> for i in r:
... print(i)
...
20
21
22
23
24
25
>>> 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=range(Begin,End,Step)

This syntax generates range of values from Begin to End-1 with Interval value
called "Step".

Examples:
>>> r=range(50,101,10)
>>> for i in r:
... print(i)
...
50
60
70

36 manojalladi23@[Link]
80
90
100

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

37 manojalladi23@[Link]
5
6
7
8
9

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

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


... print(i)
...

38 manojalladi23@[Link]
-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

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

39 manojalladi23@[Link]
... 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

Special Case:

>>> n=9
>>> for i in range(1,11):
... print(n,"x",i,"=",n*i)
...
9x1=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
>>> n=19
>>> for i in range(1,21):
... print(n,"x",i,"=",n*i)
...

40 manojalladi23@[Link]
19 x 1= 19
19 x 2 = 38
19 x 3 = 57
19 x 4 = 76
19 x 5 = 95
19 x 6 = 114
19 x 7 = 133
19 x 8 = 152
19 x 9 = 171
19 x 10 = 190
19 x 11 = 209
19 x 12 = 228
19 x 13 = 247
19 x 14 = 266
19 x 15 = 285
19 x 16 = 304
19 x 17 = 323
19 x 18 = 342
19 x 19 = 361
19 x 20 = 380

III) List Categery Data Types ( Collections Data Types or Data Structures)

=>The purpose of List Categery Data Types is that " To store Collection of Values or multiple
values either of Same type or different type or both the types with unique and duplicate."
=>We have two data types in List Categery. They are
1) list
2) tuple

1) list
=>'list' of the one of the pre-defined class and treated as list data type.
=>The purpose of list data type is that "To store Collection of Values or multiple
values either of Same type or different type or both the types with unique and duplicate."
=>The elements of list must be stored within square brackets [ ] and the elements must
separated by comma.
=>An object of list maintains inerstion Order.
=>On the object of list, we can perform Both Indexing and Slicing.
=>An object of list belongs to mutable.
=>To convert any other object into list type object, we use list()
Syntax:- listobject=list(another object)
=>We can create two types of list objects. They are
a) empty list
b) non-empty list
a) empty lis:

=>An empty list is one, which does not contain any elements and length is 0
41 manojalladi23@[Link]
=>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 lis:

=>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]
Copy Techniques in Python

=>In Python Programming, we have two types of Copy Techniques. They are

1) Shallow Copy

2) Deep Copy

42 manojalladi23@[Link]
1) Shallow Copy:

=>In Shallow Copy Process, The following Points will satisfy


a) The Initial Content of Both the Objects are Same
b) Both the objects contains Different Memory Address
c) Modifications on both the object are Independent ( Modifications are not
reflected to each other)
=>To Implement Shallow Copy, we use copy()
=>Syntax: obj2=[Link]()

Examples:

>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))
[10, 'Rossum'] 1843503104896
>>> l2=[Link]()
>>> print(l2,id(l2))
[10, 'Rossum'] 1843499592064
>>> [Link]("Python")
>>> [Link](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 Objects are Same
b) Both the objects contains Same Memory Address
c) Modifications on both the object are dependent
( Modifications are reflected to each other)
=>To Implement Deep Copy, we use Assigment Operator ( = )
=>Syntax: object2=object1

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
>>> [Link]("Python")
>>> print(l1,id(l1))

43 manojalladi23@[Link]
[10, 'Rossum', 'Python'] 1843498922432
>>> print(l2,id(l2))
[10, 'Rossum', 'Python'] 1843498922432
>>> [Link](2,"Django")
>>> print(l1,id(l1))
[10, 'Rossum', 'Django', 'Python'] 1843498922432
>>> print(l2,id(l2))
[10, 'Rossum', 'Django', 'Python'] 1843498922432

Pre-defined functions list


=>We know that , on the object of list, we can perform both Indexing and Slicing Operations.
=>Along with these operations, we can also perform many more operations on the object of
list by using pre-defined function which are present in list object.

1) append()

=>This Function is used for adding the value to the list object always at end.
=>Syntax:- [Link](value)

Examples:

>>> l1=[]
>>> print(l1,len(l1), id(l1))
[] 0 2722448959936
>>> [Link](10)
>>> [Link](10.5)

44 manojalladi23@[Link]
>>> print(l1,len(l1), id(l1))
[10, 10.5] 2 2722448959936
>>> [Link]("Rossum")
>>> print(l1,len(l1), id(l1))
[10, 10.5, 'Rossum'] 3 2722448959936
>>> [Link](True)
>>> print(l1,len(l1), id(l1))
[10, 10.5, 'Rossum', True] 4 2722448959936

2) insert()

=>This function is used for inserting the values at valid existing index.
=>Syntax: [Link](index,Value)
=>here Index can eithet +ve or -ve.

Examples:

>>> l2=[10,"Rossum",34.56,True]
>>> print(l2,id(l2))
[10, 'Rossum', 34.56, True] 2722448006784
>>> [Link](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 for removing all the elements of list.


=>Syntax:- [Link]()

Examples:

>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)
[100, 'Rossum', 45.56, 'Python', True]
>>> len(l1)
5
>>> [Link]()
>>> print(l1)
[]
>>> len(l1)
0

45 manojalladi23@[Link]
4) remove() ----Based Value

=>This is used for removing First occurence of specified element from list.
=>If the specified element not found in list then we get ValueError.
=>Syntax:- [Link](Value)

Examples:

>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)
[100, 'Rossum', 45.56, 'Python', True]
>>> [Link](100)
>>> print(l1)
['Rossum', 45.56, 'Python', True]
>>> [Link](45.56)
>>> print(l1)
['Rossum', 'Python', True]
>>> [Link](True)
>>> print(l1)
['Rossum', 'Python']
>>> [Link](100) ------------- ValueError: [Link](x): x not in list
>>> [].remove(0) ------------ValueError: [Link](x): x not in list
>>> list().remove(10) --- ValueError: [Link](x): x not in list

>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)
[10, 20, 10, 30, 10, 20, 20, 10]
>>> [Link](10)
>>> print(l2)
[20, 10, 30, 10, 20, 20, 10]
>>> [Link](10)
>>> print(l2)
[20, 30, 10, 20, 20, 10]

5) pop(index)
=>This is used for removing the elements 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
=>If the Index InValid Then we get IndexError.

Examples:

>>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)

46 manojalladi23@[Link]
[10, 20, 10, 30, 10, 20, 20, 10]
>>> [Link](2)
10
>>> print(l2)
[10, 20, 30, 10, 20, 20, 10]
>>> [Link](-1)
10
>>> print(l2)
[10, 20, 30, 10, 20, 20]
>>> [Link](1)
20
>>> [Link](11) ---------------- IndexError: pop index out of range

>>> l1=[100,"Rossum",45.56,"Python",True]
>>> [Link](1)
'Rossum'
>>> print(l1)
[100, 45.56, 'Python', True]
>>> [Link](22) ------------ IndexError: pop index out of range
>>> [].pop(0) ------------ IndexError: pop from empty list
>>> list().pop(-1) --- IndexError: pop from empty list

6) pop()

=>This is used for removing last element of list.


=>When we call this function upon empty list object then we get IndexError.
==>Syntax: [Link]()

Examples:

>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)
[100, 'Rossum', 45.56, 'Python', True]
>>> [Link]()
True
>>> print(l1)
[100, 'Rossum', 45.56, 'Python']
>>> [Link](2,"Python")
>>> print(l1)
[100, 'Rossum', 'Python', 45.56, 'Python']
>>> [Link]()
'Python'
>>> print(l1)
[100, 'Rossum', 'Python', 45.56]
>>> [Link]()
45.56

47 manojalladi23@[Link]
>>> print(l1)
[100, 'Rossum', 'Python']
>>> [Link]()
'Python'
>>> print(l1)
[100, 'Rossum']
>>> [Link]()
'Rossum'
>>> print(l1)
[100]
>>> [Link]()
100
>>> print(l1)
[]
>>> [Link]() ----------- IndexError: pop from empty list

NOTE: del operator

=>The operator "del" is used for removing


a) Based on Indexing ----- del obj[Index]
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.

7) index()

=>This function obtains Index of First Occurence of the Specified Element.


=>Syntax:- [Link](Value)
=>If the value does not exists then we get ValueError.

Examples:

>>> l2=[10,20,10,30,10,20,20,10]
>>> print(l2)
[10, 20, 10, 30, 10, 20, 20, 10]
>>> [Link](10)

48 manojalladi23@[Link]
0
>>> [Link](100) -------------- ValueError: 100 is not in list
>>> [Link](20)
1

8) count():

=>This function find number of occurences of a perticular element.


=>Syntax: [Link](value)
=>=>If the value does not exists 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]
>>> [Link](10)
4
>>> [Link](20)
3
>>> [Link](30)
1
>>> [Link](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=[Link]()

Examples:

>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))
[10, 'Rossum'] 1843503104896
>>> l2=[Link]() # shallow Copy

49 manojalladi23@[Link]
>>> print(l2,id(l2))
[10, 'Rossum'] 1843499592064
>>> [Link]("Python")
>>> [Link](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 is used for obtaining reverse of the elememnts of list ( front to back and back to front).
=>Syntax:- [Link]()

Examples:

>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1,id(l1)) ---------- [100, 'Rossum', 45.56, 'Python', True] 1843503104896
>>> [Link]()
>>> 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 Decending Order
=>By default we get in Ascending Order
=>Syntax: [Link](reverse=True or False)
=>Here When reverse=True the we get the lements of list in Decensing Order
=>Here When reverse=False ( by default) the we get the lements of list in Ascending Order

50 manojalladi23@[Link]
Examples:

>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1) --------------------- [10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> [Link]() # 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]
>>> [Link](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]
>>> [Link](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']
>>> [Link](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']
>>> [Link](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]
>>> [Link]() ----------- TypeError: '<' not supported between instances of 'str' and 'int'

12) extend()

=>This function is used for adding the content of one list object to another list object.
=>Syntax: [Link](listobj2)
=>Here listobj2 are added to listobj1

Examples:

>>> l1=[10,20,30]
>>> l2=["RS","DR","TS"]
>>> print(l1)

51 manojalladi23@[Link]
[10, 20, 30]
>>> print(l2)
['RS', 'DR', 'TS']
>>> [Link](l2)
>>> print(l1)
[10, 20, 30, 'RS', 'DR', 'TS']
>>> print(l2)
['RS', 'DR', 'TS']

inner or nested list


=>The process of defining one list inside of another list is called Inner / 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],[val21,val22...val2n], ..... 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

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

52 manojalladi23@[Link]
>>> 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' of 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 different type or both the types with unique and duplicate."
=>The elements of tuple must be stored within braces ( ) and the elements must
separated by comma.
=>An object of tuple maintains inerstion Order.
=>On the object of tuple, we can perform Both Indexing and Slicing.
=>An object of tuple belongs to immutable.
=>To convert any other object intotuple type object, we use tuple()
Syntax:- tupleobject=tuple(another object)
=>We can create two types of tuple objects. They are
a) empty tuple
b) non-empty tuple
a) empty tuple:

=>An empty tuple is one, which does not contain any elements and 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

53 manojalladi23@[Link]
b) non-empty tuple:

=>A non-empty tuple is one, which contains elements and length is >0
Syntax:- tplobj=(val1,val2...val-n)
(OR)
tplobj=val1,val2...val-n

Note: The Functionality of tuple is exactly similar to list but an object of list belongs to mutable
and an object of tuple belongs to immutable.
Examples:

>>> t1=(10,20,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

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

54 manojalladi23@[Link]
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')
>>> [Link](10) -------------------- 2
>>> [Link]("Ram") --------------- 1

The following Functions not present in tuple

append()
insert()
clear()
remove()
pop(index)
pop()
copy()
reverse()
sort()
extend()

=>Inner tuple or nested tuple

=>The process of defining one tuple inside of another tuple is called Inner / 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() 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)

55 manojalladi23@[Link]
>>> 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 in another list
=============================X======================================
Set Categery Data Types( Collections Data Types or Data Structures)
=>The purpose of Set Categery Data Types is that " To store Collection or multiple values either
of same type or different type or both the types with Unique Values ( No duplicatesd are
allowed)".
=>We have 2 data types in Set Categery. They are
1. set (mutable and immutable )
2. frozenset (immutable )

1. set
=>"set" is one of the pre-defined class and treated as set data type.
=>The purpose of set data type is that " To store Collection or multiple values either of same
type or different type or both the types with Unique Values ( No duplicatesd are allowed)".
=>The elements of set must be organized within curly braces { } and elements must separated
by comma,
=>An object of set does not maintain insertion order bcoz PVM displays any order of multiple
possibilities.
=>On the object of set, we can't perform Indexing and slicing Operations bcoz set object does
not maintain Insertion order.
=>An object of set belongs to immutable (bcoz of 'set' object does not support item
assignment) and mutable ( bcoz in the case of add() ).
=>By using set class, we can two types of set objects. They are
a) empty set
b) non-empty set
a) empty set:

=>An empty set is one, which does not contain any elements and whose length is 0
=>Syntax:- setobj=set()

56 manojalladi23@[Link]
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=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
>>> [Link]("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

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

57 manojalladi23@[Link]
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 Functrion is used for adding the lements to set object.


=>Syntax: [Link](value)

Examples:

>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1)) ------------- {10, 'Rossum'} <class 'set'> 1473821509888
>>> [Link]("python")
>>> [Link](34.56)
>>> print(s1,type(s1),id(s1))-------{10, 'Rossum', 34.56, 'python'} <class 'set'> 1473821509888

2) clear():

=>This function is used for removing all the elements of set.


=>Syntax: [Link]()
=>Examples:

>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1)) ----------- {10, 'Rossum'} <class 'set'> 1473821508992
>>> [Link]()
>>> print(s1,type(s1),id(s1)) ------------ set() <class 'set'> 1473821508992
3) remove()

=>This function is used for removing an element from set object.


=>Syntax:- [Link](value)
=>If the value does not exists in setobj then we get KeyError.

Examples:

>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1)) ----------------- {10, 'Rossum'} <class 'set'> 1473821509888
>>> [Link](10)
>>> print(s1,type(s1),id(s1)) ------------- {'Rossum'} <class 'set'> 1473821509888
>>> [Link]("Rossum")
>>> print(s1,type(s1),id(s1)) ------------ set() <class 'set'> 1473821509888

58 manojalladi23@[Link]
>>> s1={10,"Rossum"}
>>> [Link](100) --------- KeyError: 100
>>> [Link]("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:- [Link](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
>>> [Link](10)
>>> print(s1,type(s1),id(s1)) -------------- {'Rossum'} <class 'set'> 1473821509664
>>> [Link](100) --------- No Error will come
>>> print(s1,type(s1),id(s1)) -------------- {'Rossum'} <class 'set'> 1473821509664
>>> [Link]("Rossum")
>>> print(s1,type(s1),id(s1)) -------------- set() <class 'set'> 1473821509664
>>> [Link](100) ----------- No Error will come

5) pop()

=>This Function is used for removing any arbitrary element from setobj.
=>Syntax: [Link]()

Examples:

>>> s1={10,"Rossum",23.45,"Python",True,2+3j} # No output is shown


>>> [Link]()
True
>>> len(s1) 5
>>> [Link]() --------- 23.45
>>> len(s1) ------------ 4
>>> [Link]() ----------- 'Python'
>>> len(s1) ------------ 3
>>> [Link]() --------- 10
>>> len(s1) ------------- 2
>>> [Link]() ---------- 'Rossum'
>>> len(s1) ---------- 1
>>> [Link]() --------- (2+3j)
>>> len(s1) ------------ 0
>>> print(s1) ------------ set()

59 manojalladi23@[Link]
>>> [Link]() ------------------ 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
>>> [Link]() -------- 34.56
>>> print(s2) ---------- {50, 20, 10, 'python', 30}
>>> [Link]() ---------- 50
>>> print(s2) ----------- {20, 10, 'python', 30}
>>> [Link]() ----------- 20
>>> print(s2) ------------ {10, 'python', 30}
>>> [Link]() ----------- 10
>>> print(s2) ------------ {'python', 30}
>>> [Link]() ------------- 'python'
>>> print(s2) ----------- {30}
>>> [Link]() ----------- 30
>>> print(s2) --------------- set()
>>> [Link]() --------------- KeyError: 'pop from an empty set'

6) copy():

=>This function is used for copying the content of one setobject into another set object.
=>Syntax:- setobj2=[Link]()

Examples:

>>> s3={12,"Django","Python"}
>>> print(s3,id(s3)) -------------- {12, 'Django', 'Python'} 1473821510784
>>> s4=[Link]() # Shallow Copy
>>> print(s4,id(s4)) ----------- {12, 'Django', 'Python'} 1473821511008
>>> [Link]("DS")
>>> [Link]("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
>>> [Link]("Flask")

60 manojalladi23@[Link]
>>> 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 place them
in setobj3.
=>Syntax:- setobj3=[Link](setobj2)
(OR)
=>Syntax:- setobj3=[Link](setobj1)

Examples:

>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=[Link](s2)
>>> print(s3) ----------- {40, 10, 15, 20, 25, 30}
OR
>>> [Link](s2) ------------ {40, 10, 15, 20, 25, 30}

>>> s1={"Python","Django","DS"}
>>> s2={10,"Python",23.45}
>>> s3=[Link](s2)
>>> print(s3) -------------- {'Python', 'Django', 23.45, 10, 'DS'}

8) intersection():

=>This function is used for obtaining Common values from setobj1 and setobj2 and place them
in setobj3.

=>Syntax:- setobj3=[Link](setobj2)
OR
=>Syntax:- setobj3=[Link](setobj1)

Examples:

>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=[Link](s2)
>>> print(s3) ----------------- {10, 20}

>>> s1={"Python","Django","DS"}
>>> s2={10,"Python",23.45}
>>> s3=[Link](s2)
>>> print(s3) ------------ {'Python'}

61 manojalladi23@[Link]
>>> s1={10,20,30,40}
>>> s2={15,25,100,200}
>>> s3=[Link](s2)
>>> print(s3) ------------- set()

9) difference()

=>Syntax:- setobj3=[Link](setobj2)
=>This function removes the common elements from both setobj1 and setobj2 and takes
remaining elements from setobj1 and place them in setobj3.
(OR)
=>Syntax:- setobj3=[Link](setobj1)
=>This function removes the common elements from both setobj2 and setobj1 and takes
remaining elements from setobj2 and place them in setobj3.

Examples:

>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=[Link](s2)
>>>print(s3) ------------ {40, 30}

>>> s3=[Link](s1)
>>> print(s3) ----------- {25, 15}

10) symmetric_difference():

=>This function removes the common elements from setobj1 and setobj2 and takes the
remaining elements from both setobj1 and setobj2 and place them in setobj3

=>Syntax: setobj3=setobj1.symmetric_difference(setobj2)
(OR)
=>Syntax: 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}

62 manojalladi23@[Link]
Special Examples:

>>> tp={"Kohli","Ram","Rossum"}
>>> allcptp=[Link](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=[Link](tp)
>>> print(bothcptp) ------------ {'Kohli'}
>>> bothcptp=cp&tp # Bitwise AND
>>> print(bothcptp) ------------- {'Kohli'}

>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> onlycp=[Link](tp)
>>> print(onlycp) ----------------- {'Sachin', 'Rohit'}
>>> onlycp=cp-tp # Arithmetic Operator -
>>> print(onlycp) ----------- {'Sachin', 'Rohit'}

>>> onlytp=[Link](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'}

11) update()

=>Syntax:- [Link](setobj2)
=>This Function updates the setobj1 values with setobj2 values
>>> s1={10,20,30}
>>> s2={"python","Java","Data Science","IOT"}
>>> s3=[Link](s2)
>>> print(s3) ------------ None
>>> print(s1) -------- {20, 'python', 'IOT', 10, 'Java', 30, 'Data Science'}
>>> print(s2) --------- {'Java', 'python', 'IOT', 'Data Science'}

63 manojalladi23@[Link]
>>> ur={10,"Ram"}
>>> skill={"Python","Java","IOT",10}
>>> [Link](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 elements set must organized with curly braces {} and values must separated by comma
and those values can converted into frozenset by using frozenset()

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

=>An object of frozenset does not maintain insertion Order bcoz PVM displays any possibility
of elements of frozenset
=>Since frozenset object does not maintain insertion order, we can't perform Indexing
and Slicing Operations ( frozenset' object is not subscriptable)
=>An object of frozenset belongs to immutable (in the case frozenset' object does not support
item assignment and adding elements also not possible)

64 manojalladi23@[Link]
Note:-The Functionality of frozenset is similar to set but an object of set belongs to both
immutable ( in case of item assigment) and mutable (in the case of add()) where as an object
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'>
[Link](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=[Link](fs2)
>>> print(fs3)
frozenset({40, 10, 15, 20, 25, 30})
>>> fs4=[Link](fs2)
>>> print(fs4)
frozenset({40, 30})
>>> fs5=[Link](fs2)
>>> print(fs5)
frozenset({10, 20})
>>> fs6=[Link](fs1)
>>> print(fs6)
frozenset({25, 15})
>>> fs7=fs2.symmetric_difference(fs1)
>>> print(fs7)
frozenset({10, 15, 20, 25})
>>> fs7=fs1.symmetric_difference(fs2)

65 manojalladi23@[Link]
>>> print(fs7)
frozenset({10, 15, 20, 25})

>>> s1={10,20,30,40}
>>> fs1=frozenset(s1)
>>> fs2=[Link]()
>>> print(fs1,id(fs1))---------------- frozenset({40, 10, 20, 30}) 2299638113984
>>> print(fs2,id(fs2))---------------- frozenset({40, 10, 20, 30}) 2299638113984
============================X=================================

dict Catagery Data Type ( Collection Data Types or Data Structures)

=>The purpose of dict Catagery Data Type is the "To organize the data in the form of
(Key,Value)"
=>To organize the data in the form (key,value), we use a pre-defined class called "dict".
=>"dict" is one of the pre-defined class and treated as dict Catagery Data Type
=>The elements of dict must be organized in the form curly braces { } and (key,value) must
separated by comma.
=>An object of dict maintains insertion Order.
=>On the object of dict, we can't perform Indexing and Slicing Operations.
=>An object of dict belongs to mutable. In otherwords , The Values of Key are belongs to
immutable and Values of Value are belongs to mutable
=>By using dict class , we can create two types of dict objects. They are
a) empty dict
b) non-empty dict
a) An empty dict is one, which does not contains any elements and whose length is 0.
Syntax:- dictobj={}
(or)
dictobj=dict()

=>Syntax for adding (Key,value) to empty dict object

dictobj[Key1]=Value1
dictobj[Key2]=Value2

dictobj[Key-n]=Value-n

b) A non-empty dict is one, which contains elements and whose length is >0.
Syntax:- dictobj={Key1:Val1, Key2:Val2. ..... Key-n:Val-n}
Here Key1,Key2. Key-n are called Keys 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 duplicate
and they can be either Strs or Numerics

66 manojalladi23@[Link]
Examples:

>>> d1={}
>>> print(d1,type(d1)) -------------- {} <class 'dict'>
>>> len(d1) -------------- 0
>>> d2={10:1.2,20:2.5,30:2.5,40:4.5}
>>> print(d2,type(d2)) ---------- {10: 1.2, 20: 2.5, 30: 2.5, 40: 4.5} <class 'dict'>
>>> len(d2) ----------- 4

>>> d3=dict()
>>> print(d3,type(d3), len(d3))-------- {} <class 'dict'> 0
>>> d1={"Rossum":"Python","Ritche":"C", "Gosling":"Java"}
>>> print(d1,type(d1)) --- {'Rossum': 'Python', 'Ritche': 'C', 'Gosling': 'Java'} <class 'dict'>

>>> d2={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d2) ---- {10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'}

>>> print(d2[0]) ------- KeyError: 0


>>> print(d2[10]) -------- Apple
>>> print(d2[40]) ------- Sberry
>>> print(d2[400]) -------KeyError: 400

>>> d1={}
>>> print(d1,type(d1),len(d1), id(d1))----{} <class 'dict'> 0 2299637840384
>>> d1[100]="Rossum"
>>> d1[101]="Ritche"
>>> d1[102]="Travis"
>>> d1[103]="MCKinney"
>>> print(d1,type(d1),len(d1), id(d1)) --- {100: 'Rossum', 101: 'Ritche', 102: 'Travis', 103:
'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

67 manojalladi23@[Link]
Pre-defined functions present in dict
=>To do various operations on dict object, we use the pre-defined functions present in dict
object.

1) clear()

=>This function is used for removing all the elements of dict.


=>Syntax:- [Link]()
=>Examples:

>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))--------------- {100: 'Rossum', 101: 'Gosling', 102: 'Ritche'} 3
>>> [Link]()
>>> print(d1,len(d1))------------- {} 0

2) pop():
=>This function removes (Key,value) from dict object by passing Value of Key
=>If value of key does not exists then we get KeyError.
=>Syntax: [Link](Key)

Examples:

>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))----------------- {100: 'Rossum', 101: 'Gosling', 102: 'Ritche'} 3
>>> [Link](100) -------------- 'Rossum'
>>> print(d1,len(d1))----------- {101: 'Gosling', 102: 'Ritche'} 2
>>> [Link](101) ----------- 'Gosling'
>>> print(d1,len(d1))---------------- {102: 'Ritche'} 1
>>> [Link](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-dict object .
=>when we call popitem() on empty dict object then we get KeyError.
=>Syntax: [Link]()

Examples:

>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))------------- {100: 'Rossum', 101: 'Gosling', 102: 'Ritche'} 3
>>> [Link]() --------------- (102, 'Ritche')
>>> print(d1,len(d1))------------ {100: 'Rossum', 101: 'Gosling'} 2

68 manojalladi23@[Link]
>>> [Link]() --------- (101, 'Gosling')
>>> print(d1,len(d1))---------- {100: 'Rossum'} 1
>>> [Link]() ------------- (100, 'Rossum')
>>> print(d1,len(d1))--------------{} 0
>>> [Link]() -------------- KeyError: 'popitem(): dictionary is empty'

>>> {}.popitem() ----------------- KeyError: 'popitem(): dictionary is empty'


>>> dict().popitem()------------- KeyError: 'popitem(): dictionary is empty'

4) copy():

=>This function copy the content of one dict object into another dict object( Implementing
Shallow Copy).
=>Syntax:- dictobj2=[Link]()

Examples:

>>> d1={100:"Rossum",101:"Gosling"}
>>> print(d1,id(d1)) -------------- {100: 'Rossum', 101: 'Gosling'} 2002260856320
>>> d2=[Link]() # shallow copy
>>> 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 used for getting value of value by passing value of Key
=>If the value of Key does not exists then we get None as resultant value.
=>Syntax:-[Link](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'
>>> [Link](100)----------- 'Rossum'
>>> [Link](101)----------- 'Gosling'
>>> [Link](102)---------- 'Ritche'
>>> d1[103] -------------- KeyError: 103
>>> [Link](103)-------------- No Result
>>> print([Link](103))--------None--- kwd --value of NoneType

69 manojalladi23@[Link]
6) values()

=>This function gives list of values of Value


=>Syntax:- [Link]()
=>Syntax:- values= [Link]()

Examples:

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

>>> vals=[Link]()
>>> 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:- [Link]()
=>Syntax:- ks= [Link]()

Examples:

>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1)
{100: 'Rossum', 101: 'Gosling', 102: 'Ritche'}
>>> [Link]()
dict_keys([100, 101, 102])
>>> for k in [Link]():
... print(k)
...
100
101

70 manojalladi23@[Link]
102
(OR)
>>> ks=[Link]()
>>> print(ks)
dict_keys([100, 101, 102])
>>> for k in ks:
... print(k)
...
100
101
102

8) items()

=>This function is used for obtaining list of of tuples (Key,Value) from non-empty dict.
=>Syntax: [Link]()
=>Syntax:- varname=[Link]()

Examples:

>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1) ----------- {100: 'Rossum', 101: 'Gosling', 102: 'Ritche'}
>>> [Link]() ------- dict_items([(100, 'Rossum'), (101, 'Gosling'), (102, 'Ritche')])
>>> for it in [Link]():
... print(it)
...
(100, 'Rossum')
(101, 'Gosling')
(102, 'Ritche')
>>> for k,v in [Link]():
... print(k,"--->",v)
...
100 ---> Rossum
101 ---> Gosling
102 ---> Ritche
(OR)
>>> kvs=[Link]()
>>> print(kvs) ---------- dict_items([(100, 'Rossum'), (101, 'Gosling'), (102, 'Ritche')])
>>> for k,v in kvs:
... print(k,"==>",v)
...
100 ==> Rossum
101 ==> Gosling
102 ==> Ritche

71 manojalladi23@[Link]
9) update()

=>Syntax:- [Link](dictobj2)
=>This is used for updating dictobj1 values with dictobj2 values.

Examples:

>>> d1={10:"Python",20:"Java"}
>>> d2={30:"Django",40:"DS"}
>>> print(d1) --------------- {10: 'Python', 20: 'Java'}
>>> print(d2) --------------- {30: 'Django', 40: 'DS'}
>>> [Link](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'}
>>> [Link](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'}
>>> [Link](d2)
>>> print(d1) ------------------ {10: 'Python', 20: 'Django', 30: 'DS'}

Special Examples:

>>>
d1={1:["Python","DS","Django"],2:("Java","Servlets","Spring"),3:{"Oracle","MySql","MongoD
B"} }
>>> print(d1)
{1: ['Python', 'DS', 'Django'], 2: ('Java', 'Servlets', 'Spring'), 3: {'MySql', 'Oracle', 'MongoDB'}}
>>> for k,v in [Link]():
... print(k,"==>",v)
...
1 ==> ['Python', 'DS', 'Django']
2 ==> ('Java', 'Servlets', 'Spring')
3 ==> {'MySql', 'Oracle', 'MongoDB'}

72 manojalladi23@[Link]
NoneType data type

=>'NoneType' is one the pre-defined class and treated as None type Data type
=> "None" is keyword acts as value for <class,'NoneType'>
=>The value of 'None' is not False, Space , empty , 0
=>An object of NoneType class can't be created explicitly.

Examples:

>>> a=None
>>> print(a,type(a)) -----------None <class 'NoneType'>
>>> a=NoneType() -------- NameError: name 'NoneType' is not defined

73 manojalladi23@[Link]
Number of approaches to develop programs in Python
=>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 bcoz Big Problem
solving statements 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 softwares Interative Mode: Python Command Prompt, Python IDLE

b) Batch Mode:

=>In This Mode of Development, Python Progammer develops or writes batch or group of
Optimized Instructions and saved on file name with an extension .py (Source Code).

Examples Softwares

1) Python IDLE
2) EDIT PLUS
3) Pycharm
4) VS Code
5) Jupiter Note Book
6) atom
7) spider
8) sub lime text etc

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

74 manojalladi23@[Link]
#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 the console


=>To display the result of the program on the console, we use a pre-defined function called
print()
=>In Otherwords print() is used 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 Values on the console.

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

75 manojalladi23@[Link]
Syntax2:- print(Messages)

=>This Syntax display 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.

>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum=",c) ------------- sum= 30
>>> print(c," is the sum")--------30 is the sum
>>> print('sum of ',a,' and ',b,'=',c)-------sum of 10 and 20 = 30

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

76 manojalladi23@[Link]
>>> 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 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 then we must convert it into str()

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%

77 manojalladi23@[Link]
>>> # =====
>>> 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']

>>> print("*"*50) --- **************************************************


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

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)

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)

print("Enter Length and Breadth:")


length=float(input())
breadth=float(input())
#calculate area of rect
ar=length*breadth
print("Area of Rect=",ar)

78 manojalladi23@[Link]
print("Enter Length and Breadth:")
ar=float(input())*float(input())
print("Area of Rect=",ar)

print("Enter Length and Breadth:")


print("Area of Rect=",float(input())*float(input()))

print("Area of Rect=",float(input("Enter Length:"))* float(input("Enter Breadth:")))

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

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 Key Board in the form str only.
=>Programatically, to convert str type into other types, we use Type Casting Techniques.

=>Syntax:- varname=input()
=>here varname is an object of type <class,'str'>
=>input() is one of the pre-defined Function

Examples:

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

79 manojalladi23@[Link]
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 value from Key Board in the form of str type
additionally with this function we can give User-Prompting Message.
=>Programatically, to convert str type into other types, we use Type Casting Techniques.

=>Syntax: varname=input(Message)

=>here varname is an object of type <class,'str'>


=>input() is one of the pre-defined Function
=>"Message" represents 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)

80 manojalladi23@[Link]
# Program for accepting Length and Breadth and find area of rectangle
#[Link]
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
#[Link]
l=float(input("Enter Length:"))
b=float(input("Enter breadth:"))
area=l*b
print("Area of Rect=",area)

#program for cal simple intrest


#[Link]
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
#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)

81 manojalladi23@[Link]
Operators and Expressions in Python
=>An Operator is a Symbol, which is used used perform some operation on the data.
=>If any two or more Objects or variables connected with an operator then it is called
Expression.
=>In Python Programming, we have 7 types of Operators. They are

1. Arithmetic Operators
2. Assigment Operator
3. Relational Operators
4. Logical Operators
5. Bitwise Operators (Most Imp)
6. Membership Operators
a) in
b) not in
7. Identity Operators
a) is
b) is not

Note:- Python programming does not contain


a) Post and Pre-Increment and decrement Operators ( ++ -- )
b) ternary Operator ( ? : )

=>In place of ternary Operator , Python contains some other ternary operator
" expr1 if Test Cond else expr2 "

82 manojalladi23@[Link]
1. Arithmetic Operators
=>The purpose of Arithmetic Operators is that " To perform Arithmetic Operations such as
addition,substraction, multiplication etc".
=>If two or more objects or variables connected with Any Arithmetic Operator then it is called
Arithmetic Expression.
=>In Python Programming, we have 7 Arithmetic Operators. They are giben in the following
table.

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


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

83 manojalladi23@[Link]
#Program for demonstrating Arithmetic Operators
#[Link]
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)

#program for cal square root of a given number


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


#[Link]
n=int(input("Enter a number:"))
res=n**0.5
print("squareroot({})={}".format(n,res))
print(" OR ")
print("squareroot(%d)=%s" %(n,str(res)))

2. Assigment Operator
=>The purpose of assignment operator is that " To assign or transfer Right Hand Side (RHS)
Value / Expression Value to the Left Hand Side (LHS) Variable "
=>The Symbol for Assigment Operator is single equal to ( = ).
=>In Python Programming,we can use Assigment Operator in two ways.
1. Single Line Assigment
2. Multi Line Assigment

84 manojalladi23@[Link]
1. Single Line Assigment:

=>Syntax: LHS Varname= RHS Value


LHS Varname= RHS Expression

=>With Single Line Assigment at a time we can assign one RHS Value / Expression to the
single LHS Variable Name.

Examples:

>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c) ----------- 10 20 30

2. Multi Line Assigment:

=>Syntax: Var1,Var2.....Var-n= Val1,Val2. .. Val-n

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

#Program for swapping of any two values by using Multi line assingment
#[Link]
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)

85 manojalladi23@[Link]
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

#programm for swapping of two values


a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("-"*40)
print("Orginal val of a:{}".format(a))
print("Orginal val of b:{}".format(b))
print("-"*40)
#swapping logic
a,b=b,a # Multi line assigment
print("Swapped val of a:{}".format(a))
print("Swapped val of b:{}".format(b))
print("-"*40)

86 manojalladi23@[Link]
#relational Operators Functionality
#[Link]
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


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


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

87 manojalladi23@[Link]
4. Logical Operators
=>The purpose of Logical Operators is that "To Connect two or more Relational Expressions".
=>If two or more Relational Expressions connected with Logical Operators then it is called
Logical Expression or Compound Conditions(Multiple condition).
=>The result of 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.
=====================================================================
SLNO SYMBOL MEANING
=====================================================================
1 and Physical ANDing

2. or Physical ORing

3. not -------------------------------

=====================================================================
1) and :

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

In the case of "and" operator, if First Relational 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.

88 manojalladi23@[Link]
2) or :
=>The Functionality of "or" operator is described in the following Truth Table.

Rel Expr1 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 Evaluation (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 "not" operator is described in the following Truth Table.

Rel Expr1 not RelExpr1

False True

True False

Examples:
>>> a=10
>>> b=20
>>> a==b ---------- False
>>> not(a==b) ----------True
>>> print( not (10==2 or 20==3 or 5>=50))---------- True

89 manojalladi23@[Link]
>>> 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========================================

90 manojalladi23@[Link]
5. Bitwise Operators (Most Imp)

=>The purpose of Bitwise operators is that "To perform the operations on Integer data
in the fiorm bit by bit".
=>Bitwise Operators applicable on Integer data but not on float data bcoz in floating point data
decimal places does not have fixed value.
=>Bitwise opertator operates on integer data in the form bit by bit and hence they named Bitwise
Operators.
=>Bitwise Operators converts Integer data into Binary Format and operates on integer data in the
form bit by bit depends on type of Bitwise Operator.
=>In Python , we have 6 Bitwise Operators. They are

1) Left Shift Operator ( << )


2) Right Shift Operator ( >> )
3) Bitwise OR Operator ( | )
4) Bitwise AND Operator ( & )
5) Bitwise Complement Operator ( ~ )
6) Bitwise XOR Operator ( ^ )

1) Left Shift Operator ( << ):

Syntax:- varname = GivenNumber << No. of bits


=>This Operator is Flipping-off the number of bits from left side and adding number of zeros (
depending on number of Bits ) at Right Side.

Examples:

>>> a=10
>>> b=3
>>> c=a<<b
>>> print(c) -----------80
>>> print(4<<2) --------16
>>> print(14<<2) ------- 56
>>> print(2<<5) --------64

91 manojalladi23@[Link]
2) Right Shift Operator ( << ):

Syntax:- varname = GivenNumber >> No. of bits


=>This Operator is Flipping-off the number of bits from Right side and adding number of zeros
( depending on number of Bits ) at Left Side
Examples:

>>> a=10
>>> b=3
>>> c=a>>b
>>> print(c) ----------1

92 manojalladi23@[Link]
>>> print(20>>2) ------- 5
>>> print(20>>3) -------- 2

93 manojalladi23@[Link]
3) Bitwise OR Operator ( | ):

=>Syntax:- varname = State1 | State2


=>The Functionality of Bitwise OR Operator described by using the truth table.

State1 State2 State1 | State2

0 0 0

1 0 1

0 1 1

1 1 1

Examples:

>>>a=4 0100
>>>b=3 0011

>>>c=a|b 0111 result is 7

>>> a=10
>>> b=15
>>> c=a|b
>>> print(c) -----------15
>>> print(2|5) -------- 7

Special Case:

>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=[Link](s2)
>>> print(s3,type(s3))
{50, 20, 40, 10, 30} <class 'set'>

>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s4=s1|s2 # Bitwise OR Operator
>>> print(s4,type(s4)) --------------- {50, 20, 40, 10, 30} <class 'set'>

>>> s1={"Apple","kiwi","Sberry"}
>>> s2={"Apple","Sberry","Orange"}
>>> s3=s1|s2
>>> print(s3) --------------------- {'Orange', 'kiwi', 'Apple', 'Sberry'}

94 manojalladi23@[Link]
4) Bitwise AND Operator (& ):

=>Syntax:- varname = State1 & State2


=>The Functionality of Bitwise AND Operator described by using the truth table.

State1 State2 State1 & State2

0 0 0

1 0 0

0 1 0

1 1 1

Examples:

>>>a=4 ------------- > 0 1 0 0


>>>b=5 ------------- > 0 1 0 1

>>>c=a&b-----------> 0 1 0 0 ----------------- Result is 4


>>>print(c) --------- 4

>>> print(4&5) --------------- 4


>>>
>>> print(10&15) ----------- 10
>>> print(4&4) ------------ 4

Special Case:

>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=[Link](s2)
>>> print(s3,type(s3)) ----------- {30} <class 'set'>

>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=s1&s2 ---- Bitwise AND Operator
>>> print(s3,type(s3)) ----------- {30} <class 'set'>

95 manojalladi23@[Link]
5) Bitwise Complement Operator ( ~ ):

=>Bitwise Complement Operator (~) works in such way that " Given Number Converted into
Binary and Converted Binary Number Inverted (Inverted means 0 becomes 1 and 1 becomes 0)"

=>Syntax:- ~Value
or
=>Syntax:- varname= ~Value
Or
=>Syntax:- varname2= ~Variable1

Formula for Bitwise Complement = ~value=> -(value+1)

Examples:

>>>a=4
>>> ~a -5
>>>a=10
>>>b=~a
>>>print(b) -------- 11

>>>a=15
>>>print(~a) ----------- 16
>>> a=102
>>> print(~a) ------------------ 103
>>> print(~456)--------------- 457
>>> a=-103
>>> print(~a) --------------- 102
>>> a=0
>>> print(~a) ------------------ 1

6) Bitwise XOR Operator ( ^ )

=>Syntax:- varname = State1 ^ State2


=>The Functionality of Bitwise XOR Operator described by using the truth table.

State1 State2 State1 ^ State2

0 0 0

1 0 1

0 1 1

1 1 0

96 manojalladi23@[Link]
Examples:

>>>a=5 > 0101


>>>b=3 > 0011

>>>c=a^b ----------------- > 0110


>>>print(c) --------------6
>>> print(10^15) --------- 5

Special case :

>>> s1={10,20,30}
>>> s2={20,30,40,50}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3) ----------------- {40, 10, 50}

>>> s1={10,20,30}
>>> s2={20,30,40,50}
>>> s3=s1^s2 ---- Bitwise XOR
>>> print(s3) ------------ {40, 10, 50}

6. Membership Operators

=>The purpose of Membership Operators is that " To check whether the vakues present or not in
Iterable object"
=>An Iterbale object is one which contains multiple values or Sequence of Values
Examples: Sequence ,list set and dict.
=>In Python Programming, we have two type of Membership Operators. They are
1) in
2) not in

1) in Operator:

=>Syntax:- value in Iterable_object


=>The "in" operator returns True provided "Value" present in Iterable object
=>The "in" operator returns False provided "Value" not present in Iterable object

2) not in Operator:

=>Syntax:- value not in Iterable_object


=>The "not in" operator returns True provided "Value" not present in Iterable object
=>The "not in" operator returns False provided "Value" present in Iterable object

97 manojalladi23@[Link]
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
>>> "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

98 manojalladi23@[Link]
>>> "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

7. Identity Operators ( Python Command Prompt)

=>The purpose of Identity Operators is that " To compare Memory Address of two objects".
=>In Python Programming, we have two types of Identity Operators. They are

1) is
2) is not
=>To get the memory address of an object, we use id()

1) is:

Syntax:- varname= obj1 is obj2


=>"is" operator returns True when obj1 and obj2 contains Same Memory Address
=>"is" operator returns False when obj1 and obj2 contains Different Memory Address

2) is not:

=>Syntax:- varname=obj1 is not obj2


=>"is not" operator returns True when obj1 and obj2 contains Different Memory Address
=>"is not" operator returns False when obj1 and obj2 contains Same Memory Address

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

>>> s1={10,20,30}
>>> s2={10,20,30}
>>> print(s1,type(s1),id(s1))---{10, 20, 30} <class 'set'> 1872670853824

99 manojalladi23@[Link]
>>> 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

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

100 manojalladi23@[Link]
>>> 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))
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

101 manojalladi23@[Link]
>>> 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

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

=>0--256 in multiple objects of int type contains same memory address


=>More Than 256 in multiple objects of int type contains different memory address
=> -1 to -5 in multiple objects of int type contains same memory address
=>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

102 manojalladi23@[Link]
>>> a is not b
False
>>> a=257
>>> b=257
>>> print(a,type(a), id(a))
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
Special Cases

>>> a,b=300,300
>>> print(a,type(a), id(a))

103 manojalladi23@[Link]
300 <class 'int'> 1872662488496
>>> print(b,type(b), id(b))
300 <class 'int'> 1872662488496
>>> a is b --------- 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.500000000000000000000000000000000000000000000000000000000000
>>> a is b ---------- False
>>> a is not b ---------- 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

104 manojalladi23@[Link]
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 True or Y-Operation in the case False) OR Perform
Certain Operation Repeatedly for finite number of time until Test Condition Becomes 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 Repetative 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 Python Programming, Conditional or Selection or Branching Statements are classfied 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)

105 manojalladi23@[Link]
tkt=input("Do u have a ticket(yes/no):")
if([Link]()=="Yes"):
print("Enter into theater")
print("Watch the moviee")
print("Eat!")
print("\nGoto Home and Read Python Notes!")

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

#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))
106 manojalladi23@[Link]
if(a==b==c):
print("ALL VALUES ARE EQUAL")

#program for finding biggest among 3 numbers


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

#Program for accepting a digit and print its name


#[Link]
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))
107 manojalladi23@[Link]
else:
if(d==8):
print("{} is EIGHT".format(d))
else:
if(d==9):
print("{} is NINE".format(d))
else:
print("{} is number:".format(d))

#Program for accepting a digit and print its name


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


#[Link]
d1={1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT",9:"N
INE",0:"ZERO"}
dig=int(input("Enter a Digit:"))
res=[Link](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


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

108 manojalladi23@[Link]
109 manojalladi23@[Link]
#Program for accepting a digit and print its name

#[Link]

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

#Program for payslip


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

110 manojalladi23@[Link]
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)

match .. case statement (Python 3.10)


=>It is one of new Feature in Python 3.10
=>This features is also known as Multi way decision making statement.
=>Syntax:
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

111 manojalladi23@[Link]
Other statements 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) Writting default case label is optional.
7) If we write default case label then we must write it at last otherwise we get SyntaxError.

#Program for implementing all AOPs by using menus


#[Link]
print("="*50)
print("\tArithmetic Operations")
print("="*50)
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link] Div")
print("\[Link]")
print("\[Link]:")
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))

112 manojalladi23@[Link]
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")

2. Looping or Iterative or Repetative Statements

=>The purpose of Looping or Iterative or Repetative Statements is that "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 any looping statements, we have to follow 3 steps. They are

1. Initlization Part
2. Conditional Part
3. Updation Part ( Incrementation or Decrementation )

113 manojalladi23@[Link]
#Program for generating 1 to n numbers where n is +ve
#[Link]
n=int(input("Enter Value of n:")) # n= 5
if(n<=0):
print("{} is invalid input".format(n))
else:

114 manojalladi23@[Link]
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:")

#Program for generating 1 to n numbers where n is +ve


#[Link]
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
else:
print("*"*50)
print("\nProgram execution completed:")

#Program for generating n to 1 where n is +ve


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

115 manojalladi23@[Link]
#Program mul table for a given number n where n is +ve
#[Link]
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)

#Program for accepting a line of text and display all chars


#[Link]
line=input("Enter Line of Text:") # PYTHON
i=0
while(i<len(line)):
print("\t{}".format(line[i]))
i=i+1

#Program for accepting a line of text and display all chars


#[Link]
line=input("Enter Line of Text:") # PYTHON
line=line[::-1]
i=0
while(i<len(line)):
print("\t{}".format(line[i]))
i=i+1

116 manojalladi23@[Link]
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

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.

117 manojalladi23@[Link]
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")

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

text=input("Enter a line of text:")


print("Given Line={}".format(text))#Python
print("="*50)
for ch in text:
print("\t{}".format(ch))

118 manojalladi23@[Link]
#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)

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

#program finding sum of natural numberrs, squares and cubes first natural nums
#[Link]
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:

119 manojalladi23@[Link]
print("="*50)
print("\t{}\t{}\t{}".format(s,ss,cs))
print("="*50)

#Program accepting a number and find sum of its digits


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

#Program for cal factrial of a given number


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

#Program to deciding whether the given number or name is palindrome or no


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

120 manojalladi23@[Link]
#Program for co nverting Ordinary Number into Roman Eqv.
#[Link]
n=int(input("Enter a number:"))
if(n<=0):
print("No Roman Number:")
else:
while(n>=1000):
print("M",end="")

121 manojalladi23@[Link]
n=n-1000
if(n>=900):
print("CM",end="")
n=n-900
if(n>=500):
print("D",end="")
n=n-500
if(n>=400):
print("CD",end="")
n=n-400
while(n>=100):
print("C",end="")
n=n-100
if(n>=90):
print("XC",end="")
n=n-90
if(n>=50):
print("L",end="")
n=n-50
if(n>=40):
print("XL",end="")
n=n-40
while(n>=10):
print("X",end="")
n=n-10
if(n>=9):
print("IX",end="")
n=n-9
if(n>=5):
print("V",end="")
n=n-5
if(n>=4):
print("IV",end="")
n=n-4
while(n>=1):
print("I",end="")
n=n-1

122 manojalladi23@[Link]
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 prtogram".
=>when break statement takes place inside for loop or while loop then PVM will not
corresponding else block(bcoz loop is not becming False) but it executes other statements in the
program
=>Syntax1:

for varname in Iterable_object:

if (test cond):
break

=>Syntax2:

while(Test Cond-1):

if (test cond-2):
break

#This program demonstrates the functionality of break statement


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

#This program demonstrates the functionality of break statement


#[Link]
s="PYTHON"
i=0
while(i<len(s)):
if(s[i]=="H"):
break
else:

123 manojalladi23@[Link]
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else block of while loop")
print("other statements in program")

#program for decinding wthether the number is prime or not\


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

#program for decinding wthether 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))

#program for decinding wthether 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

124 manojalladi23@[Link]
if(result=="prime"):
print("{} is a prime".format(n))
else:
print("{} is not a prime".format(n))

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

while (Test Cond):

if ( Test Cond):
continue
statement-1 # written after continue stateemnt
statement-2
statement-n

125 manojalladi23@[Link]
#Program for demonstrating continue statement
#[Link]-----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")
Program for demonstrating continue statement

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

#Program for demonstrating continue statement


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

126 manojalladi23@[Link]
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

while(Tesd Cond2): # Inner while loop

else:

else:

Other statements in Program

127 manojalladi23@[Link]
=>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====================================
#Program for demonstrating inner or nested loop --- for loop in for loop
#[Link]
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")

128 manojalladi23@[Link]
print("-"*40)
print("\n Program Execution Completed!")

Output:

"""

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

Value of i--outer for loop:1

129 manojalladi23@[Link]
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!


"""

130 manojalladi23@[Link]
#Program for demonstrating inner or nested loop -----while loop in while loop
#[Link]
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!")

Output:
“””

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

131 manojalladi23@[Link]
Value of j--inner while loop:3
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!


"""

#Program for demonstrating inner or nested loop --- while loop in for loop
#[Link]
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!")

Ouput:
"""

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

Value of j--inner while loop:3

132 manojalladi23@[Link]
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!

"""

#Program for demonstrating inner or nested loop --- for loop in while loop
#[Link]
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)
else:
print("Out of outer while loop")
print("-"*40)

133 manojalladi23@[Link]
print("\n Program Execution Completed!")

#program for accepting list of value and generate mul tables for all +ve numbers
#[Link]
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)))
[Link](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)
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)

#program for generating mul table for 1 to 20


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

134 manojalladi23@[Link]
#[Link]
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))
"""
Output:

i=1
j=10
k=50
k=51
j=11
k=50
k=51
i=2
j=10
k=50
k=51
j=11
k=50
k=51
"""

#program which for will accept list of numeric values. Separate positive values and
negative [Link] program which for will accept list of numeric values. Separate positive
values and negative values.
#[Link]
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)))
[Link](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):
135 manojalladi23@[Link]
continue
else:
[Link](val)
#get Negative Values
nl=[]
for val in lst:
if(val>=0):
continue
else:
[Link](val)
else:
print("Possitive List={}".format(pl))
print("Negative List={}".format(nl))

Functions in Python

Index

=>Purpose of Functions
=>Definition of Functions
=>Types of Functions
1) Pre-defined Functions
2) Programmer / User / Custom Defined Functions
=>Parts of Functions
=>Phases in Functions
=>Syntax for Defining Functions
=>Number of Approaches to define Programmer-defined Functions
=>Programming Examples

=>Arguments and Parameters


=>Types of Arguments
1. Possitional Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable length Arguments
5. Keyword Variable length Arguments
=>Programming Examples
=>Global Variables and Local Variables
=>global keyword and globals()
=>Programming Examples

=>Anonymous Functions or Lambda Functions


=>Syntax for defining Anonymous Function or Lambda Functions
=>Programming Examples

=>Special Functions in Python

136 manojalladi23@[Link]
a) filter() with Normal and Anonymous Functions
b) map() with Normal and Anonymous Functions
c) reduce with Normal and Anonymous Functions
=>Programming Examples

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 [Link] 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 Performnace is Degrading
5. Redundency (Duplication or replication) of the code is More

Examples: GW-BASIC

2. Structured Programming Languages.

=>In Structured Programming Languages, There is a concept of [Link] that Structured


Programming Languages contains the following advatnages.
[Link] Development time is Less
2. Application Memory Space is Less
3. Application Execution is Less
4. Application Performnace is Enhancing
5. Redundency (Duplication or replication) of the code is Minimized

Examples:- C,C++,JAVA, .NET , PYTHON...etc

Functions in Python
=>The purpose of Functions concept is that " To perform certain Operations and Provides Code
Re-Usability ."

=>Definition of Function: A part of main program is called Function


(OR)
SubProgram of main program is called Function

137 manojalladi23@[Link]
=>Parts of Functions:
=>At the time of dealing with Functions in Python, we must ensure that there must exists 2 parts.
They are

1) Function definition
2) Function Call
=>Perticular 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 executing the
function by itself.

=>Phases of Functions:

=>When we define a function, we must ensure that there musty exists 3 phases. They are
1. Taking INPUT
2. Doing the PROCESS
3. giving OUTPUT / RESULT.

138 manojalladi23@[Link]
Number of approaches to define a function
=>Inpython Programming, we have 4 approaches to define a function. they are

Approach-1

Input : Function Call


Process: Function Body
Output: Functrion Call

Example:

#[Link]

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

Approach-2

Input : Function Body


Process: Function Body
Output: Functrion Body

Examples:

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

139 manojalladi23@[Link]
Approach-3
Input : Function Call
Process: Function Body
Output: Functrion Body

Examples:

#[Link]
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: Functrion Call

Examples:

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

140 manojalladi23@[Link]
#[Link]
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

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

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

#[Link]
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
141 manojalladi23@[Link]
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]))

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)))
[Link](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
[Link]()
print("Sorted Elements--Asending Order")
for val in result:
print("\t{}".format(val))
#sort the data--ASC Irder
[Link](reverse=True)
print("Sorted Elements--Decending Order")
for val in result:
print("\t{}".format(val))

#main program
sortvalues()

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

142 manojalladi23@[Link]
val=float(input("Enter {} Value:".format(i)))
[Link](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
[Link]()
print("Sorted Elements--Asending Order")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
[Link](reverse=True)
print("Sorted Elements--Decending Order")
dispvalues(result) # Function Chaining
#main program
sortvalues()

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

143 manojalladi23@[Link]
else:
print("Sum={}".format(s))
print("Avg={}".format(s/len(result)))
#main program
result=readvalues()
computersumavg(result)

#Program for finding max and min from list of values by using Functions
#[Link]
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))

#Program for finding max and min from list of values by using Functions
#[Link]
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():

144 manojalladi23@[Link]
lst=readvalues()
return min(lst)

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

List comprehension
=>The purpose of List comprehension is that to read the values dynamically from key board
separated by a delimeter ( space, comma, colon..etc)
=>List comprehension is the most effective way for reading the data for list instead tradtional
reading the data.
=>Syntax:- listobj=[ expression for varname in Iterable_object ]
=>here expression represents either type cating or mathematical expression

Examples:

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 ]

#[Link]
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())
[Link](val)
else:

145 manojalladi23@[Link]
print("content of lst",ls)

#[Link]
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:
[Link](val*2)
else:
print("new list=",newlst)
print("-"*40)
print("==============OR=================")
newlst=[ val*2 for val in lst]
print("new list=",newlst)

#This program accept list of values dynamically by using list comprehension and sort them
#[Link]
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)

def sortelements(lst):
print("Original Elements")
disp(lst)
[Link]()
print("Sorted Elements in Ascending Order")
disp(lst)
[Link]() # or [Link](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)

146 manojalladi23@[Link]
#This program accept list of names dynamically by using list comprehension and sort them
#[Link]
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)

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

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

#Program for finding max and min from list of values by using Functions
#[Link]
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()

147 manojalladi23@[Link]
lst=[10,12,45,6,23]
sqlist=[]
for val in lst:
res=val**2
[Link](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))

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

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 Function calls.
=> Local Parameters aare 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:


functioncall(list of arguments)

=>The relationship between arguments and Parameters is that Every Value of argument is
passing Formal Parameter.

#[Link]
def disp(a,b):
print("val of a={}".format(a))
148 manojalladi23@[Link]
print("val of b={}".format(b))

#main program
x=input("Enter Val of x:")
y=input("Enter Val of y:")
disp(x,y)

Number of Arguments and Parameters


=>Based on the values of arguments passing to parameters, the arguments are classified into 5
types. They are

1. Possitional Arguments (default )


2. Defualt Arguments.
3. Keyword Arguments.
4. Variable Length Arguments.
5. Keyword Variable Length Arguments.

1) Possitional Arguments (or) Parameters

=>The Concept of Possitional Parameters (or) arguments says that "The Number of
Arguments(Actual arguments ) must be equal to the number of formal parameters ".
=>This Parameter mechanism also recommends Order and Meaning of Parameters for Higher
accuracy.
=>To pass the Specific Data from Function Call to Function Definition then we must take
Possitional Argument Mechanism.
=>The default Argument Passing Mechanism is Possitional Arguments (or) Parameters.

Syntax for Function Definition :

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

Syntax for Function Call:

functionname(arg1,arg2. .. arg-n)

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

149 manojalladi23@[Link]
2) Default Parameters(or) arguments
=>When there is a Common Value for family of Function Calls then Such type of Common
Value(s) must be taken as default parameter with common value (But not recommended to pass
by using Posstional Parameters)

Syntax: for Function Definition with Default Parameters

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

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


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

Rule-: When we use default parameters in the function definition, They must be used as last
Parameter(s) otherwise we get Error( SyntaxError: non-default argument (Possitional ) follows
default argument).

#program for demonstrating Possitional Arguments concept


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

#program for demonstrating Possitional Arguments concept


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

150 manojalladi23@[Link]
dispstudinfo(30,"MC",14.16,"PYTHON") # Function Call
dispstudinfo(40,"RT",56.78,"PYTHON") # Function Call
print("="*50)

#program for demonstrating Default Arguments concept


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

#program for demonstrating Default Arguments concept


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

151 manojalladi23@[Link]
#program for demonstrating Default Arguments concept
#program
#[Link]
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)

#program for demonstrating Default Arguments concept


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

def readvalues():
n=int(input("Enter how many Names u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=input("Enter {} Name:".format(i))
[Link](val)
return lst
def dispvalues(lst):
print("="*50)
for val in lst:
print("\t{}".format(val))
print("="*50)

def sortnames():
152 manojalladi23@[Link]
result=readvalues() # Function Chaining
if(result==None):
print("No Elements are present and nothing to sort")
else:
print("Original Names")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
[Link](reverse=False)
print("Sorted Names-Asending Order")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
[Link](reverse=True)
print("Sorted Names--Decending Order")
dispvalues(result) # Function Chaining
#main program
sortnames()

2) Keyword Parameters (or) arguments

=>In some of the circumstances, we know the function name and formal parameter names and
we don't know the order of formal Parameter names and to pass the data / values accurately we
must use the concept of Keyword Parameters (or) arguments.
=>The implementation of Keyword Parameters (or) arguments says that all the formal parameter
names used as arguments in Function call(s) as keys.

Syntax for function definition:-

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

Syntax for function call:-

functionname(param-n=val-n,param1=val1,param-n-1=val-n-1, ..... )

Here param-n=val-n,param1=val1,param-n-1=val-n-1, ...... are called Keywords arguments

3) Variables Length Parameters (or) arguments

=>When we have familiy of multiple function calls with Variable number of values / arguments
then with normal python programming, we must define mutiple function defintions. This process
leads to more development time. To overcome this process, we must use the concept of Variable
length Parameters .
=>To Impelement, Variable length Parameters concept, we must define single Function
Definition and takes a formal Parameter preceded with a symbol called astrisk ( * param) and the
formal parameter with astrisk symbol is called Variable length Parameters and whose purpose is
to hold / store any number of values coming from similar function calls and whose type is <class,

153 manojalladi23@[Link]
'tuple'>.

Syntax for function definition with Variables Length Parameters:

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

=>Here *param is called Variable Length parameter and it can hold any number of argument
values (or) variable number of argument values and *param type is <class,'tuple'>

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

=>Rule:- When we use Variable length and default parameters in function Heading, we use
default parameter as last and before we use variable length parameter and in function calls, we
should not use default parameter as Key word argument bcoz Variable number of values are
treated as Posstional Argument Value(s)

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

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

154 manojalladi23@[Link]
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

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


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

155 manojalladi23@[Link]
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)

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

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

156 manojalladi23@[Link]
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)

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

#[Link]
def dispempinfo(eno,ename,sal,dsg,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,crs))

#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,"[Link]","JAVA")
dispempinfo(sal=3.4,crs="[Link]",eno=60,dsg="PM",ename="DT")
print("="*50)

157 manojalladi23@[Link]
4) Key Word Variables Length Parameters(or) arguments
=>When we have familiy of multiple function calls with Key Word Variable number of values /
arguments then with normal python programming, we must define mutiple function defintions.
This process leads to more development time. To overcome this process, we must use the
concept of Keyword Variable length Parameters .
=>To Implement, Keyword Variable length Parameters concept, we must define single Function
Definition and takes a formal Parameter preceded with a symbol called double astrisk ( **
param) and the formal parameter with double astrisk symbol is called Keyword Variable length
Parameters and whose purpose is to hold / store any number of (Key,Value) coming from
similar function calls and whose type is <class, 'dict'>.

Syntax for function definition with Keyword Variables Length Parameters:

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

=>Here **param is called Keyword Variable Length parameter and it can hold any number of
Key word argument values (or) Keyword variable number of argument values and **param type
is <class,'dict'>

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

Final Syntax:

def funcname(PosFormal parms, *Varlenparams, default params, **kwdvarlenparams):

#Program demonstrating Keyword Variable length Arguments


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

158 manojalladi23@[Link]
#Program demonstrating Keyword Variable Length Arguments
#[Link]---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

#Program demonstrating Keyword Variable length Arguments


#[Link]
def dispinfo( **k ):
print("-"*50)
for k,v in [Link]():
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.
#[Link]
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 [Link]():
print("\t{}--->{}".format(sn,sm))
totmarks=totmarks+sm
if(totmarks>0):
print("Total Marks={}".format(totmarks))
per=(totmarks / (len(submarks)*100))*100
159 manojalladi23@[Link]
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,Chemistry=54)
findtotalmarks(30,"Manaiah","[Link](CSE)",CM=70,Python=60)
findtotalmarks(40,"Rossum","Research")

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

#[Link]
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 [Link]():
print("\t{}-->{}".format(k,v))
print("="*50)

#main program
disp(1,"RS",10,20,30,a=100,b=200)

160 manojalladi23@[Link]
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)

Global variables and Local Variables


=>Local Variables are those which are defined / used Inside of Function Body.
=>Local Variables 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 variables for functiondefinition1() and

functiondefinition2()
=>here Var22,Var23... are called Local Varbales variables functiondefinition1()
=>here Var32,Var33... are called Local Varbales variables in functiondefinition2()

161 manojalladi23@[Link]
Examples:
#[Link]
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()

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

#[Link]
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
162 manojalladi23@[Link]
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()

#[Link]
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
lang="Python" # Here lang is called Global variable
learnDS()
learnML()
learnDL()

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

163 manojalladi23@[Link]
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()

global key word


=>When we want MODIFY the GLOBAL VARIABLE values in side of function defintion then
global variable names must be preceded with 'global' keyword otherwise we get
"UnboundLocalError: local variable names referenced before assignment"

Syntax:

var1=val1
var2=val2
var-n=val-n # var1,var2. var-n are called global variable names.

def fun1():

global var1,var2...var-n
# Modify var1,var2. ..var-n

def fun2():

global var1,var2...var-n
# Modify var1,var2. .. var-n

Examples:

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

#[Link]
a=10
def access1():
global a # refering global Varaible before its updation / Modification

164 manojalladi23@[Link]
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

Examples:

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

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

165 manojalladi23@[Link]
#[Link]
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

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

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

166 manojalladi23@[Link]
Global and local varibles and globals()
=>When we come acrosss same global Variable names and Local Vraiable Names in same
function definition then PVM gives preference for local variables but not for global variables.
=>In this context, to extract / retrieve the values of global variables names along with local
variables, we must use globals() and it returns an object of <class,'dict'> and this dict object
stores all global variable Names as Keys and global variable values as values of value.

=>Syntax:-
var1=val1
var2=val2

var-n=val-n # var1, var2...var-n are called global Variables


def functionname():

var1=val11
var2=val22

var-n=val-nn # var1, var2...var-n are called local Variables


# Extarct the global variables values
dictobj=globals()

globalval1=dictobj['var1'] # or [Link]("var1") or globals()['var1']


globalval2=dictobj['var2'] # or [Link]("var2") or globals()['var2']

Examples:

#[Link]
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in [Link]():
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")

167 manojalladi23@[Link]
print("="*50)
print("Val of a=", [Link]('a'))
print("Val of b=", [Link]('b'))
print("Val of c=", [Link]('c'))
print("Val of d=", [Link]('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()

Examples:

#Program for demonstrating globals()


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

168 manojalladi23@[Link]
#globalsfunex1
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')+globals()['c']+globals()['d']
print("result=",res)
#main program
operation()
-
#[Link]
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 [Link]():
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=",[Link]('a'))
print("val of b=",[Link]('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()

169 manojalladi23@[Link]
Anonymous Functions or Lambda Functions
=>Anonymous Functions are those which does not contain the any name explicitly.
=>The purpose of Anonymous Functions is that " To perform Instant Operations ".
=>Instant Operations are those which are used at that point of time and no longer interested to
use in further applications.
=>To define Anonymous Functions, we use a keyword lambda and Anonymous Functions are
also called Lambda Function.
=>Anonymous Functions contains single executable statement but not containing block of
statements.
=>Anonymous Functions returns the result automatically (No need to use write return
statement explicitly ).

Syntax:

varname=lambda params-list : expression

Explanation:

=>here "varname" is an object and it itself acts as Function Name bcoz 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 reprsents single executable statement and it performs Instant Operation and
whose result returned automatically.

#Normal Function Definition Finction Call

def sumop(a,b): res1=sumop(10,20)


c=a+b print("sum=",res1)
return c

#Anonymous Function Definition Finction Call

sumop=lambda a,b:a+b res1=sumop(100,200)


print("sum=",res1)

170 manojalladi23@[Link]
#program for performing sum of two number by using Anonymous Functions
#[Link]
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)
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.


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

171 manojalladi23@[Link]
#Program for performing finding biggest and smallest among two numbers

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

#write a python program which will accept list of numerical values and find max and min
by using anonymous functions
#[Link]
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))

172 manojalladi23@[Link]
Special Functions in Python
=>In Python Programming, we have 3 special Functions. They are
1. filter()
2. map()
3. reduce()

1) filter():

=>filter() is used for "Filtering out some elements 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 iteratable object
by using type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of filter() is that " Each Value of Iterable object sends to Function
Name. If the function return True then the element will be filtered. if the Function returns False
then that element will be neglected/not filtered ". This process will be continued until all
elements of Iterable object completed.

2) map()

=>map() is used for obtaining new Iterable object from existing iterable object by applying old
iterable elements to the function.
=>In otherwords, map() is used for obtaining new list of elements from existing existing list of
elements by applying old list elements to the function.

=>Syntax:- varname=map(FunctionName,Iterable_object)

=>here 'varname' is an object of type <class,map'> and we can convert into any iteratable object
by using type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of map() is that " map() sends every element of iterable object to the
specified function, process it and returns the modified value (result) and new list of elements will
be obtained". This process will be continued until all elements of Iterable_object completed.

#Program for filtering Possitive Elements from list of elements by using NormalFunction

173 manojalladi23@[Link]
#[Link]
def positive(n):
if n>0: return True

else: return False

def negative(n):
if n<0:
return True
else:
return False

#main program
lst=[10,20,-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
#[Link]

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


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

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

174 manojalladi23@[Link]
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.
#[Link]
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)

#write a python program which will accept line of text and obtains list of vowels by using
filter()
#[Link]
def cons(ch):
if ch not in ['a','e','i','o','u','A','E','I','O','U'] and [Link]():
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)

175 manojalladi23@[Link]
print("Number of consonats=",len(conslist))

#Program for obtaining Square for every element of list by using map() with Normal
Function
#[Link]
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
#[Link]
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()
#[Link]
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)

176 manojalladi23@[Link]
3) Reduce
=>reduce() is used for obtaining a single element / result from given iterable object by applying
to a function.
=>Syntax:-
varname=reduce(function-name,iterable-object)
=>here varname is an object of int, float,bool,complex,str only
=>The reduce() belongs to a pre-defined module called" functools".

Internal Flow of reduce()

Step-1:- reduce() selects two First values of Iterable object and place them in First var
and Second var .
Step-2:- The function-name(lambda or normal function) utilizes the values of First var and
Second var applied to the specified logic and obtains the result.
Step-3:- reduce () places the result of function-name in First variable and reduce()
selects the succeeding element of Iterable object and places in second variable.
Step-4: Repeat Step-2 and Step-3 until all elements completed in
Iterable object and returns the result of First Variable

177 manojalladi23@[Link]
#Program for reading list of values and obtains sum by using reduce()
#[Link]
import functools
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
result=[Link](lambda x,y: x+y,lst)
print("Sum({})={}".format(lst,result))

#Program for reading list of values and obtains sum by using reduce()
#[Link]
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=[Link](sumop,lst)
print("Sum({})={}".format(lst,result))

#write a python program which will accept list of names or words and concatnet them
#[Link]
import functools as k
print("Enter List of words separated by comma:")
lst=[str(val) for val in input().split(",")]
line=[Link](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()
#[Link]
import functools as k
print("Enter List of values separated by comma:")
lst=[int(val) for val in input().split(",")]
maxv=[Link](lambda a,b: a if a>b else b, lst)
minv=[Link](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()
#[Link]
import functools as k
print("Enter List of words separated by comma:")
lst=[str(val) for val in input().split(",")]
178 manojalladi23@[Link]
maxv=[Link](lambda a,b: a if a>b else b, lst)
minv=[Link](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 numericle values and find squares for
positive numbers and cubes for negative numbers
#[Link]
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
#[Link]
import functools as kvr
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
possum=[Link](lambda x,y:x+y, list(filter(lambda x : x>0, lst)))
negsum=[Link](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.
#[Link]
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)

179 manojalladi23@[Link]
Modules
Index

=>Purpose of Modules
=>Definition of Module
=>Types of Modules
a) Pre-defined Modules
b) Programmer-defined modules
=>Development Programmer-Defined Modules
=>Techniques for Re-Using the Modules
1) by using import statement (4 syntaxes )
2) By using from ... import statement (3 syntaxes )
=>Programming Examples
=>Re-loding the Modules
=>Programming Examples

Modules in Python
=>We know that Functions concept makes us understand How to perform operations and we can
re-use within the same program but not able to re-use the functions across the programs.
=>To reuse the functions and global variables across the programs, we must use the concept of
MODULES.

=>Definition of Module:

=>A Module is a collection of variables (global variables) , Functions and Classes.

=>Types of Modules:

=>In Python Programming, we have two types of Modules. They are


1) Pre-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 avialable in
Python Software (APIs) and they are used python programmers for dealing with Universal
Requirements.

Examples: math cmath functools sys calendar os


re threading pickle random ...... etc

=>Out of many pre-defined modules, in python programming one implicit pre-defined module
imported to every python program called "builtins" .

180 manojalladi23@[Link]
2) Programmer or user or custom-defined modules:
=>These modules are developed by Python Programmers and they are avialable 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

Development of Programmer-Defined Module

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

Step-1: Define Variables (Global variables)


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

=>After developing step-1, step-2 and step-3 , we must save on some file name with an
extension .py ([Link]) and it is treated as module name.
=>When a file name treated as a module name , internally Python execution environment creates
a folder automatically on the name of pycache__ and it contains module name on the name of
"[Link] ".

Examples:

pycache < ---- Folder Name

[Link] < ----------------- Module Name


[Link]<--------------- Module Name
[Link]< -------------------- Module Name

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 [Link] are
1) By using import statement
2) By using from ..... import statement.

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.

181 manojalladi23@[Link]
=>Syntax-1: import module name
=>This syntax imports single module

Example: import icici


import aop
import mathsinfo

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

=>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 [Link] Name
Module [Link] Name
Module [Link] Name
(OR)
Alias [Link] Name
Alias [Link] Name
Alias [Link] Name

182 manojalladi23@[Link]
2) By using from ..... import statement.
=>Here "form" "import" are the key words
=>The purpose of from .....import statement is that " To refer or access the variable names,
function names and class names in current program directly without writing module name."
=> 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.

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 recommmended to use bcoz it imports required Features of Module and also
import un-interrested 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

=>Hence with "import statement" we can give alias name for module names only but not for
Variables Names, Function Names and Class Names. Where as with "from ... import statement "

183 manojalladi23@[Link]
we can give lias names for Variables Names, Function Names and Class Names but not for
Module Name.

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

#[Link]
import icici
import aop
[Link]()
[Link](10,20)

#[Link]
import icici, aop
[Link]()
[Link](10,20)

#[Link]
import icici as ic
import aop as a
[Link]()
[Link](10,20)

#[Link]
import icici as ic, aop as a
[Link]()
[Link](10,20)

#[Link]
from icici import bname, loc, simpleint
print("\nBank Name:{}".format(bname))
print("\nBank Location:{}".format(loc))
simpleint()

#[Link]
from icici import bname as bn, loc as l, simpleint as si
184 manojalladi23@[Link]
print("\nBank Name:{}".format(bn))
print("\nBank Location:{}".format(l))
si()

#[Link]
from icici import *
print("\nBank Name:{}".format(bname))
print("\nBank Location:{}".format(loc))
simpleint()

#[Link]---file name and acts as Module Name


bname="ICICI"
loc="Ameerpet" # here bname and loc are global var
def simpleint(): # Function Def.
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interrest:"))
#cal si and totamt to pay
si=(p*t*r)/100
totamt=p+si
print("-"*50)
print("Principle Amount:{}".format(p))
print("Time:{}".format(t))
print("Rate of Interest:{}".format(r))
print("Simple Interest:{}".format(si))
print("Total Amount to Pay:{}".format(totamt))
print("-"*50)

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


PI=3.14
E=2.71

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


def sharesinfo():
d={"IT":401,"Pharma":301,"Fin":371,"Auto":150}
return d

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

185 manojalladi23@[Link]
print("\t{}\t\t{}".format(sn,sv))
print("="*50)

#main program
dt=[Link]()
dispshares(dt)
print("Line-16-->PVM is going to sleep for 20 secs")
[Link](20) # PVM pause the execution
print("Line-18-->PVM is commig out of sleep ")
[Link](shares)
dt=[Link]()
dispshares(dt)

#[Link]--file name and acts module name


def menu():
print("="*50)
print("\tArithmetic Operations")
print("="*50)
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link] Div")
print("\[Link]")
print("\[Link]")
print("="*50)

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

def readvalues(op):
a=float(input("Enter First Value for {}".format(op)))
b=float(input("Enter Second Value for {}".format(op)))
return a,b

def addop():
x,y=readvalues("addition")
print("sum({},{})={}".format(x,y,x+y))

def subop():
k,v=readvalues("Substraction")
print("sub({},{})={}".format(k,v,k-v))
def mulop():
k,v=readvalues("Multiplication")
print("mul({},{})={}".format(k,v,k*v))
def divop():
k,v=readvalues("Division")

186 manojalladi23@[Link]
print("Div({},{})={}".format(k,v,k/v))
print("Floor Div({},{})={}".format(k,v,k//v))
def modop():
k,v=readvalues("Modulo Div")
print("mod({},{})={}".format(k,v,k%v))
def expoop():
k=float(input("Enter Base:"))
v=float(input("Enter Power:"))
print("pow({},{})={}".format(k,v,k**v))

#[Link]--main program
from aopmenu import menu
import sys
from oprations import addop,subop,mulop,divop,modop,expoop
while(True):
menu()
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
addop()
case 2:
subop()
case 3:
mulop()
case 4:
divop()
case 5:
modop()
case 6:
expoop()
case 7:
print("Thx for using this Program!")
[Link]()
case _:
print("Ur Selection of Operation is wrong-Try again")

187 manojalladi23@[Link]
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 same folder but
unable to provide code re-usability across the folders / drives / enviroments.

=>The Package Concept is a collection of Modules.


=>The purpose of Packages is that to provide code re-usability across the folders / drives /
enviroments.

=>To deal with the package, we need to the learn the following.
a) create a package
b) re-use the package

a) create a package:

=>To create a package, we use the following steps.


i) create a Folder
ii) place / write an empty python file called init__.py
iii) place / write the module(s) in the folder where is it considered as Package
Name

Example:

bank < ---- Package Name

init .py < --- Empty Python File


[Link] < ---Module Name
[Link] ---- Module Name
[Link] -- Module Name
[Link] < --- Module Name

188 manojalladi23@[Link]
b) re-use the package
=>To the re-use the modules of the packages across the folders / drives / enviroments, we have
to two approaches. They are
iv) By using sys module
v) by using PYTHONPATH Environmental Variable Name

i) By using sys module:

Syntax:
----------- [Link]("Absolute Path of Package")

=>sys is pre-defined module


=>path is a pre-defined 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)

Example:

[Link]("E:\\KVR-PYTHON-6pM\\ACKAGES\\BANK")
(or)
[Link]("E:\KVR-PYTHON-6PM\ACKAGES\BANK")
(or)
[Link]("E:\KVR-PYTHON-6PM/ACKAGES/BANK")

ii) by using PYTHONPATH Enviromental Variables:

=>PYTHONPATH is one of the Enviromental Variable


=>Search for Enviromental Variable
Steps for setting :

Var name : PYTHONPATH


Var Value : E:\KVR-PYTHON-7AM\PACKAGES\BANK

The overall path


PYTHONPATH= E:\KVR-PYTHON-11AM\PACKAGES\BANK

189 manojalladi23@[Link]
#[Link]---file name and acts as module name
sname="Rossum"
def greet(s):
print("Hi {}, Good Evening:".format(s))

init__.py

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

190 manojalladi23@[Link]
#[Link]---file name and acts as Module Name
bname="ICICI"
loc="Ameerpet" # here bname and loc are global var
def simpleint(): # Function Def.
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interrest:"))
#cal si and totamt to pay
si=(p*t*r)/100
totamt=p+si
print("-"*50)
print("Principle Amount:{}".format(p))
print("Time:{}".format(t))
print("Rate of Interest:{}".format(r))
print("Simple Interest:{}".format(si))
print("Total Amount to Pay:{}".format(totamt))
print("-"*50)

init .py

#[Link]--file name and acts module name


def menu():
print("="*50)
print("\tArithmetic Operations")
print("="*50)
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link] Div")
print("\[Link]")
print("\[Link]")
print("="*50)

#[Link]--file name and module name


from aopmenu import menu
import sys
from oprations import addop,subop,mulop,divop,modop,expoop
def runproj():
while(True):
menu()
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
191 manojalladi23@[Link]
addop()
case 2:
subop()
case 3:
mulop()
case 4:
divop()
case 5:
modop()
case 6:
expoop()
case 7:
print("Thx for using this Program!")
[Link]()
case _:
print("Ur Selection of Operation is wrong-Try again")

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

def readvalues(op):
a=float(input("Enter First Value for {}".format(op)))
b=float(input("Enter Second Value for {}".format(op)))
return a,b
def addop():
x,y=readvalues("addition")
print("sum({},{})={}".format(x,y,x+y))

def subop():
k,v=readvalues("Substraction")
print("sub({},{})={}".format(k,v,k-v))

def mulop():
k,v=readvalues("Multiplication")
print("mul({},{})={}".format(k,v,k*v))
def divop():
k,v=readvalues("Division")
print("Div({},{})={}".format(k,v,k/v))
print("Floor Div({},{})={}".format(k,v,k//v))
def modop():
k,v=readvalues("Modulo Div")
print("mod({},{})={}".format(k,v,k%v))
def expoop():
k=float(input("Enter Base:"))
v=float(input("Enter Power:"))
print("pow({},{})={}".format(k,v,k**v))

192 manojalladi23@[Link]
realoding a modules in python
=>To reaload a module in python , we use a pre-defined function called reload(), which is
present in imp module and it was deprecated in favour of importlib module.
=>Syntax:- [Link](module name)
(OR)
[Link](module name) ---- recommended

=>Purpose / Situation:

=>reaload() reloads a previously imported module.


=>if we have edited the module source file by using an external editor and we want to use the
changed values/ updated values / new version of previously loaded module then we use reload().

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


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

#main program
#[Link]
import shares
import time
import importlib
def disp(d):
print("-"*50)
print("\tShare Name\tValue")
print("-"*50)
for sn,sv in [Link]():
print("\t{}\t\t:{}".format(sn,sv))
else:
print("-"*50)

#main program
d=[Link]()
disp(d)
[Link](15)
[Link](shares) # relodaing previously imported module
d=[Link]() # obtaining changed / new values of previously imported module
disp(d)

193 manojalladi23@[Link]
Exception Handling in Python

Index

=>Purpose of Exception Handling


=>Types of Errors in Python
a) Compile Time Errors
b) Logical Errors
c) Runtime Errors
=>Define Exception
=>Define Exception Handling
=>Types of Exceptions
a) Pre-defined or Built-in Exceptions
b) Programmer/ User / Custom Defined Exceptions
=>Handling Exceptions
=>Keywords 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

=>The purpose of Exception handling is that " To build ROBUST (Strong) Applications".
=>To Develop any real time application, we need to choose a programming [Link] 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 classfied into 3 types. They are
a) Compile Time Errors
b) Logical Errors
c) Runtime Errors

194 manojalladi23@[Link]
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.

a) Logic Errors:

=>These errors occurs during Execution or Run time.


=>These errors occurs due to Wrong Representation of Logic.
=>These errors occurs always generates Wrong Result
=>These errors solved by Programmer during Application development Time.

b) Runtime Errors:

=>These errors occurs during Execution or Run time.


=>These errors occurs due to Wrong or Invalid Input entered by Application User (or) End
User.
=>All runtime time are by default generates Technical Error Messages. which are understable
by Programmer and not by End Users. Industry always recommeds to generate User-frinedly
error Messages by using Exception Handling

Building Points to exception Handling

1) When the applicatioin User Enters Invalid Input then we get Runtime Errors
(Invalid Input --- >Runtime Error)
2) Runtime errors always gives Technical Errors Messages
(Invalid Input---->Runtime Error -- >Technical Error Messages)

3) Def. 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 understable
by Programmers and not by End Users. Industry always recommeds to generate User-frinedly
error Messages by using Exception Handling
5) Definition of Exception handling:

=>The Process of Converting Technical error Messages into User-Friendly Error Messages is
called Exception Handling.

6) When the exception occurs in Python Program, Internally 3 steps takes place. They are

195 manojalladi23@[Link]
a) Program execution Abnormally terminated
b) PVM Comes out of Program Flow
c) By default PVM generates Technical Error Message.

7) In order to Perform Step-(a), Step-(b) and 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) Hence Every Exception is treated as an object of appropriate exception class.

Types of Exceptions in Python

=>In Python Programming , we have two types of Exceptions. They are


1. Pre-defined or Built-in Exceptions
2. Programmer or User or Custom defined Exception

1. Pre-defined or Built-in Exceptions:

=>These exception developed by Python Language Developes and available in Python Software
(Library) and used by all python progarmmers for dealing with Universial Problems.
=>Some of the Universial Problems are

1) Division by zero ( ZeroDivisionError )


2) Invalid Number Format conversion( ValueError)
3) Invalid Type of Operation (TypeError)
4) Invalid Indices (IndexError)
5) Imporing of wrong Module Names ( ModuleNotFoundError)
6) Wrong attributes as w.r.t Object names ( AttributeError)
........................etc

2. Programmer or User or Custom defined Exception:

=>These exception developed by Python Language Programmers and avialable in Python


Project and used by all Other python progarmmers 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 bal in Account…….etc
196 manojalladi23@[Link]
Handling the exceptions in Python
=>Handling the exceptions 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 Exceptions
except <exception-class-name-1>:
Block of Statements
Generating User-Friendly Error Messages
except <exception-class-name-2>:
Block of Statements
Generating User-Friendly Error Messages

except <exception-class-name-n>:
Block of Statements
Generating User-Friendly Error Messages
else:
Block of Statements Reccommeded
Generate results
finally:
Block of statements executes compulsorily
irrespective exception occurs or not.

197 manojalladi23@[Link]
Explanation :

1) try block

=>It is the block in which we write block of statements generates exceptions. In otherwords,
what are all the statements generating exceptions those statements must be written within try
block and hence try block is called exception monitoring block.
=>When an exception occurs in try block then PVM comes out of try block and executes
approriate except block
=>Once PVM executes except block, PVM never goes to try block for executing rest of the
statements.
=>Every try block must be immediately followed except otherwise get SyntaxError
=>Every try block must contain atleast one except block and recommeded to write multiple
except block for generating multiple user-friendly error messages.

1) except block:

=>It is the block in which we write block of statements generates User-friendly Error Messages.
In otherwords except block will supress the Technical error Messages and generates User-
Freindly Error Messages and except block is called exception processsing Block.
NOTE:- Handling Exception = try block + except block
=>except block will execute when there is an exception in try block.
=>Even we write multiple except blocks , PVM will execute only one appropriate except block
depends type of exception.
=>The place of writing except block is after try and before else block ( if we write else block)

2) else block:

=>It is the block in which we block of statements recommended to Display Results


=>This block will execute whern there no exception occurs in 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 )
3) finally block:

=>It is the block in which we write Block of Statements which are reqlinquishing (Close or
Release or give-up or clean-up) the resources (Files or Databases)
=>finally block will execute compulosirily
=>Writing finally block is optional
=>The place of finally block is after else block (if we write)

198 manojalladi23@[Link]
# This Program accept two numerical values from KBD and find div.
#[Link]
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)

#This Program accept two numerical values from KBD and find div.
#[Link]
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")

199 manojalladi23@[Link]
Development of Programmer or User or Custom defined Exception
=>These exception developed by Python Language Programmers and avialable in Python
Project and used by all Other python progarmmers 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 bal in Account..etc

=>When an exception occurs, PVM creates an object and to create an object, PVM need an
exception class. if the eexcetion class present in Python Library then that exception class is
called Pre-defined exception class. if the excetion class not present in Python Library then that
exception class must be developed by programmer and it is known as Programmer or User or
Custom defined Exception class.

Steps for developing Programmer Programmer or User or Custom 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
messages...etc)

3. Save the abovedevelopment on the file name with an extension .py ([Link])

=>While we are developing any programmer-defined exception based applications, Programmer


must ensure 3 phases. They are

1) Development of Progremmer-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 Progremmer-defined Exception Class.


Examples:
#[Link]---file name and acts as module name
class KvrDivisionError(Exception):pass

200 manojalladi23@[Link]
2)Development of Common Function and HITTING programmer-defined exception
#[Link] ------ file name and acts as module name
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError #hitting or generating the exception
else:
return (a/b)

2) The program that handle the exception if exception occurs

#[Link]
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 for Den...")
except ValueError:
print("\nDon't enter strs, symbols and alpha-numerics")
else:
print("Div=",res)
finally:
print("I am from finally block")

201 manojalladi23@[Link]
raise key word

=>raise keyword is used for hitting / raising / generating the exception provided some condition
must be satisfied.
=>raise keyword always used inside of Function Definition only.
=>PVM uses raise keyword implicitly for hitting pre-defined Exception where as Programmer
makes the PVM to use use raise keyword explicitly for Hitting or Generating Programmer-
defined Exceptions.

=>Syntax:- if (Test Cond):


raise <exception-class-name>

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

if (Test Cond):
raise <exception-class-name>

202 manojalladi23@[Link]
Examples:

from kvr import KvrDivisionError


def division(a,b):
if(b==0):
raise KvrDivisionError
else:
return (a/b)

#Program for developing Programmer-defined exception class that works like


"ZeroDivisionError".
#[Link]---file name and acts as module name
class KvrDivisionError(Exception):pass

#Phase-1 : Development of Progremmer-defined Exception Class.

#This program develops a common function and HITTING programmer-defined


exception
#[Link] ------ file name and acts as module name
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError #hitting or generating the exception
else:
return (a/b)

#Phase-2: Development of Common Function and HITTING programmer-defined


exception

#This program that handle the exception if exception occurs


#[Link]
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:

203 manojalladi23@[Link]
print("\nDon't enter Zero for Den...")
except ValueError:
print("\nDon't enter strs, symbols and alpha-numerics")
else:
print("Div=",res)
finally:
print("I am from finally block")

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


class NegativeNumberError(Exception):pass

class ZeroError(BaseException):pass

# Development of Programmer-defined exceptions.

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


from MulExcept import NegativeNumberError, ZeroError
def table():
n=int(input("Enter a number:")) # implcitly PVM raise ValueError in case non-numeric
value
if(n<0):
raise NegativeNumberError
elif(n==0):

204 manojalladi23@[Link]
raise ZeroError
else:
print("-"*50)
print("Mul Table for :{}".format(n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
print("-"*50)

#[Link]
from MulTable import table
from MulExcept import NegativeNumberError,ZeroError
try:
table()
except ValueError:
print("\nDon't enter Strs, Symbols and alpha-numeircs")
except NegativeNumberError:
print("\nDon't enter -ve number for mul trable:")
except ZeroError:
print("\nDon't enter zero for Mul Table:")

#[Link]

#development of programmer-defined exceptions


class NegativeNumberError(Exception):pass
class ZeroError(BaseException):pass

#devlopment of function
def table():
n=int(input("Enter a number:")) # implcitly PVM raise ValueError in case non-numeric
value
if(n<0):
raise NegativeNumberError
elif(n==0):
raise ZeroError
else:
print("-"*50)
print("Mul Table for :{}".format(n))
print("-"*50)
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
print("-"*50)

205 manojalladi23@[Link]
#program for handling the exceptions
try:
table()
except ValueError:
print("\nDon't enter Strs, Symbols and alpha-numeircs")
except NegativeNumberError:
print("\nDon't enter -ve number for mul trable:")
except ZeroError:
print("\nDon't enter zero for Mul Table:")

Various Forms of except blocks

=>As part of exception Handling, except block can be in different forms. They are

Form-1 : except block handles Single Exception

try:

except <exception-class-name>:

Form-2 : single except block handles Multiple Specific Exceptions


This Facility is called Multi Exception Handling Block.

try:

except <exception-class-name-1, exception-class-name-2, .... exception-class-name-n>:


block of statements
generates user-friendly error messages
for all specific exceptions.

Form-3 : except block handles Single Exception with alias name


This Facility captures Technical Error Message occured due exception
occurence.

try:

except <exception-class-name> as aliasname:


206 manojalladi23@[Link]
print(aliasname) #Will display Technical Error Message occured due exception occurence

Form-4 : except block handles all types of exceptions


This except block is called default except block and
It must be written at last after specific Exceptions.

try:

except :

#This Program accept two numerical values from KBD and find div.
#[Link]
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")

#This Program accept two numerical values from KBD and find div.
#[Link]
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")

207 manojalladi23@[Link]
#convert s1 and s2 into int type
a=int(s1)
b=int(s2)
c=a/b
except (ZeroDivisionError,ValueError): # multi exception handling block.
print("\nDON'T ENTER ZERO FOR DEN. .. ")
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")

#This Program accept two numerical values from KBD and find div.
#[Link]
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 as z:
print(z)
except ValueError as v:
print(v)
else:
print(" ")
print("Val of a=",a)
print("Val of b=",b)
print("Div=",c)
print(" ")
finally:
print("\nI am from finally block")

#This Program accept two numerical values from KBD and find div.
#[Link]
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
208 manojalladi23@[Link]
s="PYTHON"
print(s[2])
except ZeroDivisionError:
print("\nDON'T ENTER ZERO FOR DEN. .. ")
except ValueError:
print("\nDon't enter strs , symbols and alpha-numerics")
except IndexError:
print("Plz check the index")
except : # default 'except:' must be last
print("Some thing went wrong")
else:
print(" ")
print("Val of a=",a)
print("Val of b=",b)
print("Div=",c)
print(" ")
finally:
print("\nI am from finally block")


#[Link]
def menu():
print("="*50)
print("\tATM Operations")
print("="*50)
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("\[Link]")
print("="*50)

#[Link]
class DepositError(Exception):pass

class WithdrawError(BaseException):pass

class InSuffFundError(Exception):pass

#[Link]
from atmexcept import DepositError,InSuffFundError,WithdrawError
bal=500.00 # global variable
def deposit():
damt=float(input("Enter ur deposit amount:")) # ValueError
if(damt<=0):
raise DepositError
else:
global bal

209 manojalladi23@[Link]
bal=bal+damt
print("Ur Account xxxxxx123 credited with INR:{}".format(damt))
print("Ur Current Bal :{}".format(bal))

def withdraw():
global bal
wamt=float(input("Enter ur withdraw amount:")) # ValueError
if(wamt<=0):
raise WithdrawError
elif((wamt+500)>bal):
raise InSuffFundError
else:
bal=bal-wamt
print("Ur Account xxxxxx123 debitted with INR:{}".format(wamt))
print("Ur Current Bal :{}".format(bal))

def balenq():
print("Ur Current Bal :{}".format(bal))

#[Link]--main program
import sys
from atmmenu import menu
from atmoperations import deposit, withdraw, balenq
from atmexcept import DepositError,InSuffFundError,WithdrawError
while(True):
try:
menu()
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
try:
deposit()
except ValueError:
print("Don't try to deposit strs, symbols and alpha-
numerics")
except DepositError:
print("Don't deposit -ve or zero amount in ur account:")
case 2:
try:
withdraw()
except ValueError:
print("Don't try to withdraw strs, symbols and alpha-
numerics")
except WithdrawError:

210 manojalladi23@[Link]
print("Don't withdraw -ve or zero amount from ur
account:")
except InSuffFundError:
print("Ur Account does not have suff funds--
Read Python Notes:")
case 3:
balenq()
case 4:
print("Thx for using this program")
[Link]()
case _:
print("Ur Selection of operation wrong--try again")
except ValueError:
print("plz enter Integer value for Choice:")

random module

=>random one of pre-defined module present in python


=>The purpose of random is that "To generate random values in various contexts".
=>random module contains the follwoing essential functions.
a) randrange()
b) randint()

c) random()
d) uniform()

e) choice()
f) shuffle()
g) sample()

a) randrange()

=>This function is used for generating random integer values between specified limits.
Syntax1:- [Link](Value)
This syntax generates any random value between 0 to Value-1

Syntax-2: [Link](start,stop)
This syntax generates any random value between start to stop-1

211 manojalladi23@[Link]
Examples:

>>> import random


>>> print([Link](100,150)) --- 133
>>> print([Link](100,150)) --- 121
>>> print([Link](100,150)) --- 139
>>> print([Link](100,150)) --- 143
>>> print([Link](100,150)) -- 106
>>> print([Link](100,150)) -- 133
>>> print([Link](10)) --- 5
>>> print([Link](10)) --- 9

#[Link]
import random
for i in range(1,6):
print([Link](10))
print(" -")
for i in range(1,6):
print([Link](1000,1100))
print(" ")
================================X===================================
b) randint():

=>Syntax:- [Link](start,stop)
=>This syntax generates any random value between start to stop. Here start and stop are
inclusive.
Examples:

>>> print([Link](10,15)) ----- 10


>>> print([Link](10,15)) ---- 13
>>> print([Link](10,15)) --- 14
>>> print([Link](10,15)) --- 11
>>> print([Link](10,15)) --- 15

#[Link]
import random
for i in range(1,6):
print([Link](10,20))
print(" ")
==============================X=====================================

212 manojalladi23@[Link]
c) random()

=>Syntax:- [Link]()
=>This syntax generates floating point random values between 0.0 and 1.0 (Exlusive))
Examples:

>>> import random


>>> print([Link]()) --------- 0.1623906138450063
>>> print([Link]()) ------- 0.15382209709271966
>>> print([Link]()) ------ 0.09542283007844476
>>> print([Link]()) ---- 0.6134301633766425

#[Link]
import random
lst=[]
for i in range(1,6):
[Link]("%0.2f" %[Link]())
print(" ")
print("Content of lst={}".format(lst))
============================X=======================================
d) uniform()

Syntax:- [Link](start,stop)
=>This generates random floting point values from start to stop-1 values
=>The values of start and stop can both Integer or floating point values.
Examples:

>>> import random


>>> print([Link](10,15)) --------- 14.416746067678286
>>> print([Link](10,15)) --- 13.2420406264978
>>> print([Link](10,15)) ---- 11.716110933506432
>>> print([Link](10,15)) ------- 10.703499588966528
>>> print([Link](10,15)) ---- 11.306226559323017
>>> print([Link](10.75,15.75))------- 13.939787347170148
>>> print([Link](10.75,15.75))----10.760428232717597

#[Link]
import random
lst=[]
for i in range(1,6):
[Link](float("%0.2f" %[Link](10,15.5)))

213 manojalladi23@[Link]
print(" ")
print("Content of lst={}".format(lst))
===============================X====================================
e) choice():

Syntax:- [Link](Iterable_object)
=>This function obtains random values from Iterable_object.

Examples:

>>>print([Link]([10,20,30,40,50]),[Link]("PYTHON"),[Link](range(10
,15)))---40 T 11
>>>print([Link]([10,20,30,40,50]),[Link]("PYTHON"),[Link](range(10
,15))) --------- 30 P 12
>>>print([Link]([10,20,30,40,50]),[Link]("PYTHON"),[Link](range(10
,15))) ---------- 40 N 12

#[Link]
import random
s="AaBRe#^%@8YuQLPau*&"
for i in range(1,6):
print([Link](s),[Link](s),[Link](s),[Link](s))
=================================X==================================
f) shuffle():

=>This Function is used for re-organizing the elements of any mutable object but not on
immutable object.

Syntax:- [Link](list)
=>We can shuffle the data of list but not other objects of Data Types
Examples:

>>> d={10:"cadburry",20:"kitkat",30:"malkybar", 40:"dairymilk"}


>>> print(d)---{10: 'cadburry', 20: 'kitkat', 30: 'malkybar', 40: 'dairymilk'}
>>> for k,v in [Link]():
... print(k,"--",v)
...
10 -- cadburry
20 -- kitkat
30 -- malkybar
40 -- dairymilk

214 manojalladi23@[Link]
>>> import random
>>> print([Link](d)) --- Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File
"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\lib\[Link]", line 394, in
shuffle
x[i], x[j] = x[j], x[i]
KeyError: 3
>>> s={10,20,30,40,50}
>>> print([Link](s))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File
"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\lib\[Link]", line 394, in
shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'set' object is not subscriptable

>>> t=(10,20,30,40,50)
>>> print([Link](t))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File
"C:\Users\nareshit\AppData\Local\Programs\Python\Python310\lib\[Link]", line 394, in
shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item
assignment
>>> l=[10,20,30,40,50]
>>> print([Link](l)) ---- None
>>> print(l) ------------ [30, 40, 50, 10, 20]
>>> [Link](l)
>>> print(l) ----------- [40, 30, 10, 20, 50]
>>> [Link](l)
>>> print(l) -------- [40, 10, 50, 20, 30]
>>> [Link](l)
>>> print(l) ----------- [30, 50, 20, 40, 10]

#[Link]
import random as r

215 manojalladi23@[Link]
l=[10,"Python","Rossum",34.56,True]
for i in range(1,6):
[Link](l)
print("content of l=",l)
===================================X================================

g) sample()

=>This Function is used for selecting random samples from any Iterable object based on number
of samples(+ve)
Syntax:- [Link](iterable_object, k)
=>Here 'k' can be number of samples.

Examples:

>>> import random


>>> s="ABCabcERTYUertyu$%^&*#@!%^&ghjkiyl"
>>> print([Link](s,5)) --------- ['A', '*', '^', 'j', 't']
>>> print([Link](s,5)) -------- ['%', 'l', 'b', 'C', 'y']
>>> print([Link](s,5)) --------- ['%', 'e', 'Y', 'j', 'u']
>>> print([Link](s,5)) ----- ['y', 'E', '&', '$', '#']
>>> print([Link](s,5)) --------- ['j', '*', 't', '$', 'u']

#[Link]
import random
lst=[10,"Rossum","Python",34.56,True]
for i in range(1,6):
print([Link](lst,2))
================================X===================================
#This program generates captcha Code
#[Link]
import random as r
cap="ABCDabcdLOPZWER%^&*(123456)(*&LQWER"
for i in range(1,11):
print([Link](cap),[Link](cap),[Link](cap),[Link](cap),[Link](cap))

#[Link]
import random as r
passport="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nums="0123456789"
spcialsymbols="!@#$%^&*() +"

216 manojalladi23@[Link]
for i in range(1,6):
print("Passport
Code:{}{}{}{}{}".format([Link](passport),[Link](passport),[Link](nums),[Link](spcialsy
mbols), [Link](range(10000,100000))))

#This program generates random numbers 0.0 to 1.0


#[Link]
import random as r
for i in range(1,11):
print(round([Link](),2))

#This program generates random numbers 0.0 to 1.0


#[Link]
import random as r
for i in range(1,11):
print("%0.3f" %[Link]())

#This program generates random numbers from BEGIN to END inclusive


#[Link]
import random as r
for i in range(1,11):
print([Link](10,21,3))

#[Link]
import random as r
for i in range(10,21):
print("SBI"+str([Link](1000,1500)))

#This program generates random numbers from BEGIN to END inclusive


#[Link]
import random as r
for i in range(1,11):
print([Link](10,21))

#This program generates random numbers from BEGIN to END inclusive


#[Link]
import random as r
for i in range(1,11):
print([Link](10,21,3))

217 manojalladi23@[Link]
#This program generates random numbers from 0 to n-1
#[Link]
import random as r
for i in range(1,11):
print([Link](10))

#This program generates random numbers from BEGIN to END-1


#[Link]
import random as r
for i in range(1,11):
print([Link](10,21))

#[Link]
import random as r
alp="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
print("TS08",[Link](alp),[Link](alp),[Link](range(1000,10000)))

#[Link]
import random as r
lst=[10,20,30,40,50,60,"KVR"]
for i in range(1,6):
[Link](lst)
print(lst)
print(" ")

#[Link]
for i in range(10,21):
print("SBI"+str(i))

#This program generates random float point numbers between Begin and End
#[Link]
import random as r
for i in range(1,6):
print("%0.3f" %[Link](100,120))

#This program generates random float point numbers between Begin and End
#[Link]
import random as r
for i in range(1,6):
print([Link](100,120))

218 manojalladi23@[Link]
Files in Python

Index

=>Purpose of Files
=>Types of Applications in the context of files
=>Definition of File
=>Definition of Stream
=>Types of Operations on Files
a) Write Operation
b) Read Operation
=>Types of Files
a) Text Files
b) Binary Files
=>File Opening Modes
1) r
2) w
3) a
4) r+
5) w+
6) a+
7) x
=>Syntax for Opening Files
a) 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

219 manojalladi23@[Link]
=>CSV in Pandas
=>JSON FILES in Python
================================x==============================

Types of Application in Files

=>The purpose of Files in any programming language is that " To maintain Data Persistency".
=>The Process of storing the data permanently is called Data Persistency.
=>In this context, we can develop two types of applications. They are
1) Non-Persistant Applications
2) Persistant Applications
=>In Non-Persistant Applications development, we read the data from Keyboard , stored in main
memory(RAM) in the form objects, processed and whose results displayed on Moniter.
Examples: ALL our previous examples comes under Non-Persistant Applications.

=>We know that Data stored in Main Memory is temporary.


=>In Persistant Applications development, we read the data from Keyboard , stored in main
memory(RAM) in the form objects, processed and whose results stored Permanently.
=>In Industry, we have two ways two 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 Persistenecy by Files of Python

Def. of File:

=>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 file of secondary memory becomes the objects in main memory.

Def. of Stream:

=>The Flow of Data between object(s) of Main Memory and Files of Seconday memory is called
Stream.

220 manojalladi23@[Link]
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
file 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 the data from file of secondary into object of
main memory."
=>Steps:
1) Choose the file name.
2) Open the file name in read mode.
3) Perform cycle of read operations.
=>While we are performing Read Operations, we get some exceptions. They are
a) FileNotFoundError
b) EOFError

221 manojalladi23@[Link]
Types of Files in Python

=>In Python Programming, we have two types of Files. They are

1. Text File
2. Binary Files

1) Text File:

=>A text file is one which contains Alphabets, Digits and Special Symbols.
=>In Python Programming, a text file is denoted by a letter 't' .
=>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 video files
PDF formats

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

=>This mode is used 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

=>This mode is used 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

222 manojalladi23@[Link]
written form begining 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

=>This mode is used 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 form begining of the file always.
=>When we open EXISTING FILE in "a" Mode then existing data of the existing file
APPENDED with new Data.

4. r+

=>This mode is also used for Opening the file Read Mode and Perform Read Operation.
=>After reading the data from file and later we can also Perform Write Operation.
=>When we open the file in "r+" mode and if the file does not exist then we get
FileNotFoundError.

5. w+

=>This mode is used for Opening the file in write mode and Performs Write Operation always
and later Additonally we can perform Read Operations also.
=>When we open NEW FILE in "w+" Mode the new file will be opened in write mode and data
written form begining of the file always and later 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 later we can read the data also.

6. a+

=>This mode is used creating the file and opening the file in write mode always and performs
write operation First and later 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 form the begining 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
=>This mode is used for creating the new file and opening that file in Write Mode eXclusively.
=>If we open open exitsing file in "x" mode then PVM generates FileExistError.

223 manojalladi23@[Link]
224 manojalladi23@[Link]
Opening the Files in Python

=>In Python Programming, we have two approaches to open the file. They are
1) By using open()
2) By using " with open() as "

1) By using open():

Syntax:- varname=open("File Name","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 modes (r, w,a, r+,w+,a+,x)
=>open() is pre-defined 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 close the file by using
close(). In otherwords open() does not provide "auto-closability Files"

2) By using "with open() as" :

Syntax:- with open("File Name","File Mode") as Varname:

Block of statements performs File Operations

225 manojalladi23@[Link]
------Block of statements-out of with Indentation-----

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 modes (r, w,a, r+,w+,a+,x)
=>open() is pre-defined function, which is used for opening the file in specified file mode.
=>hence the advantnage of "with open() as" approach is that " Auto-closability of File. In
otherwords, as long as PVM executes indentation Block of statements of "with open() as "
approach, file is active (or) under open and once PVM comes out of "with open() as " then PVM
closes the file automatically "

#Program for opening a file by using open()


#[Link]
try:
fp=open("[Link]")
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=", [Link])
print("File Mode=",[Link])
print("Is file readable=", [Link]())
print("Is file writable=", [Link]())
print("Is file closed=",[Link]) # False
print("="*50)
finally:
print("\ni am from finally block")
[Link]() # we are closing the file manually
print("Is file closed=",[Link]) # True

226 manojalladi23@[Link]
#Program for opening a file by using open()
#[Link]
try:
fp=open("[Link]","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=", [Link])
print("File Mode=",[Link])
print("Is file readable=", [Link]())
print("Is file writable=", [Link]())
print("Is file closed=",[Link]) # False
print("="*50)
finally:
print("\ni am from finally block")
[Link]() # we are closing the file manually
print("Is file closed=",[Link]) # True

#Program for opening a file by using open()


#[Link]
try:
fp=open("[Link]","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=", [Link])
print("File Mode=",[Link])
print("Is file readable=", [Link]())
print("Is file writable=", [Link]())
print("Is file closed=",[Link]) # False
print("="*50)

227 manojalladi23@[Link]
finally:
print("\ni am from finally block")
[Link]() # we are closing the file manually
print("Is file closed=",[Link]) # True

#Program for opening a file by using open()


#[Link]
try:
fp=open("[Link]","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=", [Link])
print("File Mode=",[Link])
print("Is file readable=", [Link]())
print("Is file writable=", [Link]())
print("Is file closed=",[Link]) # False
print("="*50)
finally:
print("\ni am from finally block")
[Link]() # we are closing the file manually
print("Is file closed=",[Link]) # True

#Program for opening a file by using "with open() as"


#[Link]
with open("[Link]","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=", [Link])
print("File Mode=",[Link])
print("Is file readable=", [Link]())
print("Is file writable=", [Link]())
print("Liner-12-->Is file closed=",[Link]) # False

228 manojalladi23@[Link]
print("="*50)
print("\nI am from out of 'with open() as indentation block ")
print("Line-15-->Is file closed=",[Link]) # True

#Program for opening a file by using "with open() as"


#[Link]
try:
with open("[Link]") 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=", [Link])
print("File Mode=",[Link])
print("Is file readable=", [Link]())
print("Is file writable=", [Link]())
print("Liner-12-->Is file closed=",[Link]) # False
print("="*50)
except FileNotFoundError:
print("File does not exist")
finally:
print("\ni am from finally block")
print("Is file closed=",[Link]) # True

Writing the data to the file

=>To write the data to the file, we have 2 pre-defined functions in file pointer object. They are

1. write()
2. writelines()

1) write():

=>Syntax: [Link](str data)


=>This function is used for writing any type of data to file in the form of str.
=>If we have non-str data then convert into str type and then write it to the file.

2) writelines():

=>Syntax: [Link](Iterable object)

229 manojalladi23@[Link]
=>This function is used for writing any type of Iterable object data to file in the form of str.
=>If we have non-str data then convert into str type and then write it to the file.
================================x====================================

#write a python program which will write different pepole address to the file
#[Link]
with open("[Link]","a") as fp:
[Link]("Travis Oliphant\n")
[Link]("A-B-3, Park End Side\n")
[Link]("Numpy Software Foundation\n")
[Link]("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 4 pre-defined functions present in File Pointer object.
They are
1. read()
2. read([Link] chars)
3. readline()
4. readlines()

1. read():

=>This function is used for reading entire content of the file in the form of str.
=>Syntax:- varname=[Link]()
=>here varname is an object of type <class, str>
Example: [Link]

2) read([Link] chars)

=>This function is used for reading specified number of chars from the given file.
=>In the file, The data always organized in the form Indices
=>Syntax:- varname=[Link](no. of chars)
=>here varname is an object of type <class, str>
Examples:- [Link]

230 manojalladi23@[Link]
3) readline()

=>This function is used for reading One Line at a time from the file in the form of str.
=>Syntax: varname=[Link]()
=>here varname is an object of type <class, str>
Examples:- [Link]

4) readlines()

=>This function is used for reading all Lines at a time from the file in the form of list .
=>Syntax: listobj=[Link]()
=>here listobj is an object of type <class, list>
Examples:- [Link]

#write a python program which will read entire data from the file --- read()
#[Link]
fname=input("Enter File Name:")
try:
with open(fname) as fp:
filedata=[Link]()
print("-"*40)
print(filedata)
print("-"*40)
except FileNotFoundError:
print("file does not exists")

#write a python program which will read entire data from the file --- read(no. of chars)
#[Link]
try:
with open("[Link]","r") as fp:
print("\nInital Position of fp:",[Link]()) # 0
filedata=[Link](6)
print("File Data=",filedata)
print("\nNow Position of fp:",[Link]()) # 6
filedata=[Link](7)
print("File Data=",filedata)
print("\nNow Position of fp:",[Link]()) # 13
filedata=[Link](17)
print("File Data=",filedata)
print("\nNow Position of fp:",[Link]()) #31
filedata=[Link]()

231 manojalladi23@[Link]
print("File Data=",filedata)
print("\nNow Position of fp:",[Link]()) # 13
print(" ")
[Link](0)
print("\nNow Position of fp after seek() :",[Link]()) # 0
filedata=[Link]()
print("File Data=",filedata)
except FileNotFoundError:
print("file does not exists")

#write a python program which will read entire data from the file --- readline()
#[Link]
try:
with open("[Link]","r") as fp:
filedata=[Link]()
print(filedata)
filedata=[Link]()
print(filedata)
filedata=[Link]()
print(filedata)
filedata=[Link]()
print(filedata)
filedata=[Link]()
print(filedata)

except FileNotFoundError:
print("file does not exists")

#write a python program which will read entire data from the file --- readlines()
#[Link]
try:
with open("[Link]","r") as fp:
filedata=[Link]()
for line in filedata:
print(line,end="")
print()

except FileNotFoundError:
print("file does not exists")

232 manojalladi23@[Link]
#Program for copying the content of One File into another File.
#[Link]
sfile=input("Enter Source File:")
try:
with open(sfile,"r") as rp:
dfile=input("Enter Destination File:")
with open(dfile,"a") as wp:
#read file data from source file
sfiledata=[Link]()
#write source file data to destination file
[Link](sfiledata)
print("\nFile Copy Process Sucessful:")
except FileNotFoundError:
print("Source File does not exists")

#write a python programm which will count no of lines , no of words, no characters from
any file
#[Link]
fname=input("Enter File Name:")
try:
fp=open(fname)
except FileNotFoundError:
print("File Does not exists")
else:
nl,nw,nc=0,0,0
filelines=[Link]()
for line in filelines:
nl=nl+1
nw=nw+len([Link]() )
nc=nc+len(line)
print(line,end="")
else:
print("-"*50)
print("Number of Lines=",nl)
print("Number of Words=",nw)
print("Number of Chars=",nc)
print("-"*50)

233 manojalladi23@[Link]
#Program for copying the content of One image into another image
#[Link]
try:
with open("D:\\KVR\\[Link]" , "rb") as rp:
with open("[Link]","wb") as wp:
filedata=[Link]()
[Link](filedata)
print("Imgage copied and Verify")
except FileNotFoundError:
print("File does not exist")

Pickling and Un-Pickling


(OR)
Object Serialization or Object De-Serialization

Pickling ( Object Serialization)

=>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()
and writelines() , they transfers the values 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 saving or transfering entire object content of main memory into the file of
secondary memory by performing single write operation is called Pickling.
=>Pickling concept participates in Write Operations.

Steps for implementing Pickling Concept:

=>import pickle 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: [Link](object , filepointer)
=>NOTE That pickling concept always takes the file in Binary Format.

234 manojalladi23@[Link]
Un-Pickling (Object De-Serialization)

=>Let us assume there exists a record with multiple values in a file of secondary memory. To
read or trasfer the entire record content from file of secondary memory, if we use read(),
read([Link] chars), readline() and readlines() then they read record values in the form of value by
value and it is one of the time consuming process( multiple read operations).
=>To overcome this time consuming process, we must use the concept of Un-pickling.
=>The advantange 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 trasefering the enrite 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 Operations.

Steps for implementing Un-Pickling Concept:

=>import pickle module


=>Choose the file name and open it into read mode.
=>Use the load() of pickle module. load() is used for transfering or loading the
entire record content from file of secondary memory into object of main memory.
Syntax: objname=[Link](filepointer)
=>NOTE That Un-pickling concept always takes the file in Binary Format.

#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)
#[Link]
import pickle
with open("[Link]","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:"))

235 manojalladi23@[Link]
#create an empty list
lst=list()
#append the employee values to list object
[Link](eno)
[Link](ename)
[Link](sal)
#save or dump list object data to the file
[Link](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)
#[Link]
import pickle
try:
with open("[Link]","rb") as fp:
print("-"*50)
print("Empno\tName\tSalary")
print("-"*50)
while(True):
try:
record=[Link](fp)
for val in record:
print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break

except FileNotFoundError:
print("File does not exist")

#Write a python program which will accept student details such as stdno stdname and
marks and store the record in a file
#[Link]
import pickle,sys
with open("[Link]","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()

236 manojalladi23@[Link]
[Link](sno)
[Link](sname)
[Link](marks)
[Link](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([Link]()=="no"):
print("Thx for using this program")
[Link]()
if([Link]()=="yes") and ([Link]() ):
break
if([Link]()!="yes" or [Link]() or
[Link]()) :
print("Plz learn typing")

except ValueError:
print("Don't enter strs, symbols and alpha-numerics for stno and marks")

#write a python program which wiil read student records from the file --- Program-B)
#[Link]
import pickle
try:
with open("[Link]","rb") as fp:
print("-"*50)
print("Stno\tName\tMarks")
print("-"*50)
while(True):
try:
record=[Link](fp)
for val in record:
print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File does not exist")

237 manojalladi23@[Link]
OS Module

=>os is one of the pre-defined module


=>the purpose of os module is that to perform some OS based Operations.
=>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) Renaming a Folder ( rename() )

1) Getting current working folder :

=>To get the current working folder , we use getcwd() of os module


=>Syntax:- varname=[Link]()

Examples:

#program for getting current working folder ---getcwd()


#[Link]
import os
cwdname=[Link]()
print("current working folder=",cwdname)

2) Creating a Folder

=>To Creating a Folder , we use mkdir() of os module.


=>Syntax:- [Link]("Folder Name")
=>If the Folder Name already exist and if we attempt to create again then we get FileExistError
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)

238 manojalladi23@[Link]
Examples:

#Program for creating a folder


#[Link]
import os
try:
[Link]("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 Folders Hierarchy

=>To Creating Folders Hierarchy, we use makedirs()


=>Syntax:- [Link]("Folders Hierarchy")
=>Here Folder Hierarchy represents Root Folder, sub Folder , sub-sub folders etc.
=>If the Folders Hierarchy already exist and if we attempt to create again then we get
FileExistError as an exception.

Examples:

#Program for Creating Folders Hierarchy


#[Link]
import os
try:
[Link]("C:\INDIA\BANG\AMPT\INDIA")
print("Folders Hirerarchy created..")
except FileExistsError:
print("Folders Hirerarchy already exist--try with some other")

4) Remove a Folder:

=>To remove a folder, we use rmdir().


=>Syntax: [Link]("Folder Name")
=>If folder name does not exists then we get FileNotFoundError.
=>rmdir() can remove only one folder at a time but not able to remove Folder Hierarchy at time.
=>rmdir() generates an exception called OSError when the folder contains some sub folder or
file names.

239 manojalladi23@[Link]
Examples:

#program for removing a folder


#[Link]
import os
try:
[Link]("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 :

=>To remove Folders Hierarchy , we use removedirs()


=>Syntax: [Link]("Folder Hierarchy")
=>Here Folder Hierarchy represents Root Folder, sub Folder , sub-sub folders etc.
=>If Folder Hierarchy does not exists then we get FileNotFoundError.
=>removemdirs() generates an exception called OSError when the folders Hierarchy contains
some sub folder or file names.

Examples:

#program for removing a folders hierarchy


#[Link]
import os
try:
[Link]("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

=>To list the files in a folder, wer use listdir()


=>Syntax: listobj=[Link]("Folder Name")
=>=>If folder name does not exists then we get FileNotFoundError.

240 manojalladi23@[Link]
Examples:

#Program for listing the files in a folder


#[Link]
import os
try:
files=[Link]("E:\KVR-PYTHON-6PM\FILES")
print("Number of files =",len(files))
for file in files:
print(file)
except FileNotFoundError:
print("File does not exists")

7) Rename a Folder

=>To Rename a Folder , we use rename()


=>Syntax: [Link]("Old Folder Name","New Folder Name")
=>If old folder does not exist then we get FileNotFoundError.

Examples;

#Program for renaming a folder


#[Link]
import os
try:
[Link]("E:\KVR-PYTHON-6PM\FILESPROG","E:\KVR-PYTHON-6PM\FILES")
print("Folder renamed")
except FileNotFoundError:
print("Folder does not exists")

#program for getting current working folder ---getcwd()


#[Link]
import os
cwdname=[Link]()
print(type(cwdname))
print("current working folder=",cwdname)

241 manojalladi23@[Link]
#Program for creating a folder
#[Link]
import os
try:
[Link]("C:\HYD\AMPT")
print("Folder created successfully-verify")
except FileExistsError:
print("Folder already exist--try with another one")
except FileNotFoundError:
print("with mkdir(), we can create Folders Hierarchy")

#Program for Creating Folders Hierarchy


#[Link]
import os
try:
[Link]("C:\INDIA\BANG\AMPT\INDIA")
print("Folders Hirerarchy created..")
except FileExistsError:
print("Folders Hirerarchy already exist--try with some other")

#program for removing a folders hierarchy


#[Link]
import os
try:
[Link]("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")

#Program for renaming a folder


#[Link]
import os
try:
[Link]("E:\KVR-PYTHON-6PM\FILESPROG","E:\KVR-PYTHON-6PM\FILES")
print("Folder renamed")
except FileNotFoundError:
print("Folder does not exists")

242 manojalladi23@[Link]
#Program for listing the files in a folder
#[Link]
import os
try:
files=[Link]("E:\KVR-PYTHON-6PM\FILES")
print("Number of files =",len(files))
for file in files:
print(file)
except FileNotFoundError:
print("File does not exists")

#Program for renaming a folder


#[Link]
import os
try:
[Link]("E:\KVR-PYTHON-6PM\FILESPROG","E:\KVR-PYTHON-6PM\FILES")
print("Folder renamed")
except FileNotFoundError:
print("Folder does not exists")

#program for removing a folder


#[Link]
import os
try:
[Link]("C:\PYTHON")
print("Folder Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folder is not empty-can't remove")

243 manojalladi23@[Link]
Working with CSV Files in Python

=>CSV stannds for Comma Separated Values.


=>A CSV File is one of the is a simple file format used to store tabular data, such as a
spreadsheet or database.
=>A CSV file stores tabular data (numbers and text) in plain text.
=>Each line of the CSV file is a data record. Each record consists of one or more fields,
separated by commas.
=>Python provides an in-built module called csv to work with CSV files.
=>There are 2 classes provided by this module for writing the data to CSV File. They are
1) By using Using [Link] class object
2) By Using [Link] class object

1) By using Using [Link] class object

=>The [Link] class object is used to insert data to the CSV file.
=>To create an object of "[Link]" class object, we use writer() and present in csv module.
=>"[Link]" class object provides two Functions for writing to CSV file.
=>They are
1) writerow()
2) writerows()

1) writerow(): This method writes a single row at a time.


Field row can be written using this method.
Syntax:- [Link](fields Row / Data Row)
2) writerows(): This method is used to write multiple rows at a time.
This can be used to write rows list.
Syntax: Writing CSV files in Python
[Link](data rows)
here data rows can be list tuple set,frozenset only

2) By Using [Link] class object

=>The "[Link]" class object is used to insert dict data to the CSV file.
=>To create an object of "[Link]" class object, we use DictWriter() and present in csv
module.
=>"[Link]" class object provides two Functions for writing to CSV.
1) writeheader()
2) writerows()

244 manojalladi23@[Link]
1) writeheader():

=>writeheader() method simply writes the first row of your csv file using the pre-specified
fieldnames.
Syntax: [Link]()

2) writerows():

=>writerows() method simply writes all the values of (Key,Value) from dict object in the form of
separate rows[ Note: it writes only the values(not keys) ]
Syntax:- [Link](dictobject)

Reading the data from CSV File

=>There are various ways to read a CSV file that uses either the CSV module or the pandas
library.
=>The csv Module provides classes for reading information from CSV file .
1) [Link]
2) [Link]

1) [Link]():

=>This Function is used for creating an object of "[Link]" class and It helps us to read the
data records from csv file.
=>Syntax:- csvreaderobj=[Link](filepointer)

2) [Link]():

=>This Function is used for creating an object of "[Link]" class and It helps us to read
the data from csv file where it contains dict data(Key,Value).
=>Syntax:- csvdictreaderobj=[Link](filepointer)

# Python program to demonstrate writing to CSV [Link]--->writer()


#[Link]
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'],

245 manojalladi23@[Link]
['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 = "[Link]"
# writing data to csv file
with open(csvfilename, 'w') as fp:
# creating a csv writer object
csvwriter = [Link](fp)
# writing the fields
[Link](recfields)
# writing the data rows
[Link](rows)
print("\nCSV file Created and Verify")

# Python program to demonstrate to write single record


# writing single record to CSV file
#[Link]
import csv

# data record of csv file


row = ['KVR', 'CSE', '2', '9.0']

# name of csv file


filename = "[Link]"
# writing to csv file
with open(filename, 'a') as fp:
# creating a csv writer object
cw = [Link](fp)
# writing the data row to the csv file
[Link](row)
print("\nSingle Record Written to the CSV File:")

246 manojalladi23@[Link]
sno sname marks cname
sno RS 33.33 PSF
sno DR 22.22 BU
sno TR 11.11 NU
sno DT 44.44 OU
sno SR 33.22 JNTU
sno TE 66.44 HCU
sno UT 22.55 AU
sno

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

247 manojalladi23@[Link]
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 by using csv module --- [Link]
#[Link]
import csv
try:
with open("[Link]","r") as fp:
cr=[Link](fp)
for record in cr:
for val in record:
print("{}".format(val),end="\t")
print()
except FileNotFoundError:
print("File does not exist")

#Program for reading the data from CSV file by using csv module --- [Link]
#[Link]
import csv
try:
with open("[Link]","r") as fp:
cr=[Link](fp)
for record in cr:
for val in record:
print("{}".format(val),end="\t")
print()
except FileNotFoundError:

248 manojalladi23@[Link]
print("File does not exist")

#Program for reading the data from CSV file by using csv module --- [Link]
#[Link]
import csv
try:
with open("[Link]","r") as fp:
dcr=[Link](fp)
print("-"*40)
for record in dcr:
for k,v in [Link]():
print("\t{}-->{}".format(k,v))
print("-"*40)

except FileNotFoundError:
print("File does not exist")

#Program for reading the data from CSV file without using csv module ----[Link]
#[Link]
try:
with open("[Link]","r") as fp:
csvfiledata=[Link]()
print(csvfiledata)
except FileNotFoundError:
print("File does not exist")

# importing the csv module


#[Link]
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']

249 manojalladi23@[Link]
# name of csv file
filename = "[Link]"

# writing to csv file


with open(filename, 'w') as fp:
# creating a csv dict writer object
dictwriter = [Link](fp, fieldnames = csvfields)
# writing headers (field names)
[Link]()
# writing data rows
[Link](mydict)
print("\nDict Data Written to the csv file--verify")

Python DataBase Communication ( PDBC )

=>Even we acheived the Data Persistency by using Files, Files has the following Limitations.

1. Files of any language does not contain security bcoz 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 differing from One OS to another OS (Files are OS depenedent)
4. Querying and Processing the data from Files is Very Complex bcoz file data is
organized w.r.t Indices and idenfying the indices is very complex.
5. Files does not contain Column Names (Except CSV Files)

=>To Overcome the limitation of files and to acheive the Data Persistency, we must use the
concept of any RDBMS DataBase Softwares ( Oracle, MYSQL, Mongo DB, DB2, SQL Server,
Postgey SQL, SQLITE3. ......... etc).

1. All RDBMS DataBase Softwares Provides Security bcoz RDBMS DataBase


Softwares considers User names and Password.
2. All RDBMS DataBase Softwares stores large amount of data
3. All RDBMS DataBase Softwares Arch Remains Same on types of OSes ( OS
Independent)
4. Querying and Processing the data from All RDBMS DataBase Softwares is
Very Simple bcoz data of All RDBMS DataBase Softwares oranganized in the of
Tables with Column Names.
5. The Data Present in any RDBMS DataBase Softwares oranganized in the of
Tables

250 manojalladi23@[Link]
with Column Names.

=>If Python Program want to communicate with any RDBMS DataBase Softwares then we must
use a PRE-DEFINED MODULE and such PRE-DEFINED MODULE does not exist in Python
Software.
=>Some Third Party Software Vendors( Ex: "Anthony Tuininga") developed a Module for
Python Programmers to copmmunicate with RDBMS DataBase Softwares and placed in github
and Third Party Software Modules must be installed.
=>To install any Third Party Software Modules in python , we use a tool called pip and it is
present in C:\Users\KVR\AppData\Local\Programs\Python\Python310\Scripts folder.

=>Syntax : pip install Module Name (at any Windows command prompt)

=>If Python Program want to communicate with Oracle Database, then we must install
cx_Oracle Module.
=>Examples : pip install cx_Oracle

=>If Python Program want to communicate with MySQL Database, then we must install
mysql-connector or mysql-connector-python Module.

=>Examples : pip install mysql-connector


=>Examples : pip install mysql-connector-python
====================================x================================

Communication between Python Program and Oracle Database

=>In order to write python program to communicate with Oracle Database, we must follow 6
steps. They are

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 Process the Result of the Query.
6. Python Program closes the connection.

251 manojalladi23@[Link]
Explanation:
1. import cx_Oracle module:

=>If a python Program want to perform any database operations(insert , delete , update record ,
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 and Class Names.

Examples: import cx_Oracle

2. Python Program must get the connection from Oracle DB

=>To do any Data Base Operations, First python program must get the connection from Oracle.
=>To get the connection from any Database, we use connect() which is present in cx_Oracle
module.
=>Syntax:- varame=cx_Oracle.connect("Connection URL")

=>Here connection URL Represents " UserName/Password@DNS/Serviceid "


(OR)
"
UserName/Password@IPAddress/Serviceid "

=>Here Varname is an object of <class, cx_Oracle.Connection>


=>Here "UserName" represents User Name of Oracle Data Base (Ex: scott )
=>here "password" represents Password of Oracle Data Base (Ex: tiger )
=>here DNS(Domain Naming Service) represents name of the machine where Database
Software Installed. The default Name of Every Machine is "localhost".
=>Here IPAddress (Internet Protocal Address) represents An address of Physical Machine where
Database software Installed. The default IP Address of Every Machine is [Link] (Loop back
address)
=>Here "serviceid" represents on which name Oracle data base Installed in current working
machine. To find Service Id in Oracle Data base, we use the following 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.

252 manojalladi23@[Link]
3. Create an object of Cursor
=>The purpose of creating an object of Cursor is that "To carry the Query from Python Program,
hand over to Database, and obtains Result from Database and Gives to Python Program".
=>To create an object of Cursor, we use cursor() which is present in Connection Object.
=>Syntax: varname=[Link]()
=>Here Varname reprsents an object of <class, cx_Oracle.Cursor>

3. Python program must Prepare the Query and Execute the Query in Oracle DB

=>A Query is a statement or Request or Question to database software for obtaining data base
results.
=>To execute the query in any Database software, we use execute() which is present in cursor
object.
=>Syntax: [Link]("Query")
=>Here Query is of type str and In any database software we have different Queries
(DDL,DML,DRL )

4. Python Program Process the Result of the Query.

=>After Executing DML statements, the result of DML statements is present in n cursor object.
To extract the result from cursor object, we use "rowcount" attribute of cursor object.
"rowcount" attribute gives number of updated / deleted / inserted in the the data base.

=>After Executing DRL statements, the result of DRL statements is present in cursor object. To
extract the from cursor object, have 3 Functions in cursor object. They are
a) fetchone()
b) fetchmany(no. of records)
c) fetchall()
=>fetchone() is used for obtaining One Record at a Time in the form of tuple. if no records found
then we this function returns None.
=>fetchmany(no. of records) is used for obtaining specified number of records.
case-1: if specified number of records==0 then this function obtains all records
case-2: if specified number of records<=Total Number of Records then this function
gives specified number of records
case-3: if specified number of records>Total Number of Records then this function
obtains all records
case-4: if specified number of records<0 then this function never gives any records.

=>fetchall() is used for obtaining all the records from cursor object.

253 manojalladi23@[Link]
Types of Queries in Database Softwares
=>In any database, we have 3 types of Queries. They are

1. DDL( Data Definition Language) Queries


2. DML (Data Manipulation Language) Queries
3. DRL (Data Retrieval 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 Columns etc.
=>in any Database software , we have 3 types of DDL Queries. They are

1. create
2. alter
3. drop
1) create:

=>This Query is used for creating a table in Oracle Database


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

2. 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 data
type....
existing col name-n database data type )

Syntax2:- SQL> alter table <table-name> add ( new col name1 database data type....
new col name-n database data type )

Examples: SQL> alter table employee add(cname varchar2(10));


SQL> alter table employee modify(ename varchar2(20), sal number(8,2));
254 manojalladi23@[Link]
3) drop :

=>This query is used for removing the table from Database Software
=>Syntax:- SQL> drop table <table-name>
=>Example:- SQL> drop table employee

#Program for getting the connection from Oracle DB


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

#Program for getting the connection from Oracle DB


#[Link]
import cx_Oracle # Step-1
try:
kvrcon=cx_Oracle.connect("scott/tiger@[Link]/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)

#Program for creating an object cursor


#[Link]
import cx_Oracle
con=cx_Oracle.connect("scott/tiger@[Link]/orcl")
print("\nPython got connection from Oracle DB")
cur=[Link]()
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


#[Link]

255 manojalladi23@[Link]
import cx_Oracle # 1
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # 2
cur=[Link]() # 3
#Step-4
tq="create table employee(eno number(2) primary key, ename varchar2(10), sal
number(8,2))"
[Link](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
#[Link]
import cx_Oracle # 1
def tabledrop():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # 2
cur=[Link]() # 3
#step-4
[Link]("drop table student")
print("Student Table droped / removed from Oracle DB sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)

#[Link]
from TableDropEx import tabledrop as td
td()

#Program for altering the by the means of adding new columns to Employee Table
#[Link]
import cx_Oracle # 1
def aftercolumnAdd():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # 2
cur=[Link]() # 3
#step-4
aqa="alter table employee add(cname varchar2(10))"
[Link](aqa)
print("Employee altered sucessfully")
except cx_Oracle.DatabaseError as db:

256 manojalladi23@[Link]
print("Prob in Database:",db)

#main program
aftercolumnAdd()

#Program for altering the column sizes of Employee Table


#[Link]
import cx_Oracle # 1
def aftercolumnsizes():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl") # 2
cur=[Link]() # 3
#step-4
aqm="alter table employee modify(eno number(3),sal number(9,2))"
[Link](aqm)
print("Employee altered sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)

#main program
aftercolumnsizes()

2. DML (Data Manipulation Language) Queries

=>The purpose of DML operations is that To manipulate the table such Inserting the records,
deleting the records and updating the records.
=>In RDBMS database softwares, we have 3 types of DML Operations. They are

1. insert
2. delete
3. update
=>When we execute any DML Operation through python program, we must use commit() for
permanent change / update / modification and to roll back we use roolback().
=>commit() and rollback() are present in connection object.

257 manojalladi23@[Link]
[Link]:
=>This query is used for inserting a record in table of database.
=>Syntax:- SQL> insert into <table-name> values( val1 for column1, val2 for column2.....
val-n for column-n)
Example: SQL> insert into student values (20,'DR',33.45,'C');
SQL>insert into student values (10,'RS',23.45,'Python');
SQL> commit ;

1. delete

=>This query is used for deleting a record .


=>Syntax1: delete from <table name>

=>Syntax2: delete from <table-name> where cond list;

=>Example: SQL> delete from student where sno=70;

2. update

=>This 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=marks+marks*0.05,crs='Django' where sno=90;

#write a python program which will insert a record in employee table


#[Link]
import cx_Oracle
def emprecordinsert():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]()
#prepare Query and execute
iq="insert into employee values (70,'SV',4.5,'HCL') "
[Link](iq)
258 manojalladi23@[Link]
[Link]()
print("{} Employee Record Inserted Successfully".format ( [Link]) )

except cx_Oracle.DatabaseError as db:


print("Problem in Database:",db)

#main program
emprecordinsert()

#write a python program which will insert a record in employee table by accepting
employee values from Keyboard
#[Link]
import cx_Oracle
def emprecordinsert():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#prepare query and execute
iq="insert into employee values (%d,'%s',%f,'%s') "
[Link](iq %(empno,ename,sal,cname))
#OR
#[Link]("insert into employee values (%d,'%s',%f,'%s')"
%(empno,ename,sal,cname))
[Link]()
print("-"*50)
print("{} Emplyee Record Inserted:".format([Link]))
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecordinsert()

259 manojalladi23@[Link]
#write a python program which will insert a record in employee table by accepting employee
values from keyboard
#[Link]
import cx_Oracle
def emprecordinsert():
while(True):
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#prepare query and execute
iq="insert into employee values (%d,'%s',%f,'%s') "
[Link](iq %(empno,ename,sal,cname))
#OR
#[Link]("insert into employee values (%d,'%s',%f,'%s')"
%(empno,ename,sal,cname))
[Link]()
print("-"*50)
print("{} Emplyee Record Inserted:".format([Link]))
print("-"*50)
ch=input("Do u want to insert another employee record(yes/no):")
if(ch=="no"):
break
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
except ValueError:
print("Don't enter strs, symbols and alpha-numerics for Empno, Salary:")

#main program
emprecordinsert()

260 manojalladi23@[Link]
#write a python program which will accept emp from the keyboard ad delete a record from
employee table
#[Link]
import cx_Oracle
def emprecorddelete():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
#prepare query and execute
[Link]("delete from employee where eno=%d" %empno)
[Link]()
print("-"*50)
if ([Link]>0):
print("{} Emplyee Record Deleted:".format([Link]))
else:
print("Employee Record Does not Exist:")
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecorddelete()

#write a python program which will accept emp compnay name from the keyboard ad
delete a record from employee table
#[Link]
import cx_Oracle
def emprecorddelete():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]()
#accept employee values from KBD
print("-"*50)
cname=input("Enter Employee Company Name:")
#prepare query and execute
[Link]("delete from employee where cname='%s' " %cname)
[Link]()
print("-"*50)
if ([Link]>0):
print("{} Emplyee Record Deleted:".format([Link]))
261 manojalladi23@[Link]
else:
print("Employee Record Does not Exist:")
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecorddelete()

#write a python program which will update emp sal by 30% and company name(based on
keyboard input) on the bases of emp number
#[Link]
import cx_Oracle
def emprecordupdate():
try:
con=cx_Oracle.connect("scott/tiger@localhost/orcl")
cur=[Link]()
#accept employee values from KBD
print("-"*50)
eno=int(input("Enter Employee Number:"))
cname=input("Enter Employee Company Name for updattion:")
[Link]("update employee set sal=sal+sal*0.3,cname='%s' where eno=%d"
%(cname,eno))
[Link]()
print("-"*50)
if ([Link]>0):
print("{} Emplyee Record Updated:".format([Link]))
else:
print("Employee Record Does not Exist:")
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)

#main program
emprecordupdate()

262 manojalladi23@[Link]
#Program obtaining connection from MySQL
#[Link]
import [Link]
con=[Link](host="localhost",

user="root",

passwd="root")
print("type of con=",type(con))
print("Python got connection from MySQL")

#Program creating an object of cursor


#[Link]
import [Link]
con=[Link](host="localhost",

user="root",

passwd="root")
cur=[Link]()
print("type of cur=",type(cur))
print("Python Program created an object of cursor

263 manojalladi23@[Link]
#Program creating a data base in mysql on the name of batch6pm
#[Link]
import [Link]
con=[Link](host="localhost",

user="root",

passwd="root")
cur=[Link]()
#prepare qurey and execute
dcq="create database batch6pm"
[Link](dcq)
print("Database created successfully in MySQL")

#Program creating a table in batch6pm database on the name of employee


#[Link]
import [Link]
try:
con=[Link](host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=[Link]()
#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 ) "
[Link](tq)
print("Table created in MySQL--Verify")
except [Link] as db:
print("Problem in Database:",db)

#Program for inserting a record(s) in employee table


#[Link]
import [Link]
def emprecordinsert():
try:
con=[Link](host="localhost",

264 manojalladi23@[Link]
user="root",

passwd="root",

database="batch6pm" )
cur=[Link]()
#accept employee values from KBD
print("-"*50)
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#prepare query and execute
iq="insert into employee values (%d,'%s',%f,'%s') "
[Link](iq %(empno,ename,sal,cname))
[Link]()
print("-"*50)
print("{} Emplyee Record Inserted:".format([Link]))
except [Link] as db:
print("Problem in Database:",db)

#main program
emprecordinsert()

#write a python program which will insert a record in employee table by accepting
employee values from Keyboard
#[Link]
import [Link]
def emprecordinsert():
while(True):
try:
con=[Link](host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=[Link]()
#accept employee values from KBD
print("-"*50)

265 manojalladi23@[Link]
empno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
cname=input("Enter Employee Company Name:")
#prepare query and execute
iq="insert into employee values (%d,'%s',%f,'%s') "
[Link](iq %(empno,ename,sal,cname))
#OR
#[Link]("insert into employee values (%d,'%s',%f,'%s')"
%(empno,ename,sal,cname))
[Link]()
print("-"*50)
print("{} Emplyee Record Inserted:".format([Link]))
print("-"*50)
ch=input("Do u want to insert another employee record(yes/no):")
if(ch=="no"):
break
except [Link] as db:
print("Problem in Database:",db)
except ValueError:
print("Don't enter strs, symbols and alpha-numerics for Empno, Salary:")

#main program
emprecordinsert()

#write a python program which will accept emp compnay name from the keyboard ad
delete a record from employee table
#[Link]
import [Link]
def emprecorddelete():
try:
con=[Link](host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=[Link]()
#accept employee values from KBD

266 manojalladi23@[Link]
print("-"*50)
empno=int(input("Enter Employee Number:"))
#prepare query and execute
[Link]("delete from employee where eno=%d " %empno)
[Link]()
print("-"*50)
if ([Link]>0):
print("{} Emplyee Record Deleted:".format([Link]))
else:
print("Employee Record Does not Exist:")
except [Link] as db:
print("Problem in Database:",db)

#main program
emprecorddelete()

#write a python program which will update emp sal by 30% and company name(based on
keyboard input) on the bases of emp number
#[Link]
import [Link]
def emprecordupdate():
try:
con=[Link](host="localhost",

user="root",

passwd="root",

database="batch6pm" )
cur=[Link]()
#accept employee values from KBD
print("-"*50)
eno=int(input("Enter Employee Number:"))
cname=input("Enter Employee Company Name for updattion:")
empsal=float(input("Enter employee salary for updation:"))
[Link]("update employee set sal=%f,cname='%s' where eno=%d"
%(empsal,cname,eno))
[Link]()
print("-"*50)
if ([Link]>0):
print("{} Emplyee Record Updated:".format([Link]))

267 manojalladi23@[Link]
else:
print("Employee Record Does not Exist:")
except [Link] as db:
print("Problem in Database:",db)

#main program
emprecordupdate()

Object Oriented Principles or Features or Concepts

Index:

=>What are the advantages of OOPs


=>List of Object Oriendted Principles
1. Classes
2. Objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing
1. Classes
=>Importaance and purpose of Classes concept
=>Syntax for Defining Class
=>Types of Data Members
a) Instance Data Members
b) Class Level Data Members
=>Types of Methods
a) Instance Method
b) Class Level Method
c) Static Method
=>What is "self" and "cls"
=>Programming Examples
2. Object
=>Importaance and purpose of Object Concept
=>Syntax for creating Object
=>Programming Examples
=>Programples related to pickling and Data base communication with Classes and objects.

268 manojalladi23@[Link]
=>Constructors in OOPs
=>Importance and purpose of Constructors
=>Types of Constructors
a) Default Constructors
b) Parameterized Constructors
=>Rules for Constructors
=>Programming Examples

=>Detstructrors in OOPs with Garbage Collector


=>Importance and purpose of Detstructrors
=>Syntax for defining Detstructrors
=>Internal flow of Detstructrors
=>relation between Detstructrors and Garbage Collector
=>gc module

3&4. Data Encapsulation and Data Abstraction


=>Importance and purpose of Data Encapsulation
=>Importaance and purpose of Data Abstraction
=>Implementation of data encapsulation and Data Abstraction
=>Programming Examples

5. Inheritance
=>Importaance and purpose of Inheritance
=>Types of Inheritances
a) single
b) multi level
c) hierarchical
d) multiple
e) Hybrid
=>Syntax for Inheritance
=>Programming Examples

Method Overriding in OOPs


=>Importaance and purpose of Method Overriding
=>memory management in Method Overriding
=>Programming Examples

[Link]
=>Importaance and purpose of Polymorphism
=>Difference between Polymorphism and Inheritance
=>Method Overring with Polymorphism

269 manojalladi23@[Link]
=>super() and class name approaches in Polymorphism
=>Programming Examples

Object Oriented Principles or Features or Concepts

=>In real time, to develop any project or application, we must choose a language and it can
satisfy two types of principles. They are
1. Procedure Oriented Principles ---- C,Pascal, cobol,8086,oracle7.3,PYTHON
2. Object Oriented Priciples.--------PYTHON C++ JAVA, .NET.......
=>Even though, PYTHON programming Belongs both Procedure and Object Oriented
Programming language and internally every thing is treated as object.

"Every Thing is an object " --Benifits


(OR)
Adavtanges of Object Oriented Principles

1. Objects allows us to store Large Volume of Data (Platform Indepenedent)


2. The Data is visiting between two machines in the form of Ciphet Text (encrypted Format).
So that we can achieve the Security
3. The Large Volume of Data can be transfered between multiple machines all at once in the
form of objects and obtains effective communication.
4. With Objects we can build high effective Re-Usable Applications.
5. The Data is always available arround Objects (Effective Memory Usage) and functions can
operate on the objects.

List of Object Oriented Principles

=>To say a languge is Object Oriented , It has to sastisfy the following Principles.

1. Classes
2. Objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing(already discussed )

270 manojalladi23@[Link]
1. Classes

=>The purpose of classes concept is that "To Develop Programmer-Defined Data Type and to
develop any any time application."
=>The Purpose of developing Programmer-Defined Data Type is that " 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 names developed by programmers are called Programmer-
defined Data Types.
=>Every Program in OOPs must starts with classes concept. Without classes , we can't develop
single program .

Def. of Class:

A class is a collection of Data members and Methods


=>When we define a class , memory space 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 python

class <clsname>:
Class Level Data Members
def instancemethod(self, list of formal params if any):

Specify Instnace Data Members and Perfoms Specific Operations

@classmethod
def classlevelmethod(cls,list of formal params if any):

Specify Class Data Members and Performs Common Operations

@staticmethod
def staticmethod(list of formal params if any):

Performs Utility / Universal Operations

271 manojalladi23@[Link]
Types of Data Members in class of Python

=>In a class of Python, we can define, 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 Memebers.
=>Instance Data Members are always used for storing Specific Values
=>Instance Data Members can be specifed / defined in 3 ways. They are
a) Through an Object
b) By using Instance Method
c) By using Constructors.
=>Instance Data Members can be accessed w.r.t object name or self
[Link] Data Member
(OR)
[Link] Data Member

2. Class Level Data Members.

=>Class Level Data Members are those, whose memory space is created Only Once
irrespective of number of objects are created.
=>Class Level Data Members are used for Storing Common values.
=>Class Level Data Members can be specifed / defined in 2 ways. They are
a) Inside of Class Definition
b) Inside of Class Level Method
=>Class Level Data Members can be accessed either w.r.t class name or object name or self or
cls
[Link] Level Data Member
(OR)
[Link] Level Data Member
(OR)
[Link] Level Data Member
(OR)
[Link] Level Data Member

272 manojalladi23@[Link]
#program for storing student number,name and marks
#[Link]
class Student:pass # Here Student is called Programmer-defined Data Type.

#main program
s1=Student()
s2=Student()
print("id of s1 object=",id(s1))
print("id of s2 object=",id(s2))
print(" ")
print("content of s1 before adding data:{} and length={}".format(s1. dict , len(s1. dict ) ))
print("content of s2 before adding data :{} and length={}".format(s1. dict , len(s1. dict )
))
print(" ")
#Add the Instance data members to s1 (Through an Object)
[Link]=10
[Link]="RS"
[Link]=22.22
#Add the Instance data members to s2(Through an Object)
[Link]=20
[Link]="TR"
[Link]=33.22
print(" ")
print("content of s1 after adding data:{} and length={}".format(s1. dict , len(s1. dict ) ))
print("content of s2 after adding data :{} and length={}".format(s1. dict , len(s1. dict ) ))
print(" ")

#program for storing student number,name and marks


#[Link]
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)
[Link]=10
[Link]="RS"
[Link]=22.22
#Add the Instance data members to s2(Through an Object)

273 manojalladi23@[Link]
[Link]=20
[Link]="TR"
[Link]=33.22
[Link]="OUCET"
#display content of s1
print(" ")
print("Content of s1 object:")
print(" ")
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print(" ")
#display content of s2
print("Content of s2 object:")
print(" ")
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print("Student College:{}".format([Link]))
print(" ")

#program for storing student number,name and marks


#[Link]
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(" ")
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
print(" ")
#Add the Instance data members to s2(Through an Object)
print("Enter Second Student details:")
print(" ")
[Link]=int(input("Enter Student Number:"))

274 manojalladi23@[Link]
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
print(" ")
print("Content of s1 object:")
print(" ")
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print(" ")
#display content of s2
print("Content of s2 object:")
print(" ")
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print(" ")
-
#program for storing student number,name and marks
#[Link]
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(" ")
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
print(" ")
#Add the Instance data members to s2(Through an Object)
print("Enter Second Student details:")
print(" ")
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
print(" ")

275 manojalladi23@[Link]
print("Content of s1 object:")
print(" ")
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print("Student Course:{}".format([Link]) ) # OR [Link]
print(" ")
#display content of s2
print("Content of s2 object:")
print(" ")
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print("Student Course:{}".format([Link]) ) # OR [Link]
print(" ")

#[Link]
class Circle:
PI=3.14

#main program
c=Circle()
c.r=float(input("Enter Radious:"))
[Link]=[Link]*c.r**2
[Link]=2*[Link]*c.r
print(" ")
print("Radious={}".format(c.r))
print("Area of Circle={}".format([Link]))
print("Perimeter of Circle={}".format([Link]))
print(" ")

276 manojalladi23@[Link]
Types of Methods in a Class

=>In a class of Python, we can define 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 Operatons on the data of object
and Hence Instance Methods are called Object Level Methods.
=>Instance Methods always Takes "self" as First Positional Parameters for obtaining
id of Current Class object.
=>Syntax:-
def InstanceMethodName(self, list of formal params):

-------Specific Operations on objects-------

=>Instance Methods of a Class must be accessed w.r.t object name or self


[Link]()
(or)
[Link]()

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 possible
to access other part of the program

2. Class Level Method

=>Class level Methods are used for Performing Class Level Operatons Such as Specifying Class
Level Data Members and Performs 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

277 manojalladi23@[Link]
=>Syntax:-
@classmethod
def ClassLevelMethodName(cls, list of formal params):

-------Common Operations-------

=>Every Class Level Method can be accessed w.r.t to Class Name or cls or object name or self
[Link] Level method Name()
(OR)
[Link] Level method Name()
(OR)
[Link] Level method Name()
(OR)
[Link] 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 Members 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 the program

#Program for reading student details from KBD and dispay by using Classes and Objects
#[Link]--file name and acts module name
class Student:
def readstudvalues(self ):
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))

#main program
s1=Student()
s2=Student()
#read the values for s1

278 manojalladi23@[Link]
print("Enter First Student details:")
print(" ")
[Link]()
print(" ")
#read the values for s2
print("Enter Second Student details:")
print(" ")
[Link]()
print(" ")
#Display the content of s1
print("Content of First Student object:")
print(" ")
[Link]()
print(" ")
print("Content of Second Student object:")
print(" ")
[Link]()
print(" ")

#Program for reading two numerical values and find sum by using Classes and Objects
#[Link]--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()
[Link]()
[Link]()
res=[Link]()
print("sum({},{})={}".format(res[0],res[1],res[2]))

279 manojalladi23@[Link]
#Program for reading two numerical values and find sum by using Classes and Objects
#[Link]--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:"))
[Link]() # calling sumop() from readvalues()

def sumop(self): # Instance Method


self.c=self.a+self.b
[Link]() # calling dispvalues() from sumop()

def dispvalues(self): # Instance Method


print("sum({},{})={}".format(self.a,self.b,self.c))

#main program
s=Sum()
[Link]()

#Program accepting student details(Instance Method)along with common value(Class


Level Method)
#[Link]
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


[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
print("Student Course1:{}".format(Student.crs1))
print("Student Course2:{}".format(Student.crs2))

280 manojalladi23@[Link]
#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(" ")
[Link]()
print(" ")
#read the values for s2
print("Enter Second Student details:")
print(" ")
[Link]()
print(" ")
#Display the content of s1
print("Content of First Student object:")
print(" ")
[Link]()
print(" ")
print("Content of Second Student object:")
print(" ")
[Link]()
print(" ")

#Program accepting student details(Instance Method)along with common value(Class


Level Method)
#[Link]
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


[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))

281 manojalladi23@[Link]
def dispstudvalues(self):
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
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(" ")
[Link]()
print(" ")
#read the values for s2
print("Enter Second Student details:")
print(" ")
[Link]()
print(" ")
#Display the content of s1
print("Content of First Student object:")
print(" ")
[Link]()
print(" ")
print("Content of Second Student object:")
print(" ")
[Link]()
print(" ")

#Program accepting student details(Instance Method)along with common value(Class


Level Method)
#[Link]
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"

282 manojalladi23@[Link]
def readstudvalues(self ): # Instance Method
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Marks:{}".format([Link]))
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(" ")
[Link]()
print(" ")
#read the values for s2
print("Enter Second Student details:")
print(" ")
[Link]()
print(" ")
#Display the content of s1
print("Content of First Student object:")
print(" ")
[Link]()
print(" ")
print("Content of Second Student object:")
print(" ")
[Link]()
print(" ")

283 manojalladi23@[Link]
3. Static Method

=>Static Methods are those which are used for Performing utility Operation or Universal
Operation
=>Static Methods Definition neither takes "self" nor takes "cls" but it takes an object as
parameter (if req) which belongs other classes
=>Syntax:
@staticmethod
def staticmethodname(list of formal params if any):

----Utility or Universal Operations----

=>Static Methods Must be accessed w.r.t class name or object name

[Link] Method name()


(OR)
[Link] Method Name()

#[Link]
class Employee:
def readempvalues(self):
print("-"*50)
[Link]=int(input("\nEnter Employee Number:"))
[Link]=input("Enter Employee Name:")
[Link]=float(input("Enter Employee Salary:"))
print("-"*50)
class Student:
def readstudvalues(self):
print("-"*50)
[Link]=int(input("\nEnter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
[Link]=input("Enter Student College:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
[Link]=int(input("\nEnter Teacher Number:"))
[Link]=input("Enter Teacher Name:")
[Link]=input("Enter Teacher Subject:")

284 manojalladi23@[Link]
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
[Link]()
#Read the values for Student object
[Link]()
#Read the values for teacher object
[Link]()
#Today i want to define single method, which will print / display any type of object values--
called static method
print("Employee Information")
[Link](e)
print("Student Information")
[Link](s)
print("Teacher Information")
[Link](t)

#[Link]
class Employee:
def readempvalues(self):
print("-"*50)
[Link]=int(input("\nEnter Employee Number:"))
[Link]=input("Enter Employee Name:")
[Link]=float(input("Enter Employee Salary:"))
print("-"*50)
class Student:
def readstudvalues(self):
print("-"*50)
[Link]=int(input("\nEnter Student Number:"))

285 manojalladi23@[Link]
[Link]=input("Enter Student Name:")
[Link]=float(input("Enter Student Marks:"))
[Link]=input("Enter Student College:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
[Link]=int(input("\nEnter Teacher Number:"))
[Link]=input("Enter Teacher Name:")
[Link]=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
[Link]()
#Read the values for Student object
[Link]()
#Read the values for teacher object
[Link]()
#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")
[Link](e)
print("Student Information")
[Link](s)
print("Teacher Information")
[Link](t)

286 manojalladi23@[Link]
#[Link]
class Operation:
def readvalues(self):
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
[Link]=input("Enter any arithmetic operator:")

class Calculator:
@staticmethod
def calc(obj): # obj= {'a': 10.0, 'b': 2.0, 'op': '+'}
if([Link]=="+"):
print("\tsum({},{})={}".format(obj.a,obj.b,obj.a+obj.b))
if([Link]=="-"):
print("\tsub({},{})={}".format(obj.a,obj.b,obj.a-obj.b))
if([Link]=="*"):
print("\tmulm({},{})={}".format(obj.a,obj.b,obj.a*obj.b))
if([Link]=="/"):
print("\tdiv({},{})={}".format(obj.a,obj.b,obj.a/obj.b))
if([Link]=="//"):
print("\tfloar div({},{})={}".format(obj.a,obj.b,obj.a//obj.b))
if([Link]=="%"):
print("\tmod({},{})={}".format(obj.a,obj.b,obj.a%obj.b))
if([Link]=="**"):
print("\texp({},{})={}".format(obj.a,obj.b,obj.a**obj.b))
if([Link] not in ["+","-","*","/","//","%","**"]):
print("{} is not a Arithmetic Operator:".format([Link]))
#main program
o1=Operation()
[Link]()
[Link](o1)

#[Link]
class Operation:
def readvalues(self):
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
[Link]=input("Enter any arithmetic operator:")

class Calculator:
@staticmethod
def calc(obj): # obj= {'a': 10.0, 'b': 2.0, 'op': '+'}

287 manojalladi23@[Link]
match([Link]):
case "+":
print("\tsum({},{})={}".format(obj.a,obj.b,obj.a+obj.b))
case "-":
print("\tsub({},{})={}".format(obj.a,obj.b,obj.a-obj.b))
case "*":
print("\tmulm({},{})={}".format(obj.a,obj.b,obj.a*obj.b))
case "/":
print("\tdiv({},{})={}".format(obj.a,obj.b,obj.a/obj.b))
case "//":
print("\tfloar div({},{})={}".format(obj.a,obj.b,obj.a//obj.b))
case "%":
print("\tmod({},{})={}".format(obj.a,obj.b,obj.a%obj.b))
case "**":
print("\texp({},{})={}".format(obj.a,obj.b,obj.a**obj.b))
case _:
print("{} is not a Arithmetic Operator:".format([Link]))
#main program
o1=Operation()
[Link]()
[Link](o1)

#[Link]
class Operation:
def readvalues(self):
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
[Link]=input("Enter any arithmetic operator:")

class Calculator:
@staticmethod
def calc(obj): # obj= {'a': 10.0, 'b': 2.0, 'op': '+'}
match(obj. dict .get("op")):
case "+":
print("\tsum({},{})={}".format(obj.a,obj.b,obj.a+obj.b))
case "-":
print("\tsub({},{})={}".format(obj.a,obj.b,obj.a-obj.b))
case "*":
print("\tmulm({},{})={}".format(obj.a,obj.b,obj.a*obj.b))
case "/":
print("\tdiv({},{})={}".format(obj.a,obj.b,obj.a/obj.b))

288 manojalladi23@[Link]
case "//":
print("\tfloar div({},{})={}".format(obj.a,obj.b,obj.a//obj.b))
case "%":
print("\tmod({},{})={}".format(obj.a,obj.b,obj.a%obj.b))
case "**":
print("\texp({},{})={}".format(obj.a,obj.b,obj.a**obj.b))
case _:
print("{} is not a Arithmetic Operator:".format([Link]))
#main program
o1=Operation()
[Link]()
[Link](o1)

#[Link]
import cx_Oracle
class Student:
def readstudevalues(self):
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=int(input("Enter Marks in C:"))
[Link]=int(input("Enter Marks in CPP:"))
[Link]=int(input("Enter Marks in Python:"))
def calculations(self):
[Link]=[Link]+[Link]+[Link]
[Link]=([Link]/300)*100
def decidegrade(self):
if(([Link]<40) or ([Link]<40) or ([Link]<40) ):
[Link]="FAIL"
else:
if(([Link]<=300) and ([Link]>=250)):
[Link]="DISTINCTION"
elif(([Link]<=249) and ([Link]>=200)):
[Link]="FIRST"
elif(([Link]<=199) and ([Link]>=150)):
[Link]="SECOND"
elif(([Link]<=149) and ([Link]>=120)):
[Link]="THIRD"
def savestudresult(self):
try:
con=cx_Oracle.connect("scott/tiger@[Link]/orcl")
cur=[Link]()

289 manojalladi23@[Link]
[Link]("insert into result
values(%d,'%s',%d,%d,%d,%d,%f,'%s')"%([Link],[Link],[Link],[Link],[Link],[Link]
tmarks,[Link],[Link]) )
[Link]()
print("\n{} Student Result Saved Successfully:".format([Link]))
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)

#main program
s=Student()
[Link]()
[Link]()
[Link]()
[Link]()

#[Link]
import [Link]
import sys
class Student:
def readstudevalues(self):
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=int(input("Enter Marks in C:"))
[Link]=int(input("Enter Marks in CPP:"))
[Link]=int(input("Enter Marks in Python:"))
def calculations(self):
[Link]=[Link]+[Link]+[Link]
[Link]=([Link]/300)*100
def decidegrade(self):
if(([Link]<40) or ([Link]<40) or ([Link]<40) ):
[Link]="FAIL"
else:
if(([Link]<=300) and ([Link]>=250)):
[Link]="DISTINCTION"
elif(([Link]<=249) and ([Link]>=200)):
[Link]="FIRST"
elif(([Link]<=199) and ([Link]>=150)):
[Link]="SECOND"
elif(([Link]<=149) and ([Link]>=120)):
[Link]="THIRD"
def savestudresult(self):

290 manojalladi23@[Link]
while(True):
try:
[Link]()
[Link]()
[Link]()
con=[Link](host="localhost",

user="root",

passwd="root",

database="batch6pm")
cur=[Link]()
[Link]("insert into result
values(%d,'%s',%d,%d,%d,%d,%f,'%s')"%([Link],[Link],[Link],[Link],[Link],[Link]
tmarks,[Link],[Link]) )
[Link]()
print("\n{} Student Result Saved
Successfully:".format([Link]))
print("-"*50)
ch=input("\nDo u want to insert another student record(yes/no):")
if([Link]()=="no"):
print("Thx for using this program:")
[Link]()
except [Link] as db:
print("Prob in Database:",db)
except ValueError:
print("Don't enter strs, symbols and alpha-numerics for
marks,sno")

#main program
s=Student()
[Link]()

291 manojalladi23@[Link]
Constructors in Python

=>The purpose of Constructors in Python is that "To Initlize the object ".
=>Initlizing the object is nothing but placing our own values in the object without leaving an
object empty.

=>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 initlize the object without leaving an object empty.

Syntax for Defining Constructor:

def init (self, list of formal params if any):

Block of Statements--Initlization

Rules or Properties of Constructor:

1. The Name of the constructor is def init (self)


2. The Constructors automatically or implicitly called by PVM during object creation
3. Constructors should not return any value ( It can return only None value)
4. Constructors paricipates in Inheritance Process.
5. Constructors can be Overridden (can re-defined)

Types Constructors in Python

=>In Python Programming, we have two types of Constructors. They are

1. Default or Paremeter-Less Constructor


2. Parameterized Constructor

1. Default or Paremeter-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 Paremeter-Less Constructor is that "To Initlize multiple objects of
same class with same values".
=>Syntax:
def init (self):

292 manojalladi23@[Link]
Block of Stmts--Initlization

=>Examples

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

[Link] Constructor

=>A Constructor is said to be Paremeterized iff it always takes any argument(s ) or Formal
Param(s)
=>The purpose of Paremeterized Constructor is that "To Initlize multiple objects of
same class with Different values".
=>Syntax:
def init (self, list of formal params):

Block of Stmts--Initlization

Examples:

#[Link]
class Test:
def init (self,a,b):
print("i am from Parameterized Constructor:")
self.a=a
self.b=b

293 manojalladi23@[Link]
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 define both default and Parameterized constructors bcoz PVM
can remember only latest constructor (due to its interpretation Process) . To full fill the need of
both default and parameterized constructors , we define single constructor with default parameter
mechanism.

Examples:

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

#[Link]
class Student:
def getstudvalues(self):
[Link]=10
[Link]="RS"

#main program
s=Student() # Object Creation i want place my own data without leaving an object empty.
print(s. dict )
[Link]()
print(s. dict )

294 manojalladi23@[Link]
#[Link]
class Student:
def init (self):
print("I am from default constructor")
[Link]=10
[Link]="RS"

#main program
s=Student() # Object Creation ---- i want place my own data without leaving an object empty.
print(s. dict )

#[Link]
class Student:
def init (self,sno,sname):
print("I am from Parameterfized constructor")
[Link]=sno
[Link]=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 )

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

295 manojalladi23@[Link]
#[Link]
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

#Program for can Factorial of agiven Number by using Classes and Objects
#[Link]
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")
[Link]()

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

296 manojalladi23@[Link]
#Program for can Factorial of agiven Number by using Classes and Objects
#[Link]
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
[Link]()
except ValueError:
print("Don't enter Strs, symbols and alpha-numric")

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

297 manojalladi23@[Link]
Destructors 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 is role is to collect un-used memory space and it
improves the performnace of python based applications.
=>Every Garbage Collector Program is internally and calling Destructor Functions
=>The destructor function name in python is def del (self).
=>The destructor always called by Garbage Collector when the program executed completed
for de-allocating the memory space. Where as constructor called By PVM implicitly when object
is created for initlizing the object.

=>When the program execution is completed, GC calls its own destructor to de-allocate the
memory space of objects present in program aand it is called automatic Garbage Collection.

=>Hence , We have THREE programming conditions for calling GC and to make the garbage
collector to call destructor Functions.

a) By default (or) automatically GC calls destructor, when the program execution completed.
b) Make the object refereence as None by Forcefully
Syntax : objname=None
c) delete the object by using del by Forcefully
Syntax:- del objname

=>Syntax:

def del (self):

Garbage Collector

=>Garbage Collector contains a pre-defined module called "gc"


=>Here gc contains the following contains the following Functions.

1) isenabled()
2) enable()
3) disable()
=>GC is not under control Programmer but it always maintained and mangaged by OS and PVM

298 manojalladi23@[Link]
#[Link]
class Student:
def init (self,sno,sname):
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))

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

#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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:")
[Link](5)
#Here GC calls destructor automatically when the program execution completed---This is
called automatic Garbage Collection.

299 manojalladi23@[Link]
#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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:")
[Link](5)
s1=None
[Link](5)
s2=Student(20,"Umesh")
s3=Student(30,"Rossum")
s4=Student(40,"Ritche")
print("Program Execution Ended:")
[Link](5)
#Here GC calls destructor automatically when the program execution completed---This is
called automatic Garbage Collection.

#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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:")
[Link](5)
s1=None # Forcefully calling GC

300 manojalladi23@[Link]
[Link](5)
s2=Student(20,"Umesh")
print("No Longer Interested to maintain s2 object:")
[Link](5)
s2=None # Forcefully calling GC
[Link](5)
s3=Student(30,"Rossum")
print("No Longer Interested to maintain s3 object:")
[Link](5)
s3=None # Forcefully calling GC
[Link](5)
s4=Student(40,"Ritche")
print("No Longer Interested to maintain s4 object:")
[Link](5)
s4=None # Forcefully calling GC
[Link](5)
print("Program Execution Ended:")

#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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:")
[Link](5)
del s1 # Forcefully calling GC
[Link](5)
s2=Student(20,"Umesh")
print("No Longer Interested to maintain s2 object:")
[Link](5)
del s2 # Forcefully calling GC
[Link](5)
s3=Student(30,"Rossum")

301 manojalladi23@[Link]
s4=Student(40,"Ritche")
print("No Longer Interested to maintain s3 object and s4 object:")
[Link](5)
del s3 # Forcefully calling GC
del s4 # Forcefully calling GC
[Link](5)
print("Program Execution Ended:")

#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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.

#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
def del (self): # Destructor called by GC
print("GC calls del (self)-for de-allocating Memory space:")

#main program
print("Program Execution Started:")

302 manojalladi23@[Link]
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print("No Longer Interested to maintain s1 object:")
[Link](5)
del s1 # Forcefully calling GC
print("No Longer Interested to maintain s2 object:")
[Link](5)
del s2 # Forcefully calling GC
print("Program Execution Ended:")

#[Link]
import time
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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:")
[Link](5)
del s1 # Forcefully calling GC
print("No Longer Interested to maintain s2 object:")
[Link](5)
del s2 # Forcefully calling GC
print("No Longer Interested to maintain s3 object:")
[Link](5)
s3=None # Forcefully calling GC
print("Program Execution Ended:")

#[Link]
import gc
print("Line--3: Is is GC Running=", [Link]()) # True
print("This is Python Class")

303 manojalladi23@[Link]
print("Python developed by RS")
[Link]()
print("Line No:7-->Is is GC Running=", [Link]()) # False
print("Python is an oop lang")
[Link]()
print("Line--10: Is is GC Running=", [Link]()) # True
print("Python is Fun lang")

#[Link]
import time,gc
class Student:
def init (self,sno,sname): # Constructor called by PVM
[Link]=sno
[Link]=sname
print("\t{}\t{}".format([Link],[Link]))
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=", [Link]()) # True
s1=Student(10,"Litun")
s2=Student(20,"Umesh")
[Link]()
print("Line--17: Is is GC Running=", [Link]()) # False
print("Program Execution Ended:")
[Link](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 Confidental Information / Features of
Class (Data Members and Methods ) ".
=>Data Encapsulation can be applied in two levels. They are
a) At Data Members Level
b) At Methods Level

304 manojalladi23@[Link]
=>To implement Data Encapsulation in python programming, The Data Members , Methods
must be preceded with double under score ( _ _ )

Syntax1:- (Data member Lavel )


class <ClassName>:
def methodname(self):
self. Data MemberName1=Value1
self. Data MemberName2=Value2

self. Data MemberName-n=Value-n

(OR)

Syntax1:- ( Data member Lavel )

class <ClassName>:
def init (self):
self. Data MemberName1=Value1
self. Data MemberName2=Value2

self. Data MemberName-n=Value-n

Syntax2:- (Method Level)

class <ClassName>:
def methodname(self):
[Link] MemberName1=Value1
[Link] MemberName2=Value2

[Link] MemberName-n=Value-n

Example1:

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


class Account:
def getaccountdet(self):
self. acno=34567
[Link]="Rossum"

305 manojalladi23@[Link]
self. bal=34.56
[Link]="SBI"
self. pin=1234
[Link]=4444444
#here acno,bal and pin are encapsulated

Example2:

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


class Account1:
def getaccountdet(self): # here getaccountdet() is made is encapsulated
[Link]=34567
[Link]="Rossum"
[Link]=34.56
[Link]="SBI"
[Link]=1234
[Link]=4444444

Data Abstraction:

=>The Process of retrieving / extracting Essential Details without considering Hidden Details is
called Data Abstraction.

Example1:

#[Link] -- This Program access only cname,bname and pincode only


from account import Account
ao=Account()
[Link]()
#print("Account Number={}".format([Link])) Not Possible to access
print("Account Holder Name={}".format([Link]))
#print("Account Bal={}".format([Link])) Not Possible to access
print("Account Branch Name={}".format([Link]))
#print("Account PIN={}".format([Link])) Not Possible to access
print("Account Branch Pin Code={}".format([Link]))

306 manojalladi23@[Link]
Example2:

#[Link]--here we can't access method itself. so that we cant access Instance Data
Members.
from account1 import Account1
ao=Account1()
#[Link]()---can't access
#print("Account Number={}".format([Link]))
#print("Account Holder Name={}".format([Link]))
#print("Account Bal={}".format([Link]))
#print("Account Branch Name={}".format([Link]))
#print("Account PIN={}".format([Link]))
#print("Account Branch Pin Code={}".format([Link]))

Note:- We can't apply Data Encapsulation on Constructors in Python but whose Initlized Data
Memebrs can be encapsulated.

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


class Account:
def init (self):
self. acno=111 # encaspsulated
[Link]="Rossum"
self. bal=5.5 # encaspsulated
self. pin=4567 # encaspsulated
[Link]="SBI"

#[Link]--------------------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([Link]))
#print("Account Balance:{}".format([Link])) can't access
#print("Account pin:{}".format([Link])) can't access
print("Account Branch Name:{}".format([Link]))
print("-"*50)

307 manojalladi23@[Link]
#[Link]--- file name and module name
class Account:
def getaccdetails(self):
self. acno=111 # encaspsulated
[Link]="Rossum"
self. bal=5.5 # encaspsulated
self. pin=4567 # encaspsulated
[Link]="SBI"

#[Link]---------------Data Abstraction process


from Account2 import Account
ac=Account()
[Link]()
print("Account Details")
print("-"*50)
#print("Account Number:{}".format([Link])) can't access
print("Account Holder Name:{}".format([Link]))
#print("Account Balance:{}".format([Link])) can't access
#print("Account pin:{}".format([Link])) can't access
print("Account Branch Name:{}".format([Link]))
print("-"*50)

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


class Account:
def getaccdetails(self): # encaspsulated
[Link]=111
[Link]="Rossum"
[Link]=5.5
[Link]=4567
[Link]="SBI"

#[Link]----------------Data Abstraction process


from Account3 import Account
ac=Account()
#[Link]() can't access
print("Account Details")
print("-"*50)
"""print("Account Number:{}".format([Link]))
print("Account Holder Name:{}".format([Link]))
print("Account Balance:{}".format([Link]))
print("Account pin:{}".format([Link]))

308 manojalladi23@[Link]
print("Account Branch Name:{}".format([Link]))
print("-"*50)""" # can't access

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


class Account:
def init (self): # Not comes under Data Encapsulation
[Link]=111
[Link]="Rossum"
[Link]=5.5
[Link]=4567
[Link]="SBI"

#[Link]-------------------Data Abstraction process


from Account4 import Account
ac=Account()
print("Object Created")
ac. init () # Not comes under Data Encapsulation
print("Account Number:{}".format([Link]))
print("Account Holder Name:{}".format([Link]))
print("Account Balance:{}".format([Link]))
print("Account pin:{}".format([Link]))
print("Account Branch Name:{}".format([Link]))

objects in Python

=>When we define a class, memory space is not created for Data Members and Methods but
whose memory is created when we create an object w.r.t class name.
=>To do any Data Processing, It is mandatory to create an object.
=>To create an object, there must exists a class Definition otherwise we get NameError.

Definition of object:

=>Instance of a class is called object ( Instance is nothing but allocating sufficient memory space
for the Data Members and Methods of a class).

Syntax for creating an object

varname=classname()

Examples: create an object of Student

309 manojalladi23@[Link]
so=Student()
Example:- create an object Employee

eo=Employee()

Differences Betwwen Classes and Objects

Class:

1) A class is a collection of Data Members and Methods


2) When we define a class, memory space is not created for Data Members and Methods and it
can be treated as specification / model for real time application.
3) Definition of a perticular 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 create 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 crate an object after loading the class definition otherwise we get NameError

Inheritance

=>Inhenritance is one of distinct features of OOPs


=>The purpose of Inheritance is that " To build Re-usable Applications in Python Object
Oriented Programming".

=>Definition of Inheritance:

=>The Process obtaining Data members , Methods and Constructors (Features ) of one class
into another class is called Inheritance.
=>The class which is giving Data members , Methods and Constructors (Features ) is called
Super or Base or Parent Class.
=>The Class which is taking Data members , Methods and Constructors (Features ) is called
Sub or Derived or Child Class.
=>The Inheritance concept always follows Logical (Virtual)Memory Management. This

310 manojalladi23@[Link]
Memory Management says that " Neither we write Source Code nor Takes Physical Memory
Space ".

Advatnages of Inheritance:

=>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. Redundency (Duplication ) of the code is minimized.

311 manojalladi23@[Link]
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):

312 manojalladi23@[Link]
Explanation

=>Here clsname-1,clsname-2, ... clsname-n are called Base or Super Classes


=><clsname-n+1> is called Derived ot 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 bcoz it inherits all the features of Intermediate Base Classes
and top most base class.
=>For Every Class in Python, there exist a pre-defined implicit base class called "object" bcoz it
provides Garbage Collection to all its sub classes.

#[Link]
class BC:
def getN(self):
self.n=float(input("Enter a number:"))

class DC(BC):
def square(self):
[Link]=self.n**2
def disp(self):
print("square({})={}".format(self.n,[Link]))

#main program
do1=DC()
[Link]()
[Link]()
[Link]()

-
#[Link]
class BC:
def getN(self):
self.n=float(input("Enter a number:"))

class DC(BC):
def square(self):
[Link]=self.n**2
def disp(self):
[Link]() # Calling Base Class Instance Method Name
[Link]() # Calling Current Class Instance Method Name

313 manojalladi23@[Link]
print("square({})={}".format(self.n,[Link]))
#main program
do1=DC()
[Link]()

-
#write a python program which will implement the following let us assume there exist a
class called university which contains university name and location accept and display
university dtails let us assume there exist a college which contains college name and its
location. accept and display college details along with university details . let us assume
there exist student contains student nmber,sname, and course pursing. accept and display
student details along with college and university details
#[Link]
class Univ:
def getunivdet(self):
[Link]=input("Enter University Name:")
[Link]=input("Enter University Location:")

def dispunivdet(self):
print("-"*50)
print("University Name:{}".format([Link]))
print("University Location:{}".format([Link]))
print("-"*50)

class College(Univ):
def getcolldet(self):
[Link]=input("Enter College Name:")
[Link]=input("Enter College Location:")

def dispcolldet(self):
print("-"*50)
print("College Name:{}".format([Link]))
print("College Location:{}".format([Link]))
print("-"*50)

class Student(College):
def getstuddet(self):
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=input("Enter Student Course:")
def dispstuddet(self):

314 manojalladi23@[Link]
print("-"*50)
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Course:{}".format([Link]))
print("-"*50)

#main program
s=Student()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

-
#[Link]---File Name and Module Name
class Univ:
def getunivdet(self):
[Link]=input("Enter University Name:")
[Link]=input("Enter University Location:")

def dispunivdet(self):
print("-"*50)
print("University Name:{}".format([Link]))
print("University Location:{}".format([Link]))
print("-"*50)

-
#[Link] ----- File Name and Module Name
from Univ import Univ
class College(Univ):
def getcolldet(self):
[Link]=input("Enter College Name:")
[Link]=input("Enter College Location:")

def dispcolldet(self):
print("-"*50)
print("College Name:{}".format([Link]))
print("College Location:{}".format([Link]))
print("-"*50)

315 manojalladi23@[Link]
#[Link]---file name and module name
from College import College
class Student(College):
def getstuddet(self):
[Link]=int(input("Enter Student Number:"))
[Link]=input("Enter Student Name:")
[Link]=input("Enter Student Course:")
[Link]()
[Link]()
def dispstuddet(self):
[Link]()
[Link]()
print("-"*50)
print("Student Number:{}".format([Link]))
print("Student Name:{}".format([Link]))
print("Student Course:{}".format([Link]))
print("-"*50)

-
#[Link]
from Student import Student
s=Student()
[Link]()
[Link]()

-
#[Link]
class Father:
def fatherproperty(self):
[Link]=float(input("Enter Property of Father:"))

class Mother:
def motherproperty(self):
[Link]=float(input("Enter Property of Mother:"))

class Child(Father,Mother):

316 manojalladi23@[Link]
def childprop(self):
[Link]=float(input("Enter Property of Child:"))
[Link]()
[Link]()
def totproperty(self):
[Link]=[Link]+[Link]+[Link]
def disptotalprop(self):
[Link]()
[Link]()
print("-"*50)
print("Child Property:{}".format([Link]))
print("Father Property:{}".format([Link]))
print("Mother Property:{}".format([Link]))
print("-"*50)
print("Total Property:{}".format([Link]))
print("-"*50)
#main program
c=Child()
[Link]()

Method Overriding in Python

=>Method Overriding=Method Heading is same + Method Body is Different


(OR)
=>The process of re-defining the original method of base class into various derived classes for
performing different operations is called Method Overriding.
=>To use Method Overriding in python program we must apply Inheritance Principle.
=>Method Overriding used for implementing Polymorphism Principle.

Examples:

#[Link]
class Circle:
def draw(self): # original Method
print("Drawing Circle")

class Rect(Circle):
def draw(self): # overridden Method
print("Drawing Rect:")

317 manojalladi23@[Link]
super().draw()

class Square(Rect):
def draw(self): # overridden Method
print("Drawing Square:")
super().draw()

#main program
so=Square()
[Link]()

-
#[Link]
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()
[Link]()
ps=PerfectStudent()
[Link]()

Polymorphism in Python

=>Polymorphism is one of the distinct features of OOPs


=>The purpose of Polymorphism is that "Efficient Utilization Memory Spacee (OR) Less
Memory space is achieved".

=>Def. of Polymorphism:

=>The Process of Representing "One Form in multiple Forms " is called Polymorphism.
=>The Polymorphism Principle is implemented(Bring into action) by Using "Method

318 manojalladi23@[Link]
Overriding" feature of all OO Programming Languages.
=>In The definition of polymorphism, "One Form" represents "Original Method" and multiple
forms represents Overridden Methods.
=>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 "Overridden Method(multiple Forms)".

Number of approaches to call original methods constructors


from Overridden methods / Constructors

=>We have two approches to call original method / constructors of base class from overridden
method / constructors of derived class. They are

1) By using super()
2) By using Class Name

1) By using super():

=>super() is one of the 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 immediate base class method but unable to call Specified
method of base Class . To do this we must use class name approach.

2) By using Class Name:

=>By using ClassName approach, we can call any base class method / constructor name from the
context of derived class method / constructor names.

Syntax1:- [Link](self, list of values if any)


Syntax2:- ClassName. init (self, list of values if any)

#[Link]

319 manojalladi23@[Link]
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()

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

-
#[Link]
class Circle:
def draw1(self):
print("Drawing--Circle")

class Rect(Circle):

320 manojalladi23@[Link]
def draw2(self):
print("Drawing---Rect")

#main program
r=Rect()
r.draw1()
r.draw2()

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

#main program
s=Square()
[Link]()

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

321 manojalladi23@[Link]
class Square(Circle,Rect):
def init (self): # Overridden Constructor (Multiple Forms)
print("Drawing--Square--DC")
Rect. init (self)
super(). init ()

#main program
s=Square()

#write a python program which will calculate area of different figures by using
polymorphism
#[Link]
class Circle:
def area(self,r):
print("-"*50)
[Link]=3.14*r**2
print("Area of Circle={}".format([Link]))
print("-"*50)
class Square(Circle):
def area(self,s):
print("-"*50)
[Link]=s**2
print("Area of Square:{}".format([Link]))
print("-"*50)
class Rect(Square):
def area(self,l,b=0):
print("-"*50)
[Link]=l*b
print("Area of Rect:{}".format([Link]))
print("-"*50)
[Link](self,float(input("Enter Radious:")))
super().area(float(input("Enter Side:")))

#main program
r=Rect()

322 manojalladi23@[Link]
[Link](float(input("Enter Length:")),float(input("Enter breadth:")) )

-
#write a python program which will calculate area of different figures by using
polymorphism
#[Link]
class Circle:
def init (self,r):
print("-"*50)
[Link]=3.14*r**2
print("Area of Circle={}".format([Link]))
print("-"*50)
class Square:
def init (self,s):
print("-"*50)
[Link]=s**2
print("Area of Square:{}".format([Link]))
print("-"*50)
class Rect(Square,Circle):
def init (self,l,b=0):
print("-"*50)
[Link]=l*b
print("Area of Rect:{}".format([Link]))
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 Expressions
=>Module Name for Regular Expressions ( re )
=>Functions in "re" module
1) finditer()

323 manojalladi23@[Link]
2) findall()
3) search()
4) start()
5) end()
6) group()
=>Programming Examples

=>Programmer-Defined Character Classes


=>Programming Examples
=>Pre-Defined Character Classes
=>Programming Examples
=>Quantifiers in Regular Expressions
=>Programming Examples

=>Combined Programming Examples on Programmer, Pre-defined and Quantifers.

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

=>Def. of Regular Expression:

=>A Regular Expression is one of the Search Pattern which is a combination of alphabets , digits
and special symbols and it is used to search or match or find in the given data and obtains desired
result .

Applications 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

324 manojalladi23@[Link]
Module name for Regular Expressions(RegEx)
=>To deal with Regular Expressions programs, we must use a pre-defined module called "re".
=>"re" module contains the following functions.
1) finditer()
2) findall()
3) search()
4) start()
5) end()
6) group()

Pre-defined Functions in re module

=>The 're' module contains the follwing essential Functions.

1) finditer():

Syntax:- varname=[Link]("search-pattern","Given data")


=>here varname is an object of type <class,'Callable_Itetaror'>

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

2) group():

=>This function is used obtaining matched value by the findIter()


=>This function present in match class of re module
Syntax:- varname=[Link]()

3) start():

=>This function is used obtaining starting index of matched value


=>This function present in match class of re module
Syntax: varname=[Link]()

325 manojalladi23@[Link]
4)end():
=>This function is used obtaining end index+1 of matched value
=>This function present in match class of re module
Syntax: varname=[Link]()

4) search():

Syntax:- varname=[Link]("search-pattern","Given data")


=>here varname is an object of <class,'[Link]'> or <class,'NoneType'>

=>This function is used for searching the search pattern in given data for first occuence / match
only but not for other occurences / matches.
=>if the search pattern found in given data then it returns an object of match class which
contains matched value and start and end index values and it indicates search is successful.
=>if the search pattern not found in given data then it returns None which is type <class,
"NoneType"> and it indicates search is un-successful

5) findall():

Syntax:- varname=[Link]("search-pattern","Given data")


=>here varname is an object of <class,'list'>

=>This function is used for searching the search pattern in entire given data and find all
occurences / matches and it returns all the matched values in the form an object <class,'list'> but
not returning Start and End Index Values.

#[Link]
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="Python"
lst=[Link](sp,gd)
print("'{}' is found {} Times:".format(sp,len(lst)))

-
#[Link]
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="python"
matobj=[Link](sp,gd) # here matobj is an object of <class , [Link]>
if(matobj!=None):

326 manojalladi23@[Link]
print("\nSearch is Sucessful")

327 manojalladi23@[Link]
print("Start Index:{} End Index:{}
Value:{}".format([Link](),[Link](),[Link]()) )
else:
print("\nSearch is Not Successful")

-
#[Link]
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="ant"
obj=[Link](sp,gd) # Here obj is an object of <class 'callable_iterator'>
for m in obj:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](),[Link]()))

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] ---------------- >Searches for Upper Case Alphabets
4) [^A-Z]----------------->Searches for all except Upper Case Alphabets
5) [a-z] ----------------- >Searches for all lower Case Alphabets
6) [^a-z] ------------------ >Searches for all except lower Case Alphabets
7) [0-9] -------------------->Searches for digits only
8) [^0-9] ------------------- >Searches for all except digits
9) [A-Za-z] ---------------- >Searches for all alphabets
10) [^A-Za-z] ------------- >Searches for all except alphabets
11) [A-Za-z0-9]----------->Searches for all Alpha-Numerics or Alphabets and Digits
12) [^A-Za-z0-9] --------- >Searches for all special symbols ( Except Alpha-Numerics )
13) [a-z0-9] --------------- >Searches for Lower alphabets and digits
14) [^a-z0-9] -------------- >Searches for all except Lower alphabets and digits
15) [A-Z0-9] -------------- >Searches for Upper alphabets and digits
16) [^A-Z0-9]] --------------- >Searches for all except Upper alphabets and digits

328 manojalladi23@[Link]
#[Link]
#Searching for either 'a' or 'b' or 'c' only
import re
mat=[Link]("[abc]","cAKL5&@9HpaTbU*#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

Start Index:0 End Index:1 Value:c


Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:b

"""

-
#[Link]
#Searching for all except a' or 'b' or 'c'
import re
mat=[Link]("[^abc]","cAKL5&@9HpaTbU*#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

329 manojalladi23@[Link]
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

"""

-
#[Link]
#Searches for Upper Case Alphabets only
import re
mat=[Link]("[A-Z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

-
#[Link]
#Searches for all except Upper Case Alphabets
import re
mat=[Link]("[^A-Z]","cA5&@K9HpaTbU*L#4QLe")

330 manojalladi23@[Link]
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

"""
#[Link]
#Searches for all lower Case Alphabets only
import re
mat=[Link]("[a-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)
"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

331 manojalladi23@[Link]
"""

-
#[Link]
#Searches for all except lower Case Alphabets.
import re
mat=[Link]("[^a-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

"""

-
#[Link]
#Searches for all digits
import re
mat=[Link]("[0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:

332 manojalladi23@[Link]
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

Start Index:2 End Index:3 Value:5


Start Index:6 End Index:7 Value:9
Start Index:16 End Index:17 Value:4

"""

-
#[Link]
#Searches for all except digits
import re
mat=[Link]("[^0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)
"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

333 manojalladi23@[Link]
"""

-
#[Link]
#Searches for all alphabets
import re
mat=[Link]("[A-Za-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

-
#[Link]
#Searches for all except alphabets
import re
mat=[Link]("[^A-Za-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

334 manojalladi23@[Link]
"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

-
#[Link]
#Searches for all alphabets and Digits only(Except Special Symbols)
import re
mat=[Link]("[A-Za-z0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

335 manojalladi23@[Link]
"""

-
#[Link]
#Searches for all special symbols except alphabets
import re
mat=[Link]("[^A-Za-z0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

"""

-
#[Link]
#Searches for Space Character
import re
mat=[Link]("\s","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""

E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

Start Index:4 End Index:5 Value:


Start Index:11 End Index:12 Value:
"""

336 manojalladi23@[Link]
#[Link]
#Searches for all except Space Character
import re
mat=[Link]("\S","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)
"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

-
#[Link]
#Searches for all digits
import re
mat=[Link]("\d","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))

337 manojalladi23@[Link]
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

Start Index:2 End Index:3 Value:5


Start Index:7 End Index:8 Value:9
Start Index:18 End Index:19 Value:4
"""

#[Link]
#Searches for all except except digits
import re
mat=[Link]("\D","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)
"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

338 manojalladi23@[Link]
"""

-
#[Link]
#Searches for all except except digits
import re
mat=[Link]("\w","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
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
"""

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"

339 manojalladi23@[Link]
1) \s ---------------- > Search for space character

2) \S ---------------->Searches for all except space character

3) \d------------------>Searches for all digits only OR [0-9]

4) \D------------------>Searches for all except Digits OR [^0-9]

5) \w----------------->Searches for any word character ( Alphabets and Digits) OR [A-Za-z0-9]

6) \W---------------->Searches for special symbols OR [^A-Za-z0-9]

#[Link]
#Searches for all special symbols
import re
mat=[Link]("\W","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

"""

#[Link]
#Searches for only 'k'
import re
mat=[Link]("k","kvkkvkkkvkv")

340 manojalladi23@[Link]
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

"""

-
#[Link]
#Searches for either one 'k' or more k's
import re
mat=[Link]("k+","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

"""

#[Link]
#Searches for either zero k or one 'k' or more k's

341 manojalladi23@[Link]
import re
mat=[Link]("k*","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

-
#[Link]
#Searches for all
import re
mat=[Link](".","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{} Value:{}".format([Link](),[Link](), [Link]()))
print("-"*50)

"""
E:\KVR-PYTHON-6PM\REGEXPRS>py [Link]

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

342 manojalladi23@[Link]
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

"""

-
#Program for mobile number validation
#[Link]
import re
while(True):
mno=input("Enter Ur Mobile Number:")
if(len(mno)==10):
result=[Link]("\d{10}",mno)
if(result!=None):
print("Mobile Number is valid:")
break
else:
print("Mobile Number should Not contain Alphabets and special
symbols:")
else:
print("Mobile Number is invalid, bcoz it contains more than 10 digits")

-
#Program for obtaining names of people from given text.
#[Link]
import re
gd="Rossum got 40 marks , Ritche got 55 marks , Rakesh got 22 marks , Ramesh got 33 marks
and Rajesh got 11 marks and Suvendu got 22 marks"
names=[Link]("[A-Z][a-z]+",gd)
print("-"*50)
print("Names of Students:")
print("-"*50)
for val in names:
print("\t{}".format(val))
print("-"*50)

#Program for obtaining names of people from given text.
#[Link]
import re

343 manojalladi23@[Link]
gd="Rossum got 40 marks , Ritche got 55 marks , Rakesh got 22 marks , Ramesh got 33 marks
and Rajesh got 11 marks and Suvendu got 22 marks"
names=[Link]("[A-Z][a-z]+",gd)
print("-"*50)
print("Names of Students:")
print("-"*50)
for val in names:
print("\t{}".format([Link]()))
print("-"*50)

-
#Program for obtaining name and marks of people from given text.
#[Link]
import re
gd="Rossum got 40 marks , Ritche got 55 marks , Rakesh got 22 marks , Ramesh got 33 marks
and Rajesh got 11 marks and Suvendu got 22 marks"
names=[Link]("[A-Z][a-z]+",gd)
marks=[Link]("\d{2}",gd)
print("-"*50)
print("\tNames \tMarks ")
print("-"*50)
for n,m in zip(names,marks):
print("\t{}-->{}".format(n,m))
print("-"*50)

-
#Program for obtaining name and marks of people from given the file ([Link])
#[Link]
import re
try:
with open("E:\KVR-PYTHON-6PM\OOPS\[Link]","r") as fp:
filedata=[Link]()
names=[Link]("[A-Z][a-z]+",filedata)
marks=[Link]("\d{2}",filedata)
print("-"*50)
print("\tNames \tMarks ")
print("-"*50)
for n,m in zip(names,marks):
print("\t{}-->{}".format(n,m))
print("-"*50)

344 manojalladi23@[Link]
except FileNotFoundError:
print("File does not exist")

-
#Program for obtaining name and marks of people from given the file ([Link])
#[Link]
import re
try:
with open("E:\KVR-PYTHON-6PM\OOPS\[Link]","r") as fp:
filedata=[Link]()
names=[Link]("[A-Z][a-z]+",filedata)
marks=[Link]("\d{2}",filedata)
mails=[Link]("\S+@\S+",filedata)
print("-"*50)
print("\tNames \tMarks\tMails ")
print("-"*50)
for n,m,ma in zip(names,marks,mails):
print("\t{}-->{}--->{}".format(n,m,ma))
print("-"*50)

except FileNotFoundError:
print("File does not exist")

-
#Program for obtaining mails from file data
#[Link]
import re
gd="Rossum got 40 marks and whose mail id is rossum123@[Link] , Ritche got 55 marks and
whose mail id is ritche_c@[Link] , Rakesh got 22 marks and whose mail id is
rakesh_java@[Link] , Ramesh got 33 marks and whose mail id is ramesh_sci@[Link] and
Rajesh got 11 marks and whose mail id is rajesh.k@[Link] and Suvendu got 22 marks and
whose mail id is suv_123@[Link] and Ram got 66 marks and whose mail id is
ram.R@[Link]"
mails=[Link]("\S+@\S+",gd)
print("-"*50)
print("Mails of Students:")
print("-"*50)
for val in mails:
print("\t{}".format([Link]()))
print("-"*50)

345 manojalladi23@[Link]
-
#Program for obtaining marks of people from given text.
#[Link]
import re
gd="Rossum got 40 marks , Ritche got 55 marks , Rakesh got 22 marks , Ramesh got 33 marks
and Rajesh got 11 marks and Suvendu got 22 marks"
marks=[Link]("\d{2}",gd)
print("-"*50)
print("Marks of Students:")
print("-"*50)
for val in marks:
print("\t{}".format([Link]()))
print("-"*50)

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 arrays
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 Basic Slicing on ndarray in numpy
=>Advanced Indexing Advanced Slicing on ndarray in numpy
=>Copy and View on ndarray object
=>Selecting Elements or Filtering Elements from ndarray
=>Sortubng and Searching operations on ndarray

346 manojalladi23@[Link]
NUMPY
Introduction to 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 and it present in
(C:\Users\nareshit\AppData\Local\Programs\Python\Python39\Scripts)
=>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 numpy module.
=>A Numpy module is a collection of Variables, Functions and Classes.

History of Numpy:

=>Numpy was developed by studying existing module called "Numeric 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 languages.

Advantages of using NumPy

Need of NumPy:

=>With the revolution of data science, data analysis libraries like NumPy, SciPy, Scikit, Pandas,
etc. have seen a lot of growth. 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.

347 manojalladi23@[Link]
The advantages of Numpy Programming are:

1) With Numpy Programming, we can deal with Arrays such 1-D, 2-D and Multi Dimensional
Arrays.
2) NumPy maintains minimal memory for large sets of data:
3) Numpy provides Fast in Performing Operations bcoz internally its data is available at
same address.
4) NumPy performs array-oriented computing.
5) It efficiently implements the multidimensional arrays.
6) It performs scientific computations.
7) It is capable of performing reshaping the data stored in multidimensional arrays.
8) NumPy provides Many in-built functions for Various Complex Mathematical Operations such
as statistical , financial, trigonometric Operations etc.

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 organized in the object of "ndarray", which is one of the
pre-defined class in numpy module. Hence 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 and ndarray object of Numpy Module:

=>An object of list contains both homogeneous and hetrogeneous 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 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 Vector based operations.
=>In large sampling of data, List based applications takes more memory space where as ndarray
object takes less memory space.
=>List based applications are not effiecient bcoz list object values takes more time to extract or
retrive ( they are available at different Address) where as numpy based applications are efficient
bcoz of ndarray object values takes less to time to extract or retrive( they are available at same
Address).
=>List object can't perform complex mathematical operations where as an object of ndarray can
perform complex mathematical operations.

348 manojalladi23@[Link]
Quantifiers in Regular Expressions

=>Quantifiers in Regular Expressions are used for searching number of occurences of the
specified value (alphabets or digits or special symbols) used in search pattern to search in the
given data and obtains desired result.

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 searches for all

Note:

\ddd or \d{3} ---- >searches for 3 digits


\dd.\dd--- searhes for 2 integer values and 2 decimal values
\d{2,4} --- searches for min 2 digit number and max 4 digit number.
[A-Za-z]+ ---searches one alphabet or More alphabets.
\w+
[0-9]+ or \d+

Number of approaches to create an object of ndarray

=>In numpy programmiong, 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 Objects into ndrray object.
=>Syntax:- varname=[Link]( Object,dtype )
Here var name is an object of <class,ndarray>
here array() is pre-defined function of numpy module used for converting

349 manojalladi23@[Link]
Traditional Python Objects into ndrray object.
object represents any Traditional Python Objects
dtype represents any numpy data type such as int8,int16,int32,float16, float 32,
float64,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=[Link](l1)
>>> print(a,type(a)) ---------------[10 20 30 40 50 60] <class '[Link]'>
>>> t=(10,20,30,40,50,60,70)
>>> print(t,type(t)) -------------(10, 20, 30, 40, 50, 60, 70) <class 'tuple'>
>>> a=[Link](t)
>>> print(a,type(a)) -------------[10 20 30 40 50 60 70] <class '[Link]'>
>>> d1={10:1.2,20:4.5,30:6.7}
>>> a=[Link](d1)
>>> a --- array({10: 1.2, 20: 4.5, 30: 6.7}, dtype=object)

-
>>> t=(10,20,30,40,50,60)
>>> a=[Link](t)
>>> a ------------- array([10, 20, 30, 40, 50, 60])
>>> [Link] ----------- 1
>>> [Link] --------- dtype('int32')
>>> [Link] ----------- (6,)
>>> b=[Link](3,2)
>>> c=[Link](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 '[Link]'>
>>> print(c,type(c))

350 manojalladi23@[Link]
[[10 20 30]
[40 50 60]] <class '[Link]'>
>>> [Link] ------------ 2
>>> [Link] ----------- 2
>>> [Link] --------------(3, 2)
>>> [Link] ----------- (2, 3)
>>> d=[Link](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=[Link](t1)
>>> a
array([[10, 20],
[30, 40]])
>>> [Link] --------- 2
>>> [Link] -------- (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=[Link](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]]]
>>> [Link]
3
>>> [Link]
(2, 2, 3)
>>> b=[Link](4,3)

351 manojalladi23@[Link]
>>> b
array([[10, 20, 15],
[30, 40, 25],
[50, 60, 18],
[70, 80, 35]])
>>> c=[Link](3,4)
>>> c
array([[10, 20, 15, 30],
[40, 25, 50, 60],
[18, 70, 80, 35]])
>>> d=[Link](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():

Syntax1:- varname=[Link](Value)
Syntax2:- varname=[Link](Start,Stop)
Syntax3:- varname=[Link](Start,Stop,Step)
=>Here var name is an object of <class,ndarray>

=>Syntax-1 creates an object of ndarray with the values from 0 to value-1


=>Syntax-2 creates an object of ndarray with the values from Start to Stop-1
=>Syntax-3 creates an object of ndarray with the values from Start to Stop-1 with equal

352 manojalladi23@[Link]
Interval of Value ---- step
=>arange() always create an object of ndarray in 1-D array only but not Possible to create
directly 2-D and Multi Dimesional Arrays.
=>To create 2-D and Multi Dimesional Arrays, we must use reshape() or shape attribute

Examples:

>>> import numpy as np


>>> a=[Link](10)
>>> a ---------- array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> [Link] ------- 1
>>> a=[Link](50,62)
>>> print(a,type(a)) -- [50 51 52 53 54 55 56 57 58 59 60 61] <class '[Link]'>
>>> [Link] ----- 1
>>> a=[Link](10,23,2)
>>> a ---- array([10, 12, 14, 16, 18, 20, 22])
>>> a=[Link](10,22,2)
>>> a ------- array([10, 12, 14, 16, 18, 20])
>>> b=[Link](2,3)
>>> c=[Link](3,2)
>>> b-----
array([[10, 12, 14],
[16, 18, 20]])
>>> c
array([[10, 12],
[14, 16],
[18, 20]])
>>> [Link] ------ 2
>>> [Link] ------- 2
>>> [Link] ---- (2, 3)
>>> [Link] ----(3, 2)
>>> l1=[ [[10,20],[30,40]], [[15,25],[35,45]] ]
>>> l1 --------- [[[10, 20], [30, 40]], [[15, 25], [35, 45]]]
>>> a=[Link](l1) -------- TypeError: unsupported operand type(s) for -: 'list' and 'int'

3. zeros():

=>This Function is used for building ZERO matrix either with 1-D or 2-D or n-D
=>Syntax: varname=[Link](shape,dtype)

353 manojalladi23@[Link]
=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D( Number of
Matrices,Number of Rows, Number of Columns)

Examples:

>>> import numpy as np


>>> a=[Link](12)
>>> a ---------- array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> a=[Link](12,dtype=int)
>>> a ----------- array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> [Link](3,4)
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> [Link](4,3)
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> [Link](6,2)
array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]])
>>> [Link](2,6)
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
>>> [Link](2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])

>>> [Link](2,2,2,2) ----- ValueError: cannot reshape array of size 12 into shape (2,2,2,2)
>>> [Link](3,2,2)

354 manojalladi23@[Link]
array([[[0, 0],
[0, 0]],

[[0, 0],
[0, 0]],

[[0, 0],
[0, 0]]])
>>> [Link](2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],

[[0, 0],
[0, 0],
[0, 0]]])
>>> [Link](2,2,3)
array([[[0, 0, 0],
[0, 0, 0]],

[[0, 0, 0],
[0, 0, 0]]])

-
>>> import numpy as np
>>> a=[Link]((3,3),dtype=int)
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=[Link]((2,3))
>>> a
array([[0., 0., 0.],
[0., 0., 0.]])
>>> a=[Link]((2,3),int)
>>> a
array([[0, 0, 0],
[0, 0, 0]])
>>> a=[Link]((3,2,3),dtype=int)
>>> a
array([[[0, 0, 0],

355 manojalladi23@[Link]
[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 '[Link]'>

4. ones()

=>This Function is used for building ONEs matrix either with 1-D or 2-D or n-D
=>Syntax: varname=[Link](shape,dtype)

=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D( Number of


Matrices,Number of Rows, Number of Columns)

Examples:

>>> import numpy as np


>>> a=[Link](10)
>>> print(a,type(a)) ---------[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] <class '[Link]'>
>>> a=[Link](10,dtype=int)
>>> print(a,type(a)) ------------[1 1 1 1 1 1 1 1 1 1] <class '[Link]'>
>>> [Link] --------- (10,)
>>> [Link]=(5,2)
>>> a
array([[1, 1],
[1, 1],
[1, 1],
[1, 1],
[1, 1]])

356 manojalladi23@[Link]
>>> [Link]-------------- 2
>>> [Link] ----------- (5, 2)
>>> [Link]=(2,5)
>>> a
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
>>> [Link] (2, 5)
>>>
>>> a=[Link]((3,4),dtype=int)
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> a=[Link]((4,3),dtype=int)
>>> print(a,type(a))
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]] <class '[Link]'>
>>> [Link] -------- (4, 3)
>>> [Link]=(3,2,2)
>>> a
array([[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]]])
>>> a=[Link]((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]],

357 manojalladi23@[Link]
[[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 for building a matrix by specifying fill value either 1-D or 2-D or n-D
=>Syntax:-
varname=[Link](shape,fill_value,dtype)
=>varname is an obejct of <class, [Link]>
=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D( Number of
Matrices,Number of Rows, Number of Columns)
=>fill_value can be any number of programmer choice

Examples:

>>> a=[Link](3,1)
>>> a -------- array([1, 1, 1])
>>>print(type(a)) ------- <class,[Link]>
>>> a=[Link](3,9)
>>> a ----------- array([9, 9, 9])
>>> a=[Link](6,8)
>>> a ------------ array([8, 8, 8, 8, 8, 8])
>>> [Link]=(3,2)
>>> a
array([[8, 8],
[8, 8],
[8, 8]])
>>> a=[Link](6,9)
>>> a --------- array([9, 9, 9, 9, 9, 9])
>>> [Link](2,3)

358 manojalladi23@[Link]
array([[9, 9, 9],
[9, 9, 9]])
>>> a=[Link]((3,3),9)
>>> a
array([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])
>>> a=[Link]((2,3),6)
>>> a
array([[6, 6, 6],
[6, 6, 6]])
>>> [Link](3,2)
array([[6, 6],
[6, 6],
[6, 6]])
>>> a=[Link]((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=[Link](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 M values and prepared Square Unit
Matrix.
=>Here K reporesents Principle diagnol element. if k=0 then it always points principle diagnol
=>If k=-1,-2,-3...-n represents Bellow Principle diagnol elements.
=>If k=1,2,3. ... n represents Above Principle diagnol elements.

359 manojalladi23@[Link]
Examples:

>>> import numpy as np


>>> #varname=[Link](N,M=None,K=0,dtype
>>> a=[Link](3)
>>> print(a,type(a))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] <class '[Link]'>
>>> a=[Link](3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]] <class '[Link]'>
>>> a=[Link](3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class '[Link]'>
>>> a=[Link](4,3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]
[0 0 0]] <class '[Link]'>
>>> a=[Link](3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class '[Link]'>
>>> a=[Link](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 '[Link]'>
>>> a=[Link](3,4,k=-1,dtype=int)
>>> print(a,type(a))

360 manojalladi23@[Link]
[[0 0 0 0]
[1 0 0 0]
[0 1 0 0]] <class '[Link]'>
>>> a=[Link](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 '[Link]'>
>>> a=[Link](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 '[Link]'>
>>> a=[Link](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 '[Link]'>
>>> a=[Link](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 '[Link]'>
>>> a=[Link](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 '[Link]'>
>>> a=[Link](5,6,k=2,dtype=int)
>>> print(a,type(a))

361 manojalladi23@[Link]
[[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 '[Link]'>
>>> a=[Link](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 '[Link]'>

7) identity():

=>This function always bulid Identity or unit matrix


=>Syntax:- varname=[Link](N,dtype)
=>Here N represents Either we can take Rows or Columns and PVM takes as NXN Matrix
(Square Matrix--Unit or Identity)

Examples:

>>> import numpy as np


>>> a=[Link](3,dtype=int)
>>> print(a,type(a))-------------
[[1 0 0]
[0 1 0]
[0 0 1]] <class '[Link]'>
>>> a=[Link](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 '[Link]'>

362 manojalladi23@[Link]
Numpy—Arithmetic Operations
=>On the objects of ndaary,we can apply all types of Arithmetic Operators.
=>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 perfomed w.r.t Arithmetic Operators.

a) add():

Syntax:- varname=[Link](ndarrayobj1, ndarrayobj2)


=>This function is used for adding elements of ndarrayobj1, ndarrayobj2 and result can be
displayed

Examples:

>>> l1=[ [10,20],[30,40] ]


>>> l2=[[1,2],[3,4]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=[Link](a,b)
>>> c
array([[11, 22],
[33, 44]])

-
>>> x=[Link]([[1,2,3],[4,5,6]])
>>> x
array([[1, 2, 3],
363 manojalladi23@[Link]
[4, 5, 6]])
>>> y=[Link]([4,4,4])
>>> y
array([4, 4, 4])
>>> z=x+y
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> z=[Link](x,y)
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> k=[Link]([[2,3],[4,5]])
>>> k
array([[2, 3],
[4, 5]])
>>> kvr=[Link](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=[Link](l1)
>>> b=[Link](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]])

364 manojalladi23@[Link]
b)subtract()
Syntax:- varname=[Link](ndarrayobj1, ndarrayobj2)
=>This function is used for subtracting elements of ndarrayobj1, ndarrayobj2 and result can be
displayed

Examples:

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=[Link](a,b)
>>> c
array([[ 9, 18],
[27, 36]])

-
>>> d=a-b # we used operator - instead of subtract()
>>> d
array([[ 9, 18],
[27, 36]])

-
b) multiply():

Syntax:- varname=[Link](ndarrayobj1, ndarrayobj2)


=>This function is used for performing element-wise multiplication of ndarrayobj1, ndarrayobj2
and result can be displayed

Examples:
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[1, 2],
365 manojalladi23@[Link]
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> c=[Link](a,b)
>>> c
array([[ 5, 12],
[12, 12]])

-
>>> e=a*b # we used operator * instead of multiply()
>>> e
array([[ 5, 12],
[12, 12]])

-
c) dot() or matmul()
=>To perform Matrix Multiplication, we use dot()

Syntax:- varname=[Link](ndarrayobj1, ndarrayobj2)


varname=[Link](ndarrayobj1, ndarrayobj2)

=>This function is used for performing actual matrix multiplication of ndarrayobj1, ndarrayobj2
and result can be displayed
Examples:

>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> d=[Link](a,b)
>>> d
array([[13, 12],
[31, 30]])

366 manojalladi23@[Link]
(OR)

>>> d=[Link](a,b)
>>> d
array([[13, 12],
[31, 30]])

-
d) divide()

Syntax:- varname=[Link](ndarray1,ndarry2)
=>This function is used for performing element-wise division of ndarrayobj1, ndarrayobj2 and
result can be displayed

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=[Link](a,b)
>>> c
array([[10., 10.],
[10., 10.]])

-
>>> d=a/b # we used operator / instead of divide()
>>> d
array([[10., 10.],
[10., 10.]])

e) floor_divide()

Syntax:- varname=numpy.floor_divide(ndarray1,ndarry2)
=>This function is used for performing element-wise floor division of ndarrayobj1, ndarrayobj2
and result can be displayed
>>> l1=[[10,20],[30,40]]

367 manojalladi23@[Link]
>>> l2=[[1,2],[3,4]]
>>> a=[Link](l1)
>>> b=[Link](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]])

-
>>> d=a//b # we used operator // instead of floor_divide()
>>> d
array([[10, 10],
[10, 10]])

f) mod()

Syntax:- varname=[Link](ndarray1,ndarry2)
=>This function is used for performing element-wise modulo division of ndarrayobj1,
ndarrayobj2 and result can be displayed

-
Examples:

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=[Link](a,b)
>>> c

368 manojalladi23@[Link]
array([[0., 0.],
[0., 0.]])

-
=>We can also do with operator %
>>> e=a%b
>>> e
array([[0, 0],
[0, 0]], dtype=int32)

g) power():

Syntax:- varname=[Link](ndarray1,ndarry2)
=>This function is used for performing element-wise exponential of ndarrayobj1, ndarrayobj2
and result can be displayed

>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=[Link](l1)
>>> b=[Link](l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>>c=[Link](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)

369 manojalladi23@[Link]
Numpy---Advanced Indexing
==>If we want to access multiple elements, which are not in order (arbitrary elements) of 1D,2D
and N-D arrays we must use the concept of Advanced Indexing.
=>If we want access the elements based on some condition then we can't use basic indexing and
Basic Slicing Operations. To fullfill such type of requirements we must use advanced Indexing.

=>Accessing Multiple Arbitrary Elements ---1D :

=>Syntax:- ndarrayname [ 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=[Link](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=[Link](lst) # here lst converted into ndarray object
>>> print(indexes) -------- [0 2 7]
>>> print(a[indexes]) ------------ [10 30 80]
(OR)
>>> ind=[0,2,7] # prepare the list of indexes of arbitray elements(10,30,80) of ndarray and pass
to ndarray
>>> print(a[ind]) ----------- [10 30 80]

Examples:
Q1-->Access 20 30 80 10 10 30
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=[Link](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 Arbitrary Elements ---2D :

=>Syntax:- ndarrayobj[ [row indexes],[column indexes] ]

370 manojalladi23@[Link]
Examples:-

>>>import numpy as np
>>>mat=[Link]([ [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])

=>Accessing Multiple Arbitrary Elements ---3D :


Syntax:- ndarray[ [Indexes of 2Dmatrix],[row indexes],[column indexes] ]

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=[Link](l1)
>>>print(mat3d)
>>> print(mat3d)
[[[ 1 2 3 4]
[ 5 6 7 8]

371 manojalladi23@[Link]
[ 9 10 11 12]]

[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
>>> [Link]
3
>>> [Link]
(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=[Link](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]
array([ 1, 8, 13, 20])
>>> a[ [0,0,0,1,1,1],[0,1,2,0,1,2],[0,1,2,0,1,2] ]

372 manojalladi23@[Link]
array([ 1, 6, 11, 13, 18, 23])

-
a=[Link]([10,20,30,40,50,60,70,80,15,25,35,45,55,65,75,85])
print(a)

[Link]=(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---Basic Indexing

==>If we want to access Single element of 1D,2D and N-D arrays we must use the concept of
Basic Indexing.

=>Accessing Single Element 1D-Array :

=>Syntax:- ndarrayname [ Index ]

373 manojalladi23@[Link]
=>Here 'index' can be either either +ve or -ve indexing

Examples:

>>> a=[Link]([10,20,30,40,50,60])
>>> a
array([10, 20, 30, 40, 50, 60])
>>> a[0]
10
>>> a[3]
40

=>Accessing single Element of 2D :

=>Syntax:- ndarrayobj[ row index,column index]

Examples:-

>>>import numpy as np
>>> a=[Link]([10,20,30,40,50,60])
>>> b=[Link](2,3)
>>> b
array([[10, 20, 30],
[40, 50, 60]])
>>> b[0,0]
10
>>> b[0,1]
20
>>> b[1,2]
60

=>Accessing single Element of 3D :

Syntax:- ndarrayobj[ Index of matrix , row index , column index ]

Examples:

>>> a=[Link]([10,20,30,40,50,60,70,80])
>>> b=[Link](2,2,2)
>>> b

374 manojalladi23@[Link]
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---Indexing and Slicing Operations of 1D,2D and 3D array

1D Arrays Slicing:

Syntax:- 1dndrrayobj[begin:end:step]

Examples:

>>> a=[Link]([10,20,30,40,50,60,70])
>>> a ----------- array([10, 20, 30, 40, 50, 60, 70])
>>> a[::-1] ---------- array([70, 60, 50, 40, 30, 20, 10])
>>> a[::] ----------array([10, 20, 30, 40, 50, 60, 70])

2D Arrays Slicing:

Syntax:- ndrrayobj[i,j]
here 'i' represents Row Index
here 'j' represents Column Index

Syntax:- 2dndrrayobj[Row Index, Column Index]

Syntax:- 2dndrrayobj[begin:end:step, begin:end:step]

Examples:

>>> a=[Link]([[10,20,30],[40,50,60]])
>>> a
array([[10, 20, 30],
[40, 50, 60]])

375 manojalladi23@[Link]
>>> a[0,0]
10
>>> a[0:,0:1]
array([[10],
[40]])
>>> a[0:,1:2]
array([[20],
[50]])
>>> a[1:,:]
array([[40, 50, 60]])

3D Arrays Slicing

Syntax:- 3dndrrayobj[i,j,k]

here 'i' represents Which 2D matrix ( Matrix Number-->0 1 2 3 4 5 ...... )


here 'j' represents which Rows in that 2D matrix
here 'k' represents which Columns in that 2D matrix
(OR)
Syntax:- 3dndrrayobj[ Matrix Index, Row Index, Column Index ]
(OR)
Syntax:- 3dndrrayobj[begin:end:step, begin:end:step, begin:end:step ]

Examples:

>>> 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=[Link](lst)
>>> print(arr2)
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]

[[13 14 15]
[16 17 18]
[19 20 21]]]
>>> [Link]
3

376 manojalladi23@[Link]
>>> [Link]
(2, 3, 3)
>>> arr2[:,:,0:1]
array([[[ 1],
[ 4],
[ 7]],

[[13],
[16],
[19]]])
>>> arr2[:,:,:1]
array([[[ 1],
[ 4],
[ 7]],

[[13],
[16],
[19]]])
>>> arr2[: , 0:2, 1:3]
array([[[ 2, 3],
[ 5, 6]],

[[14, 15],
[17, 18]]])
>>> arr2[: , :2, 1:]
array([[[ 2, 3],
[ 5, 6]],

[[14, 15],
[17, 18]]])

377 manojalladi23@[Link]
Numpy—Statistical Operations

=>On the object of ndarray,we can the following Statistical Operations.


a) amax()
b) amin()
c) mean()
d) median()
e) var()
f) std()
=>These operation we can perform on the entire matrix and we can also peform on columnwise
(axis=0) and Rowwise (axis=1)

a) amax():

=>This functions obtains maximum element of the entire matrix.


=>Syntax1:- varname=[Link](ndarrayobject)

=>Syntax2:- varname=[Link](ndarrayobject,axis=0)--->obtains max

elements on the basis columns.

=>Syntax3:- varname=[Link](ndarrayobject,axis=1)--->obtains max

elements on the basis Rows.

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=[Link](l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> max=[Link](A)
>>> cmax=[Link](A,axis=0)
>>> rmax=[Link](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]

378 manojalladi23@[Link]
b) amin()
=>This functions obtains minmum element of the entire matrix.
=>Syntax1:- varname=[Link](ndarrayobject)

=>Syntax2:- varname=[Link](ndarrayobject,axis=0)--->obtains min


elements on the basis columns.

=>Syntax3:- varname=[Link](ndarrayobject,axis=1)--->obtains min


elements on the basis Rows.
Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=[Link](l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> min=[Link](A)
>>> cmin=[Link](A,axis=0)
>>> rmin=[Link](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]

b) mean():

=>This is used for cal mean of the total matrix elements.


=>The formula for mean=(sum of all elements of matrix) / total number of elements.
Syntax1:- varname=[Link](ndarrayobject)
Syntax2:- varname=[Link](ndarrayobject,axis=0)--->Columnwise Mean
Syntax3:- varname=[Link](ndarrayobject,axis=1)--->Rowwise Mean

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=[Link](l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> m=[Link](A)
379 manojalladi23@[Link]
>>> cm=[Link](A,axis=0)
>>> rm=[Link](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. ]

c) median()

=>This is used for calculating / obtaining median of entire matrix elements.


=>Median is nothing but sorting the given data in ascending order and select middle element.
=>If the number sorted elements are odd then center or middle element becomes median.
=>If the number sorted elements are even then select center or middle of two elements, add
them and divided by 2 and that result becomes median.

Syntax1:- varname=[Link](ndarrayobject)

Syntax2:- varname=[Link](ndarrayobject,axis=0)

Syntax3:- varname=[Link](ndarrayobject,axis=1)

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=[Link](l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> md=[Link](A)
>>> cmd=[Link](A,axis=0)
>>> rmd=[Link](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=[Link](l1)
>>> print(A)
[[2 3]
[4 1]]
>>> md=[Link](A)
380 manojalladi23@[Link]
>>> cmd=[Link](A,axis=0)
>>> rmd=[Link](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]

d) var():

Variance= sqr(mean-xi) / total number of elements


here 'xi' represents each element of matrix.

Syntax1:- varname=[Link](ndarrayobject)

Syntax2:- varname=[Link](ndarrayobject,axis=0)

Syntax3:- varname=[Link](ndarrayobject,axis=1)

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=[Link](l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=[Link](A)
>>> cvr=[Link](A,axis=0)
>>> rvr=[Link](A,axis=1)
>>> print("Variance=",vr) ----- ariance= 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]

e) std()

standard deviation=sqrt(var)

Syntax1:- varname=[Link](ndarrayobject)

381 manojalladi23@[Link]
Syntax2:- varname=[Link](ndarrayobject,axis=0)

Syntax3:- varname=[Link](ndarrayobject,axis=1)

Examples:

>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=[Link](l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=[Link](A)
>>> cvr=[Link](A,axis=0)
>>> rvr=[Link](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]

-
>>> sd=[Link](A)
>>> csd=[Link](A,axis=0)
>>> rsd=[Link](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]

NOTE:

>>> import statistics


>>> l=[10,20,10,30,40,10,50,10]
>>> [Link](l)
10
>>> l=[10,20,10,30,40,10,50,10,20,20,20]
>>> [Link](l)
10
>>> l=[20,10,10,30,40,10,50,10,20,20,20]
>>> [Link](l)

382 manojalladi23@[Link]
20
>>> [Link](l)
[20, 10]
>>> l=[20,10,10,30,40,10,50,10,20,20,20,10]
>>> [Link](l)
[10]
>>>
NumPy Array Copy vs View

=>The Difference Between Copy and View

=>The main difference between a copy and a view of an array is that the copy is a new array, and
the view is just a view of the original array.
=>The copy owns the data and any changes made to the copy will not affect original array, and
any changes made to the original array will not affect the copy. modfifications are Independent (
Like Shallow Copy)

=>Syntax:- varname=[Link]()
(OR)
ndarrayobj2=[Link](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=[Link]()

COPY:

Example

# Make a copy, change the original array, and display both arrays:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
x = [Link]()
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.

383 manojalladi23@[Link]
VIEW:
Example

#Make a view, change the original array, and display both arrays:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
x = [Link]()
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.

# Make Changes in the VIEW:

Example

# Make a view, change the view, and display both arrays:


import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
x = [Link]()
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

NumPy Sorting Arrays

=>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 alphabetical, ascending or descending.
=>The NumPy ndarray object has a function called sort(), that will sort a specified array.

Examples:

import numpy as np
arr = [Link]([3, 2, 0, 1])

print([Link](arr))#[0 1 2 3 ]
--------------------------------------

384 manojalladi23@[Link]
import numpy as np
arr = [Link](['banana', 'cherry', 'apple'])
print([Link](arr)) # ['apple' 'banana' 'cherry']

import numpy as np
arr = [Link]([True, False, True])
print([Link](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.

Examples:

import numpy as np
arr = [Link]([[3, 2, 4], [5, 0, 1]])
print([Link](arr))
#output
[[2 3 4]
[0 1 5]]

-
a=[Link]([110, 20, -30, 40, 50, 160, 7, 8, 90])
print(a)

[Link](a)-----------array([-30, 7, 8, 20, 40, 50, 90, 110, 160])


[Link](a)[::-1]-----array([160, 110, 90, 50, 40, 20, 8, 7, -30])
[Link]=(3,3)
a array([[110, 20, -30],
[ 40, 50, 160],
[ 7, 8, 90]])

[Link](a,axis=0) # ColumnWise
array([[ 7, 8, -30],
[ 40, 20, 90],
[110, 50, 160]])

print(a)
array([[110, 20, -30],

385 manojalladi23@[Link]
[ 40, 50, 160],
[ 7, 8, 90]])

[Link](a,axis=1) # Row Wise


array([[-30, 20, 110],
[ 40, 50, 160],
[ 7, 8, 90]])

Numpy--selecting the elements based on condition


(OR)
Creating Filter Directly From ndArray

=>To select any element from ndarray object, we have two approaches. They are

Approach-1:

satisfied and False represents Condition not satisfied]

Syntax:- varname=ndarrayobject with condition

varname is called boolean array.

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

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

386 manojalladi23@[Link]
>>> import numpy as np
>>> l=[10,21,-34,23,-45,30,-40]
>>> print(l) ------------- [10, 21, -34, 23, -45, 30, -40]
>>> a=[Link](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=[Link](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=[Link]([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])

-
>>> a=[Link]([10,20,30,40,50,60,70,80,90])
>>> b=[Link](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],

387 manojalladi23@[Link]
[False, False, True]])
>>> b[m3] ------------------------- array([30, 60, 90])
======================OR===========================
>>> b[b%3==0] ------------------ array([30, 60, 90])

Series

=>It is a One-Dimensional Labelled Array Capable of Storing / Holding Homogeneous data of


any type (Integer, String, float,.........Python objects etc).
=>The Axis Labels are collectively called Index.
=>Pandas Series is nothing but a column value in excel sheet.
=>Pandas Series Values are Mutable.
=>Pandas Series contains Homogeneous Data ( Internally even we store different types values ,
They are treated as object type)

Creating a Series

=>A Series object can be created by using the folowing Syntax:


Syntax:-

varname=[Link](object, index, dtype)

Explanation:-

=>Here varname is an object of <class, [Link] >


=>pandas is module name
=>Series() is pre-defined Function in pandas module and it is used for creating an object of
Series class.
=>'object' can either int, float, complex, bool, str, bytes, bytearray,range, list,ndarray,dict ..... etc
(But not set type bcoz they are un-ordered)
=>'index' represents the position of values present Series object. The default value of Index
starts from 0 to n-1, Here n represents number of values in Series object. Programatically we can
give our own Index Values.
=>'dtype' represents data type (Ex:- int32, ,int64, float32, float64. etc)

-
Examples:- Create a series for 10 20 30 40 50 60

>>> import pandas as pd

388 manojalladi23@[Link]
>>> import numpy as np
>>> lst=[10,20,30,40,50,60]
>>> s=[Link](lst)
>>> print(s,type(s))
0 10
1 20
2 30
3 40
4 50
5 60
dtype: int64 <class '[Link]'>

-
>>> lst=[10,20,30,40,50,60]
>>> s=[Link](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 '[Link]'>

-
>>> lst=["Rossum","Gosling","Travis","MCKinney"]
>>> a=[Link](lst)
>>> a ------ array(['Rossum', 'Gosling', 'Travis', 'MCKinney'], dtype='<U8')
>>> print(a, type(a))--['Rossum' 'Gosling' 'Travis' 'MCKinney'] <class '[Link]'>
>>> s=[Link](a)
>>> print(s,type(s))
0 Rossum
1 Gosling
2 Travis
3 MCKinney
dtype: object <class '[Link]'>

-
>>>lst=[10,"Rossum",34.56,"Author"]
>>> s=[Link](lst)
>>> print(s,type(s))

389 manojalladi23@[Link]
0 10
1 Rossum
2 34.56
3 Author
dtype: object <class '[Link]'>

Creating an Series object with Programmer-defined Index

>>> lst=[10,"Rossum",34.56,"Author"]
>>> print(lst) ------- [10, 'Rossum', 34.56, 'Author']
>>> s=[Link](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=[Link](lst,index=[100,200,300,400])
>>> print(s,type(s))
100 Rossum
200 Gosling
300 Travis
400 MCKinney
dtype: object <class '[Link]'>

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 Indices (Or Indexes)
automatically and corresponding values of dict 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=[Link](d1)

390 manojalladi23@[Link]
>>> 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=[Link](d2)
>>> print(s)
RS 2.3
JG 1.2
MCK 4.5
TOLI 2.4
dtype: float64

DataFrame in Pandas

=>A DataFrame is 2-Dimensional Data Structure to organize the data .


=>In Otherwords a DataFrame Organizes the data in the Tabular Format, which is
nothing but Collection of Rows and Columns.
=>The Columns of DataFrame can be Different Data Types or Same Type
=>The Size of DataFrame can be mutable.

================================================
Number of approaches to create DataFrame
================================================
=>To create an object of DataFrame, we use pre-defined DataFrame() which is present in pandas
Module and returns an object of DataFrame class.
=>We have 5 Ways to create an object of DataFrame. They are
a) By using list / tuple
b) By using dict
c) By using Series
d) By using ndarray of numpy
e) By using CSV File (Comma Separated Values)

=>Syntax for creating an object of DataFrame in pandas:

varname=[Link](object,index,columns,dtype)

391 manojalladi23@[Link]
Explanation:
=>'varname' is an object of <class,'[Link]'>
=>'[Link]()' is a pre-defined function present in pandas module and it is used to
create an object of DataFrame for storing Data sets.
=>'object' represents list (or) tuple (or) dict (or) Series (or) ndarray (or) CSV file
=>'index' represents Row index and whose default indexing starts from 0,1,...n-1
where 'n' represents number of values in DataFrame object.
=>'columns' represents Column index whose default indexing starts from 0,1..n-1
where n number of columns.
=>'dtype' represents data type of values of Column Value.

Creating an object DataFrame by Using list / tuple

>>>import pandas as pd
>>>lst=[10,20,30,40]
>>>df=[Link](lst)
>>>print(df)
0
0 10
1 20
2 30
3 40

lst=[[10,20,30,40],["RS","JS","MCK","TRV"]]
df=[Link](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=[Link](lst)
print(df)
0 1
0 10 RS
1 20 JG
2 30 MCK
3 40 TRA

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

392 manojalladi23@[Link]
lst=[[10,'RS'],[20,'JG'],[30,'MCK'],[40,'TRA']]
df=[Link](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=[Link](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

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=[Link](dictdata)
>>> print(df)
Names Subjects Ages
0 Rossum Python 65
1 Gosling Java 80
2 Ritche C 85
3 McKinney Pandas 55
>>> df=[Link](dictdata,index=[1,2,3,4])

393 manojalladi23@[Link]
>>> print(df)
Names Subjects Ages
1 Rossum Python 65
2 Gosling Java 80
3 Ritche C 85
4 McKinney Pandas 55

Creating an object DataFrame by Using Series object

>>> import pandas as pd


>>> sdata=[Link]([10,20,30,40])
>>> df=[Link](sdata)
>>> print(df)
0
0 10
1 20
2 30
3 40
>>> sdata=[Link]({"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=[Link](sdata)
>>> print(df)
0
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
>>> ddata={"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]}
>>> df=[Link](ddata)
>>> print(df)
IntMarks ExtMarks
0 10 80
1 20 75
2 30 65
3 40 50

394 manojalladi23@[Link]
-------------------------------------------------------------------------
Creating an Object DataFrame by Using ndarray object

>>> import numpy as np


>>> l1=[[10,60],[20,70],[40,50]]
>>> a=[Link](l1)
>>> df=[Link](a)
>>> print(df)
0 1
0 10 60
1 20 70
2 40 50
>>> df=[Link](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("D:\KVR-JAVA\[Link]")
print("type of df=",type(df)) #type of df= <class '[Link]'>
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

Accesssing the Data of DataFrame

1) [Link]([Link] rows)
2) [Link]([Link] rows)
3) [Link]()
4) [Link]

395 manojalladi23@[Link]
5) DataFrameobj [start:stop:step]
6) DataFrameobj["Col Name"]
7) DataFrameobj[ ["Col Name1","Col Name-2" ... "Col Name-n"] ]
8) DataFrameobj[ ["Col Name1","Col Name-2" ... "Col Name-n"]] [start:stop:step]
9) [Link]()

Understabding loc() ----- here start and stop index Included and
Col Names can be used(but not column numbers]

1) [Link][row_number]
2) [Link][row_number,[Col Name, ........ ] ]
3) [Link][start:stop:step]
4) [Link][start:stop:step,["Col Name"] ]
5) [Link][start:stop:step,["Col Name1", Col Name-2. ..... "] ]
6) [Link][start:stop:step,"Col Name1" : Col Name-n"]

Understabding iloc() ----- here start index included and stop index excluded and
Col Numbers must be used(but not column names]

1) [Link][row_number]
2) [Link][row_number,Col Number ........ ]
3) [Link][row_number,[Col Number1,Col Number2. .......... ] ]
3) [Link][row start:row stop, Col Start: Col stop]
4) [Link][row start:row stop:step, Col Start: Col stop:step]
5) [Link][row start:row stop,Col Number ]
6) [Link][ [row number1, row number-2. ... ] ]
7) [Link][ row start: row stop , [Col Number1,Col Number2. .......... ] ]
8) [Link][ : , [Col Number1,Col Number2. ..........] ]

Adding Column Name to Data Frame

1) dataframeobj['new col name']=default value


2) dataframeobj['new col name']=expression

Removing Column Name from Data Frame

1)[Link](columns="col name")
2)[Link](columns="col name",inplace=True)

396 manojalladi23@[Link]
Sorting the dataframe data

1) dataframeobj.sort_values(["colname"])
2) dataframeobj.sort_values(["colname"],ascending=False)
3) dataframeobj.sort_values(["colname1","col name2",...col name-n] )

knowing duplicates in dataframe data

1) [Link]() -------------- gives boolean result

Removing duplicates from dataframe data

1) dataframeobj.drop_duplicates()
2) dataframeobj.drop_duplicates(inplace=True)

Data Filtering and Conditional Change / updations

1) [Link][ simple condition]

Ex: [Link][ df["maths"]>75 ]


[Link][df["maths"]>90 ,["name","maths"]]

2) [Link][ compound condition]


Ex: [Link][ (df["maths"]>60) & (df["maths]<85) ]
Ex: [Link][ (df["maths"]>95) &(df["maths"]<=99),["name","maths"] ]

3) [Link][ (compund condition), ["Col Name"] ]=Expression

Ex: [Link][ (df["percent"]>=60) & (df["percent"]<=80),["grade"] ]="First" # cond updattion.

DataFrame--GroupBy

=>The Group By mechanism in the Pandas provides a way to break a DataFrame into different
groups or chunks based on the values of single or multiple columns.
=>Let’s understand with some examples.

397 manojalladi23@[Link]
=>Assume we have a DataFrame,

ID Name Age City Experience

11 Jack 44 Sydney 19
12 Riti 41 Delhi 17
13 Aadi 46 Mumbai 11
14 Mohit 45 Delhi 15
15 Veena 43 Delhi 14
16 Shaunak 42 Mumbai 17
17 Manik 42 Sydney 14
18 Vikas 42 Delhi 11
19 Samir 42 Mumbai 15
20 Shobhit 40 Sydney 12

=>This DataFrame has a column ‘City’ which has three unique values like, “Delhi”, “Mumbai”
and “Sydney”. We want to create different groups out of this DataFrame based on the column
“City” values.
=>As this column has only three unique values, so there will be three different groups.
=>Group 1 will contain all the rows for which column “City” has the value “Delhi” i.e.

ID Name Age City Experience

12 Riti 41 Delhi 17
14 Mohit 45 Delhi 15
15 Veena 43 Delhi 14
18 Vikas 42 Delhi 11

Group 2 will contain all the rows for which column “City” has the value “Mumbai” i.e.

ID Name Age City Experience

13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15

Group 3 will contain all the rows for which column “City” has the value “Sydney” i.e.

398 manojalladi23@[Link]
ID Name age city Experience
11 Jack 44 Sydney 19
17 Manik 42 Sydney 14
20 Shobhit 40 Sydney 12

=>The groupby() method of DataFrame, gives us an iterable object of group Name and contents.
We can also select individual groups too. It also provides a way to group large amounts of data
and compute operations on these groups. For example, by using the GroupBy mechanism for the
above DataFrame, we can get the,

Mean Experience of employees for each Group.


Mean Age of employees for each Group.
Maximum Experience of an employee for each Group.
Minimum Experience of an employee for each Group.
Maximum Age of an employee for each Group.
Minimum Age of an employee for each Group.
and many more things….

[Link]() method

DataFrame’s groupby() method accepts column names as arguments. Based on the column
values, it creates several groups and returns a DataFrameGroupBy object that contains
information about these groups.

For example, let’s create groups based on the column “City”,

# Create Groups based on values in column 'city'


groupObj = [Link]('City')
print(groupObj)

Output

<[Link] object at 0x000002895CA14048>

The groupby() function created three groups because column ‘City’ has three unique values. It
returned a DataFrameGroupBy object with information regarding all three groups.

399 manojalladi23@[Link]
Iterate over all the DataFrame Groups
DataFrame’s groupby() function returns a DataFrameGroupBy object, which contains the
information of all the groups. The DataFrameGroupBy is an iterable object. It means using a for
loop, we can iterate over all the created Groups,

# Iterate over all the groups


for grpName, rows in [Link]('City'):

print("Group Name: ", grpName)


print('Group Content: ')
print(rows)

Output:

Group Name: Delhi


Group Content:

ID Name Age City Experience

12 Riti 41 Delhi 17
14 Mohit 45 Delhi 15
15 Veena 43 Delhi 14
18 Vikas 42 Delhi 11
Group Name: Mumbai
Group Content:

ID Name Age City Experience

13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15
Group Name: Sydney
Group Content:

ID Name Age City Experience

11 Jack 44 Sydney 19
17 Manik 42 Sydney 14
20 Shobhit 40 Sydney 12

=>We iterated over the DataFrameGroupBy object using a for loop. For each of the groups, it
400 manojalladi23@[Link]
returns a tuple. This tuple contains the group Name and a DataFrame containing the rows in that
Group.
=>In our example, the group names were the unique values of “City” Column i.e. “Delhi”,
“Mumbai” and “Sydney”. So, basically, a group was created for each city, and the group name is
the corresponding city name.

Get first row of each Group

=>DataFrame’s groupby() function returns a DataFrameGroupBy object, which contains the


information of all the groups. The DataFrameGroupBy object also provides a function first(), and
it returns a DataFrame containing the first row of each of the Group.
=>The [Link]().nth() function is used to get the value corresponding the nth row for
each group. To get the first value in a group, pass 0 as an argument to the nth() function.

For example

# Get first row of each group


firstRowDf = [Link]('City').first()
print(firstRowDf)

Output:

City Name Age Experience

Delhi Riti 41 17
Mumbai Aadi 46 11
Sydney Jack 44 19
There were three unique values in the column “City”, therefore 3 groups were created. The first()
function fetched the first row of each of the Group and returned a DataFrame populated with
that. The returned DataFrame has a row for each of the city and it is the first row from each of
the city groups.

Get the count of number of DataFrame Groups

The DataFrameGroupBy object also provides a function size(), and it returns the count of rows in
each of the groups created by the groupby() function. For example,

# Get the size of DataFrame groups


print([Link]('City').size())

401 manojalladi23@[Link]
Output:

Delhi 4
Mumbai 3
Sydney 3
dtype: int64
As there were three unique values in the column “City”, therefore 3 groups were created by
groupby() function. The size() function returned a Series containing the count of number of rows
for each of the group.

Get a specific DataFrame Group by the group name

DataFrame’s groupby() function returns a DataFrameGroupBy object, which contains the


information of all the groups. The DataFrameGroupBy object also provides a function
get_group(). It accepts a group name as an argument and returns a DataFrame containing only
rows for that group. For example, for our DataFrame, the groupby(“City”) function created three
objects and returned a DataFrameGroupBy object. The group names were the unique values in
column “City” i.e. “Delhi”, “Mumbai” and “Sydney”. So, let’s select the rows of Group named
“Mumbai”,

# Get a specific group by the group name


specificGroup = [Link]('City').get_group('Mumbai')
print(specificGroup)

Output:

ID Name Age City Experience

13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15

It returned a DataFrame containing all the rows for “Mumbai” group.

Statistical operations on the DataFrame GroupBy object

DataFrame’s groupby() function returns a DataFrameGroupBy object, which contains the


information of all the groups. The DataFrameGroupBy object also provides a function mean(). It
returns the mean values of all numeric columns for each Group. For example,

402 manojalladi23@[Link]
# Get the mean of all numeric columns in each of the group
meanValues = [Link]('City').mean()
print(meanValues)

Output:

City Age Experience

Delhi 42.750000 14.250000
Mumbai 43.333333 14.333333
Sydney 42.000000 15.000000
Our DataFrame has two numeric columns ‘Age’ and ‘Experience’. The mean() function
calculated the mean values for these columns in each of the groups and returned a DataFrame.
Basically, this DataFrame contains the mean of employees’ age and Experience of employees in
each of the three cities.

If we are interested in mean values of a single column only, then we can first select the column
and later call the mean() function. For example,

# Get the mean Age of employees


# in each of the three cities
meanAge = [Link]('City')['Age'].mean()
print(meanAge)

Output:

City
Delhi 42.750000
Mumbai 43.333333
Sydney 42.000000
Name: Age, dtype: float64
It returned the mean Age of employees in each of the three cities. Apart from mean() function,
the DataFrameGroupBy object also provides many other functions for aggregations.

Get the count of number of DataFrame Groups

The DataFrameGroupBy object also provides a function size(), and it returns the count of rows in
each of the groups created by the groupby() function. For example,

403 manojalladi23@[Link]
# Get the size of DataFrame groups
print([Link]('City').size())

Output:

Delhi 4
Mumbai 3
Sydney 3
dtype: int64

As there were three unique values in the column “City”, therefore 3 groups were created by
groupby() function. The size() function returned a Series containing the count of number of rows
for each of the group.

Get a specific DataFrame Group by the group name

DataFrame’s groupby() function returns a DataFrameGroupBy object, which contains the


information of all the groups. The DataFrameGroupBy object also provides a function
get_group(). It accepts a group name as an argument and returns a DataFrame containing only
rows for that group. For example, for our DataFrame, the groupby(“City”) function created three
objects and returned a DataFrameGroupBy object. The group names were the unique values in
column “City” i.e. “Delhi”, “Mumbai” and “Sydney”. So, let’s select the rows of Group named
“Mumbai”,

# Get a specific group by the group name


specificGroup = [Link]('City').get_group('Mumbai')
print(specificGroup)

Output:

ID Name Age City Experience

13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15
It returned a DataFrame containing all the rows for “Mumbai” group.

Statistical operations on the DataFrame GroupBy object

DataFrame’s groupby() function returns a DataFrameGroupBy object, which contains the

404 manojalladi23@[Link]
information of all the groups. The DataFrameGroupBy object also provides a function mean(). It
returns the mean values of all numeric columns for each Group. For example,

# Get the mean of all numeric columns in each of the group


meanValues = [Link]('City').mean()
print(meanValues)

Output:

City Age Experience

Delhi 42.750000 14.250000
Mumbai 43.333333 14.333333
Sydney 42.000000 15.000000

Our DataFrame has two numeric columns ‘Age’ and ‘Experience’. The mean() function
calculated the mean values for these columns in each of the groups and returned a DataFrame.
Basically, this DataFrame contains the mean of employees’ age and Experience of employees in
each of the three cities.

If we are interested in mean values of a single column only, then we can first select the column
and later call the mean() function. For example,

# Get the mean Age of employees


# in each of the three cities
meanAge = [Link]('City')['Age'].mean()
print(meanAge)
.
Output:

City
Delhi 42.750000
Mumbai 43.333333
Sydney 42.000000
Name: Age, dtype: float64
It returned the mean Age of employees in each of the three cities. Apart from mean() function,
the DataFrameGroupBy object also provides many other functions for aggregations.

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

405 manojalladi23@[Link]
import pandas as pd
# List of Tuples
empoyees = [
(11, 'Jack', 44, 'Sydney',19) ,
(12, 'Riti', 41, 'Delhi' , 17) ,
(13, 'Aadi', 46, 'Mumbai', 11) ,
(14, 'Mohit', 45, 'Delhi' , 15) ,
(15, 'Veena', 43, 'Delhi' , 14) ,
(16, 'Shaunak', 42, 'Mumbai', 17 ),
(17, 'Manik', 42, 'Sydney', 14 ),
(18, 'Vikas', 42, 'Delhi', 11 ),
(19, 'Samir', 42, 'Mumbai', 15 ),
(20, 'Shobhit', 40, 'Sydney', 12) ]
# Create a DataFrame object
df = [Link](empoyees,
columns=['ID', 'Name', 'Age', 'City', 'Experience'])
df = df.set_index('ID')
# Display the DataFrame
print(df)
print("-"*40)
groupObj = [Link]('City')
for grpName, rows in groupObj:
print("Group Name: ", grpName)
print('Group Content: ')
print(rows)
print(" ")
firstRowDf = [Link]('City').first()
print(firstRowDf)
print(" ")
firstRowDf = [Link]('City').nth(1)
print(firstRowDf)
print(" ")
print([Link]('City').size())
print(" ")
specificGroup = [Link]('City').get_group('Mumbai')
print(specificGroup)
print(" ")
meanValues = [Link]('City').mean()

406 manojalladi23@[Link]
print(meanValues)
print(" ")
meanAge = [Link]('City')['Age'].mean()
print(meanAge)

String Handling in Python(part-2)

=>We know that a String is a collection / sequence of Characters enclosed within single / double
Quotes (or) triple single / double Quotes.
=>String data is of type <class,'str'>
=>To do various opereations on String data, we have to use the following the functions.
1) capitalize():

=>This function is used for capitalizing the given str data


=>Syntax: varname=[Link]()

Examples:

>>> s="python is an oop lang"


>>> print(s,type(s)) -------- python is an oop lang <class 'str'>
>>> cs=[Link]()
>>> print(cs,type(cs)) ---- Python is an oop lang <class 'str'>
>>> print(s,type(s)) ------- python is an oop lang <class 'str'>

2) title():

=>This Function is used for getting all words First Characters as capital.
=>Syntax:- varname=[Link]()

Examples:

>>> s="python is an oop lang"


>>> ts=[Link]()
>>> print(ts,type(ts)) ------- Python Is An Oop Lang <class 'str'>
>>> print(s,type(s)) python is an oop lang <class 'str'

407 manojalladi23@[Link]
3) find():

=>This function is used for finding an index of the first occurance of specified str data in the
given str data.
=>If the data found then it returns Its +ve index value
=>If the data not found then it returns -1

Syntax:- varname=[Link](str data)

Examples:

>>> s="python is an oop lang"


>>> print(s,type(s))
python is an oop lang <class 'str'>
>>> ind=[Link]("python")
>>> print(ind) ----- 0
>>> ind=[Link]("n")
>>> print(ind) ----- 5
>>> ind=[Link]("k")
>>> print(ind) ----------- 1
>>> ind=[Link]("o")
>>> print(ind) ------ 4

Examples:

>>> s="apple is red"


>>> [Link]("p")
1
>>> enumerate(s)
<enumerate object at 0x00000129EDF7D4C0>
>>> for i,l in enumerate(s):
... print(i,l)
...
0a
1p
2p
3l
4e

408 manojalladi23@[Link]
5
6i
7s
8
9r
10 e
11 d
>>> for i,l in enumerate(s):
... print("{} found at {} Index".format(l,i))
...
a found at 0 Index
p found at 1 Index
p found at 2 Index
l found at 3 Index
e found at 4 Index
found at 5 Index
i found at 6 Index
s found at 7 Index
found at 8 Index
r found at 9 Index
e found at 10 Index
d found at 11 Index
>>>

Examples:

#[Link]
line=input("Enter a line of text:")
print("Given Data={}".format(line))
for ch in line:
print("\tCharacter: {} Index={}".format(ch,[Link](ch)))

#[Link]
line=input("Enter line of text:") # Python
i=0
for ch in line:
print("Character :{}--->Index:{} and orginal Index={}".format( ch, [Link](ch),i ))
i=i+1

409 manojalladi23@[Link]
4) isalnum():
=>This Function returns True Provided str data contains "Alphabets with digits or only with
digits or only with alphabets"
=>This Function returns False Provided str data is a combination of "Alphabets and numbers
with any special Symbols"

Syntax:- varname=[Link]()
(or)
[Link]()

Examples:

>>> s="12345"
>>> b=[Link]()
>>> print(b) ----------- True
>>> s="python12345"
>>> [Link]() --------- True
>>> s="python12345#"
>>> [Link]() -------- False
>>> s="python 12345"
>>> [Link]() --------- False
>>> s="Python is an oop lang"
>>> [Link]() ---------- False
>>> s="python"
>>> [Link]() ------- True
>>>s="-123"
>>> [Link]() ---------- False

4) isalpha():

=>This Function returns True provided str data contains only Alphabets otherwise it returns
False.

=>Syntax:- varname=[Link]()

Examples:

>>> s="Python"
>>> b=[Link]()

410 manojalladi23@[Link]
>>> print(b) ----------- True
>>> s="1234"
>>> print([Link]())--------False
>>> s="python1234"
>>> print([Link]())-------False
>>> s="python_1234"
>>> print([Link]())-------False

5) isdigit():

=>This Function returns True provided str data contains only purly digits(0-9) otherwise it
returns False.
Syntax:- varname=[Link]()
or
[Link]()

Examples:

>>> a="1234"
>>> print([Link]()) -----------True
>>> a="pyth1234"
>>> print([Link]()) ------- False
>>> a="python"
>>> print([Link]()) ----- False
>>> a="pyth#$123"
>>> print([Link]()) -------- False

6) islower() :

=>This Function returns True provided the str data is completely available in lowercase
otherwise it returns False.

Syntax:- varname=[Link]()
or
[Link]()
Examples:

>>> s="python"

411 manojalladi23@[Link]
>>> print([Link]()) --------- True
>>> s="Python"
>>> print([Link]()) -------- False
>>> s="python is an oop lang"
>>> print([Link]()) --- True
>>> s="python is An oop lang"
>>> print([Link]()) ------ False

7) isupper() :

=>This Function returns True provided the str data is completely available in upper case
otherwise it returns False.

Syntax:- varname=[Link]()
or
[Link]()

Examples:

>>> s="Python"
>>> print([Link]()) --------- False
>>> s="PYTHON"
>>> print([Link]()) ------ True
>>> s="python is an oop lang"
>>> print([Link]()) -------- False
>>> s="PYTHON IS AN OOP LANG"
>>> print([Link]()) ------ True

8) isspace()

=>This Function returns True provided str data contains purely space(s) otherwise it returns
False.
=>Syntax:- varname=[Link]()
(or)
[Link]()

412 manojalladi23@[Link]
Examples:

>>> s="Python is an oop"


>>> print([Link]()) ------- False
>>> s=" "
>>> print([Link]()) -------True
>>> s=" "
>>> print([Link]()) -------True
>>> s="123 345"
>>> print([Link]()) -- False
>>> s="" # empty string
>>> [Link]() ---------- False

9) upper():

=>This Function is used for converting lower case data into upper case data.
Syntax:- varname=[Link]()

10) lower():

=>This Function is used for converting upper case data into lower case data.
Syntax:- varname=[Link]()

Examples:
>>> s="python is an oop lang"
>>> uc=[Link]()
>>> print(uc) ------ PYTHON IS AN OOP LANG
>>> print(s)------ python is an oop lang
>>> print(uc) ---- PYTHON IS AN OOP LANG
>>> lc=[Link]()
>>> print(lc) -------- python is an oop lang

11) join():

=>This Function is used concatinating all the sequence of values which are available in the form
str
Syntax:- varname=[Link](iterable obj)
=>Here iterable obj contains multiple values in the form of str

413 manojalladi23@[Link]
Examples-:
>>>tpl=('java', 'python', 'Data Science')
>>> print(tpl, type(tpl))--('java', 'python', 'Data Science') <class 'tuple'>
>>> s2=""
>>> s3=[Link](tpl)
>>> print(s3) --- >javapythonData Science

>>> lst=["Apple","Mango","Kiwi","Guava"]
>>> frs=""
>>> frs=[Link](lst)
>>> print(frs) ------------------ AppleMangoKiwiGuava
>>> lst=["Apple","Mango","Kiwi","Guava"]
>>> frs=" "
>>> frs=[Link](lst)
>>> print(frs) ------------- Apple Mango Kiwi Guava

12) split():

=>This function is used for splitting the given str data into different tokens based spitting value.
The default splitting value is space
=>This Function returns splitting values in the form of list.

Syntax:- listobj=[Link]()

listobj=[Link]("spliting value")
Examples:

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


>>> [Link]() --------- ['Python', 'is', 'an', 'oop', 'lang']
>>> s="9-11-2021"
>>> l=[Link]("-")
>>> print(l) --------- ['9', '11', '2021']
>>> s="apple#kiwi#guava-banana"
>>> l=[Link]("#")
>>> print(l) --------- ['apple', 'kiwi', 'guava-banana']
>>> l[2].split("-") ------- ['guava', 'banana']

#[Link]
line=input("Enter a line of text:")
print("Given Data={}".format(line))
for ch in line:

414 manojalladi23@[Link]
print("\tCharacter: {} Index={}".format(ch,[Link](ch)))
print(" ")
for i,l in enumerate(line):
print("{} found at {} Index".format(l,i))

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

Examples: Python, Java . C#.Net...etc

415 manojalladi23@[Link]
Intruduction to Thread Based Applications

=>The purpose of multi threading is that "To provide Concurrent / Simultaneous


execution / Paralllel Execution".
=>Concurrent Execution is nothing but executing the operations all at once.
=>The advantage of Concurrent execution is that to get less execution time.
=>If a Python Program contains multiple threads then it is called Multi Threading program.

=>Def. of thread:

=>A flow of Control is called thread.


=>The purpose of thread is that "To Perform certain operation whose logic
developed in Functions / Methods concurently."

=>By default Every Python contains Single Thread and whose name is "MainThread" and It
provides Sequential Execution.
=>Programtically, In a Python Program we can create multiple sub / Child
threads and whose purpose is that "To execute operations whose logic is written in Functions /
Methods Concurrently ".
=>Hence Programatically a Python Program contains two types of Threads. They are
a) MainThread
b) Sub / Child Threads
=>MainThread is created / Initiated by PVM ,when program exeuction starts and the role of

416 manojalladi23@[Link]
mainThread is to execute main program statements and Monitor the exeuction status of Sub
threads(if sub threads present).
=>The Sub / Child Threads always executes operations whose logic is written in Functions /
Methods Concurrently ".

#[Link]
import time,threading
def squares(lst):
for i in lst:
print("{} executed by
square({})={}".format(threading.current_thread().name,i,i**2))
[Link](1)

def cubes(lst):
for i in lst:
print("{} executed by
cubes({})={}".format(threading.current_thread().name,i,i**3))
[Link](1)

#main program
bt=[Link]()
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=[Link]()
print("Exec Time by Non-Threading application:{}".format(et-bt))

#[Link]
import time,threading
def squares(lst):
for i in lst:
print("{} executed by
square({})={}".format(threading.current_thread().name,i,i**2))
[Link](1)
def cubes(lst):
for i in lst:
print("{} executed by
cubes({})={}".format(threading.current_thread().name,i,i**3))

417 manojalladi23@[Link]
[Link](1)

#main program
bt=[Link]()
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=[Link](target=squares,args=(lst,) ) # Thread-1
t2=[Link](target=cubes,args=(lst,) ) # Thread-2
[Link]()
[Link]()
[Link]()
[Link]()
print("\nProgram execution Completed:")
et=[Link]()
print("Exec Time by Threading Application:{}".format(et-bt))

threading module

1) current_thread()

=>It is used for obtaining name of th thread


=>Syntax: threading.,cuurent_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 [Link]

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=[Link](target=Functionname, args=(Val1,val2. .. Val-n))
Here varname is called an object of sub thread

418 manojalladi23@[Link]
2) start():

=>This function is used for dispatching the sub thread for executing targeted Function .
=>Syntax:- [Link]()

3) join():

=>This function is used for making the sub threads to join with main thread after sub threads
completion.
Syntax: [Link]()
[Link]()

[Link]()

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:- [Link]("str")
(OR)
[Link]=str data Here str data represent sub thread name
Example: [Link]("Raju")
(OR)
[Link]="Raju"

5) getName():

=>This function is used forobtaining the thread name


=>This Function is deprecated on the name of "name" attribute
=>Syntax:- subthreadname=[Link]()
(OR)
str data=[Link] # Here str data represent sub thread name
Example: tname=[Link]()
(OR)
tname=[Link]

6) is_alive():

=>This function returns true provded sub thread is under execution otherwise it return False.
=>Syntax: subthreadname.is_alive()

419 manojalladi23@[Link]
Example: t1.is_alive()

7) run(self):

Number of approaches to develop multi threading 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


#[Link]
import time
import threading # step-1
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)
[Link](1)
print("-"*50)
#main program
t1=[Link](target=generate) # step-3
[Link]()

420 manojalladi23@[Link]
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


#[Link]
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)
[Link](1)
print("-"*50)
#main program
n=Numbers() #Step-4
t1=[Link](target=[Link],args=(int(input("Enter a number:")),)) #Step-5
[Link]() #Step-6

#[Link]
import threading
tname=threading.current_thread().name
print("Name of the thread=",tname)
print("Number of Active Threads=",threading.active_count())

421 manojalladi23@[Link]
#[Link]
import threading,time
def fun1(mssg):
print("\nName of the thread in fun1()=",threading.current_thread().name) # Thread-1
print("Hi {} , Good Evening".format(mssg))
[Link](10)

#main program
tname=threading.current_thread().name
print("Name of the thread=",tname)
print("Number of Active therads before start of sub thread=",threading.active_count()) # 1
t1=[Link](target=fun1,args=("Rossum",) ) # Just created---New State
[Link]()
print("Number of Active threads after start of sub thread=",threading.active_count()) # 2
[Link]()
print("Line-16 Number of Active threads incl sub thread=",threading.active_count()) # 1

#[Link]
import threading,time
def fun1(mssg):
print("\nName of the thread in fun1()=",threading.current_thread().name) # Raju
print("Hi {} , Good Evening".format(mssg))
[Link](10)

#main program
tname=threading.current_thread().name
print("Name of the thread=",tname)
print("Number of Active therads before start of sub thread=",threading.active_count()) # 1
t1=[Link](target=fun1,args=("Rossum",) ) # Just created---New State
[Link]="Raju Nayak" # OR [Link]("Raju") # setting user-friendly name to the sub /
child thread
[Link]()
print("Number of Active threads after start of sub thread=",threading.active_count()) # 2
[Link]()
print("Line-16 Number of Active threads complete execution of sub
thread=",threading.active_count()) # 1

#[Link]
import threading,time
def fun1(mssg):

422 manojalladi23@[Link]
print("\nName of the thread in fun1()=",threading.current_thread().name) # Raju
print("Hi {} , Good Evening".format(mssg))
[Link](10)

#main program
tname=threading.current_thread().name
print("Name of the thread=",tname)
print("Number of Active therads before start of sub thread=",threading.active_count()) # 1
t1=[Link](target=fun1,args=("Rossum",) ) # Just created---New State
print("Exec status of sub thread before start=",t1.is_alive()) # False
[Link]()
print("Exec status of sub thread after start=",t1.is_alive()) # true
[Link]()
print("Line-17:---Exec status of sub thread after completion=",t1.is_alive()) # False

#Program generating 1 to n number after each very second by using threads


#[Link]
import time
import threading # step-1
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)
[Link](1)
print("-"*50)

#main program
t1=[Link](target=generate) # step-3
[Link]()

#Program generating 1 to n number after each very second by using threads


#[Link]
import time
import threading #Step-1

423 manojalladi23@[Link]
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)
[Link](1)
print("-"*50)

#main program
n=Numbers() #Step-4
t1=[Link](target=[Link],args=(int(input("Enter a number:")),)) #Step-5
[Link]() #Step-6

Pandas

Introduction to Pandas:

=>Pandas is an open source Python Library / Module providing high performance and data
manipulation and Analysis Tool.
=>The word PANDAs derived from PANel DAta
=>The pandas concept developed by WES MCKinney in the year 2008.
=>The Traditional Python Programming does not contain any Module for Data Analysis and
Now Python Programming uses Pandas as a Data anaysis tool.
=>Python Pandas can be used in wide range of fields like Financial Services, Statistics , retail
maketing sectors..etc as data analysis tool
=>pandas module developed in C and Python Languages.

Instalation of Pandas:

=>The standard python software / Distribution (CPYTHON) does not contain any module for
data analysis and now we are using third party module called PANDAS and whose module name
is pandas
=>Programatically to use pandas as part of our python program, we must install pandas module

424 manojalladi23@[Link]
by using pip tool.

Syntax:- pip install module name

Example:- pip install pandas

Key Features of Pandas:-----> Series DataFrame

1) Fast and Efficient Data Frame with default and costomized indexing
2) Tools for loading the data in in-memory data objects( objects of Series, DataFrame
)
3) We can access the data from pandas by using Labeled Based Slicing and indexing.
4) Columns from in-memory data objects( objects of Series, DataFrame ) can be deleted and
inserted

threading module

1) current_thread()

=>It is used for obtaining name of th thread


=>Syntax: threading.,cuurent_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 [Link]

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=[Link](target=Functionname, args=(Val1,val2. .. Val-n))
Here varname is called an object of sub thread

425 manojalladi23@[Link]
2) start():

=>This function is used for dispatching the sub thread for executing targeted Function .
=>Syntax:- [Link]()

3) join():

=>This function is used for making the sub threads to join with main thread after sub threads
completion.
Syntax: [Link]()
[Link]()

[Link]()

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:- [Link]("str")
(OR)
[Link]=str data Here str data represent sub thread name
Example: [Link]("Raju")
(OR)
[Link]="Raju"

5) getName():

=>This function is used forobtaining the thread name


=>This Function is deprecated on the name of "name" attribute
=>Syntax:- subthreadname=[Link]()
(OR)
str data=[Link] # Here str data represent sub thread name
Example: tname=[Link]()
(OR)
tname=[Link]

426 manojalladi23@[Link]
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()

7) run(self):

=>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>([Link]):

def run(self):
block of statements
provides logic for thread

Number of approaches to develop multi threading 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.

427 manojalladi23@[Link]
Examples:
#Program generating 1 to n number after each very second by using threads
#[Link]
import time
import threading # step-1
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)
[Link](1)
print("-"*50)

#main program
t1=[Link](target=generate) # step-3
[Link]()

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


#[Link]
import time
import threading #Step-1
class Numbers: #Step-2
def generate(self,n): #Step-3
self.n=n

428 manojalladi23@[Link]
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)
[Link](1)
print("-"*50)

#main program
n=Numbers() #Step-4
t1=[Link](target=[Link],args=(int(input("Enter a number:")),)) #Step-5
[Link]() #Step-6

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


#[Link]
import threading ,time # Step-1
# Step-2 Step-3
class Numbers([Link]):
def setvalue(self,n):
self.n=n
def run(self): # Step-4--->Overriding the run() of Thread class of threading module
[Link](int(input("Enter Value of n:")))
if(self.n<=0):
print("{} is invalid".format(self.n))
else:

429 manojalladi23@[Link]
print("-"*50)
print("Numbers within :{}".format(self.n))
print("-"*50)
for i in range(1,self.n+1):
print("Val of i=",i)
[Link](1)
print("-"*50)

#main program
n=Numbers() #Step-5 --- Sub thread creation only
print("Execution status of sub thread before =",n.is_alive())
[Link]() # Step-6 --- dispatching sub thread
print("Execution status of sub thread after start=",n.is_alive())

#Program generating 1 to n number after each very second by using threads


#[Link]
import threading ,time # Step-1
# Step-2 Step-3
class Numbers([Link]):
def setvalue(self,n):
self.n=n
def run(self): # Step-4--->Overriding the run() of Thread class of threading module
[Link](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)
[Link](1)
print("-"*50)

#main program
n=Numbers() #Step-5 --- Sub thread creation only
print("Execution status of sub thread before =",n.is_alive())
[Link]() # Step-6 --- dispatching sub thread
print("Execution status of sub thread after start=",n.is_alive())

430 manojalladi23@[Link]
#Write a Python Program which will accept a line of text and display each and every
character after one second using thread
#[Link] --- Functional Approach
import threading,time
def chargeneration(line):
if ([Link]() or len(line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",line)
print("-"*50)
for ch in [Link]():
print("\t\t{}".format(ch))
[Link](0.5)
print("-"*50)

#main program
t=[Link](target=chargeneration,args=(input("Enter a line:"),))
[Link]()

#Write a Python Program which will accept a line of text and display each and every
character after one second using thread
#[Link] --- Object Oriented Approach without Inheritance
import threading,time
class CharGen:
def chargeneration(self,line):
[Link]=line
if ([Link]() or len([Link])==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",[Link])
print("-"*50)
for ch in [Link]():
print("\t\t{}".format(ch))
[Link](0.5)
print("-"*50)
#main program
t=[Link](target=CharGen().chargeneration,args=(input("Enter a line:"),))
[Link]()

431 manojalladi23@[Link]
#Write a Python Program which will accept a line of text and display each and every
character after one second using thread
#[Link] --- Object Oriented Approach with Inheritance
import threading,time
class CharGen([Link]):
def run(self):
[Link]=input("Enter a line of Text:")
if ([Link]() or len([Link])==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",[Link])
print("-"*50)
for ch in [Link]:
print("\t\t{}".format(ch))
[Link](0.5)
print("-"*50)

#main program
cg=CharGen() # here cg is an object of CharGen Class and it is sub thread
[Link]() # start() automatically calls run(), which as already overridden in CharGen Class.

#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.
#[Link]
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):
print("{}-->Generates Even
Number:{}".format(threading.current_thread().name,i))
[Link](0.75)

class Odd:
def oddnumbers(self,n): # Object Oriented Approach without using Inheritance
if(n<=0):
print("{} is invalid".format(n))
else:

432 manojalladi23@[Link]
for i in range(1,n+1,2):
print("{}-->Generates Odd
Number:{}".format(threading.current_thread().name,i))
[Link](0.75)

class Vowels([Link]):
def settext(self,line):
[Link]=line
def run(self): # Object Oriented Approach without using Inheritance
if ([Link]() or len([Link])==0):
print("Given String is empty:")
else:
for i in [ j for j in [Link] if [Link]() in ['a','e','i','o','u'] ]:
print("{}-->Generates
Vowel:{}".format(threading.current_thread().name,i))
[Link](0.75)

#main program
v=Vowels() # Object Oriented Approach with Inheritance
line=input("Enter a line of text:")
[Link](line)
n=int(input("Enter a Number:"))
et=[Link](target=evennumbers,args=(n,)) # Functional Approach
ot=[Link](target=Odd().oddnumbers,args=(n,)) # Object Oriented Approach without
using Inheritance
[Link]()
[Link]()
[Link]()

433 manojalladi23@[Link]
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.

=>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=[Link]()
2) To obtain the lock on the sharable resource, we must use acquire()
Syntax:

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

[Link]()

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.

434 manojalladi23@[Link]
#[Link]
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))
[Link](0.5)
print("-"*50)
#main program
t1=[Link](target=table,args=(4,))
t2=[Link](target=table,args=(14,))
t3=[Link](target=table,args=(-9,))
t4=[Link](target=table,args=(19,))
[Link]()
[Link]()
[Link]()
[Link](

435 manojalladi23@[Link]
#[Link] (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)
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))
[Link](0.5)
print("-"*50)

#main program
t1=[Link](target=Multable().table,args=(4,))
t2=[Link](target=Multable().table,args=(14,))
t3=[Link](target=Multable().table,args=(-9,))
t4=[Link](target=Multable().table,args=(19,))
[Link]()
[Link]()
[Link]()
[Link]()

#[Link] (With Inheritance)


import threading,time
class MulTable([Link]):
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)

436 manojalladi23@[Link]
for i in range(1,11):
print("\t{} x {}={}".format(self.n,i,self.n*i))
[Link](0.5)
print("-"*50)

#main program
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
[Link](4)
[Link](14)
[Link](-9)
[Link](19)
[Link]()
[Link]()
[Link]()
[Link]()

#[Link]
import threading,time
def table(n):
[Link]() # 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))
[Link](0.5)
print("-"*50)
[Link]() # release the lock

#main program
#Create an object Lock class
L=[Link]() # Here L is an object of Lock class and it is global variable
t1=[Link](target=table,args=(4,))

437 manojalladi23@[Link]
t2=[Link](target=table,args=(14,))
t3=[Link](target=table,args=(-9,))
t4=[Link](target=table,args=(19,))
[Link]()
[Link]()
[Link]()
[Link]()

#[Link] (With Inheritance)


import threading,time
class MulTable([Link]):
K=[Link]() # Here K is an object of Lock class and it is Class Level Variable
def setval(self,n):
self.n=n
def run(self):
[Link]()
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))
[Link](0.5)
print("-"*50)
[Link]()
#main program
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
[Link](4)
[Link](14)
[Link](-9)
[Link](19)
[Link]()
[Link]()
[Link]()

438 manojalladi23@[Link]
[Link]()

#[Link] (Without Inheritance)


import threading,time
class Multable:
def table(self,n):
[Link]() # 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))
[Link](0.5)
print("-"*50)
[Link]() # release the lock

#main program
#Create an object Lock class
K=[Link]() # Here K is an object of Lock class and it is global variable
t1=[Link](target=Multable().table,args=(4,))
t2=[Link](target=Multable().table,args=(14,))
t3=[Link](target=Multable().table,args=(-9,))
t4=[Link](target=Multable().table,args=(19,))
[Link]()
[Link]()
[Link]()
[Link]()

#[Link] (Without Inheritance)


import threading,time
class Multable:
@classmethod
def getlock(cls):
cls.K=[Link]() # Here K is an object of Lock class and it is Class Level
Variable

439 manojalladi23@[Link]
def table(self,n):
[Link]() # 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))
[Link](0.5)
print("-"*50)
[Link]() # release the lock

#main program
[Link]()
t1=[Link](target=Multable().table,args=(14,))
t2=[Link](target=Multable().table,args=(8,))
t3=[Link](target=Multable().table,args=(-16,))
t4=[Link](target=Multable().table,args=(23,))
[Link]()
[Link]()
[Link]()
[Link]()

#[Link]
import threading,time
class Train([Link]):
L=[Link]() # Here L is called Class Level Variable
seats=20 # Here seats are called Class Level Variable
def reserve(self,rs):
[Link]=rs
def run(self):
[Link]()
if([Link]<[Link]):
print("Hi {} , u don't have {} Seats in My
train:".format(threading.current_thread().name,[Link]))

440 manojalladi23@[Link]
else:
[Link]=[Link]
print("Hi {} , u have Reserved {} Seats in My
train:".format(threading.current_thread().name,[Link]))
print("Still Available Seats:{}".format([Link]))
[Link](2)
[Link]()

#main program
t1=Train()
[Link]="Litun"
t2=Train()
[Link]="manaiah"
t3=Train()
[Link]="bavika"
t4=Train()
[Link]="rajrao"
t5=Train()
[Link]="KVR"
[Link](10)
[Link](15)
[Link](4)
[Link](2)
[Link](6)
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

441 manojalladi23@[Link]
Decorators in Python

=>Decorator is one of the Function which will provides Additional Processing capability to the
normal Function value and returns the modified value.
=>A Decorator Function is always takes Normal Function as parameter

Syntax:-

def functionname1( functionname ): # Decorator


def innerfunctionname(): # Inner Function name
val=functionname()

#do the operationon ' val '

return resut # Inner Funtion must return modified value


return innerfunctionname # Decorator returns inner function name

=>here functionname1 is called Decorator function


=>here Functionname as a formal parameter . Every decorator function must take normal
function as parameter.

#Program for decorator


#[Link]
def getval(): # Defined by Rajesh
return 5

def square( gv ): # Here Square is called Decorator


def processsquare(): # Here processqquare is called Inner Function
n=gv()
res=n**2
return res
return processsquare

#main program
result=square( getval )
r=result()
print("Result=",r)

442 manojalladi23@[Link]
#Program for decorator
#[Link]

def square( gv ): # Here Square is called Decorator


def processsquare(): # Here processqquare is called Inner Function
n=gv()
res=n**2
return res
return processsquare

@square
def getval(): # Defined by Rajesh
return 5

#main program
result=getval()
print("result=",result)

#Program for decorator


#[Link]

def getval():
return (float(input("Enter a number:")))

def squareroot(kvr): # here squareroot is called Decorator


def processsqrt(): # Here processsqrt is called Inner Function
n=kvr()
res=n**0.5
return res
return processsqrt

#main program
res=squareroot(getval)
r=res()
print("Square root={}".format(r))

443 manojalladi23@[Link]
#Program for decorator
#[Link]

def squareroot(kvr): # here squareroot is called Decorator


def processsqrt(): # Here processsqrt is called Inner Function
n=kvr()
res=n**0.5
return res
return processsqrt

@squareroot
def getval():
return (float(input("Enter a number:")))

#main program
res=getval()
print("Result=",res)

#Program for decorator


#[Link]
def getval(): # Defined by Rajesh
return 5

def getsquare(): # Rakesh want square of 5


n=getval()
print("Square({})={}".format(n,n**2))

def getsqroot(): #Ramesh want square root of 5


n=getval()
print("Square root({})={}".format(n,n**0.5))

#main program
getsquare()
getsqroot()

444 manojalladi23@[Link]
Iterators in Python

Why should WE use Iterators:

=>In modern days, we have a lot of data in our hands, and handling this huge amount of data
creates problems for everyone who wants to do some sort of analysis with that [Link], If you’ve
ever struggled with handling huge amounts of data, and your machine running out of memory,
then WE use the concept of Iterators in Python.
=>Therefore, Rather than putting all the data in the memory in one step, it would be better if we
could work with it in bits or some small chunks, dealing with only that data that is required at
that moment. As a result, this would reduce the load on our computer memory tremendously.
And this is what exactly the iterators do.
=>Therefore, you can use Iterators to save a ton of memory, as Iterators don’t compute their
items when they are generated, but only when they are called upon.

=>Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts,
and sets.
=>The iterator object is initialized using the iter() method. It uses the next() method for iteration.
=>Here iter() is used for converting Iterable object into Iterator object.
=>next() is used for obtaining next element of iterator object and if no next element then we get
an exception called StopIteration.
=>On the object of Iterator, we can't perform Indexing and Slicing Operations bcoz They supply
the values on demand .
Examples:

s = 'Python'
itobj = iter(s)
while True:
try:
item = next(s) # Iterate by calling next
print(item)
except StopIteration: # exception will happen when iteration will over
break

mytuple = ("apple", "banana", "cherry")


myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))

445 manojalladi23@[Link]
#[Link]
import sys
lst=[10,20,30,40,50,60,70,80,90] # here lst is called Iterable object
print(lst,type(lst),[Link](lst))
#convert Iterable object into Iterator object
lstitr=iter(lst)
print(lstitr,type(lstitr),[Link](lst))
print(" ")
while(True):
try:
print(next(lstitr))
except StopIteration:
break

#[Link]
import sys
d={10:"python",20:"Java",30:"Dsc"}
print(d,type(d),[Link](d))
#convert Iterable object into Iterator object
ditr=iter(d)
print(ditr,type(ditr),[Link](ditr))
print(" ")
while(True):
try:
k=next(ditr)
print(k,"--->",[Link](k))
except StopIteration:
break

#[Link]
import sys
s="PYTHON PROG"
print(s,type(s),[Link](s))
its=iter(s)
print(its,type(its),[Link](its))
print(" ")
while(True):
try:
k=next(its)
print(k,end=" ")

446 manojalladi23@[Link]
except StopIteration:
break

#[Link]
import sys
s="PYTHON PROG"
print(s,type(s),[Link](s))
its=iter(s)
print(its,type(its),[Link](its))
print(" ")
for i in next(its):
print(i)

generator in python

=>generator is one of the function


=>The generator function always contains yield keyword
=>If the function contains return statement then it is called Normal Function
=>If the function contains yield keyword then it is called generator
=>Syntax:
def function_name(start,stop,step):

yield value

=>The 'yield' key word is used for giving the value back to function call from function defintion
and continue the function execution until condition becomes false.
=>The advantage of generators over functions concept is that it save lot of memory space in the
case large sampling of data. In otherwords Functions gives all the result at once and it take more
memory space where as generators gives one value at a time when programmer requested and
takes minimized memory space.

#[Link]
def kvrrange(beg,end):
while(beg<=end):
yield beg
beg=beg+1

447 manojalladi23@[Link]
#main program
r=kvrrange(10,16) # Function Call
print(r,type(r))
print(" ")
while(True):
try:
print(next(r))
except StopIteration:
break

#[Link]
def kvrrange(beg,end,step):
while(beg<=end):
yield beg
beg=beg+step

#main program
r=kvrrange(10,20,2) # Function Call
print(r,type(r))
print(" ")
while(True):
try:
print(next(r))
except StopIteration:
break

Network Programming in Python

=>The purpose of Network Programming in Python is that "To share the data between multiple
remote machines which are located across the world".
=>A network is a collection of inter-connected autonomous computers connected with Server".
=>The main of Network Programming in python is that to Client-Server Applications.
=>In Client-Server Application development, there exist two types of Programs. They are
1. Client-Side Program
2. Server-Side Program

448 manojalladi23@[Link]
Def. of Client Side Program

=>A Client Side Program is one which always makes a request to server-side program and
obtains response from Server-Side Program.

Def. of Sever Side Program

A Server Side Program is one, which will receive the request from Client Side Program, Process
and Gives Response back Client side program.

=>Def of DNS(Domain Naming Service) represents name of the machine where Server Side
Program is Available. The default DNS of Every Machine is "localhost".

Def of IPAddress (Internet Protocal Address) represents An address of Physical Machine where
Server Side Program is Available. The default IP Address of Every Machine is [Link] (Loop
back address)

Def. of Port Number:

A Port Number is a logical Numerical id where Server Side Program is running

Steps for Developing Server-Side Program and Client Side Applications

Steps for Developing Server-Side Program

1. import socket module


2. Every Server Side Program must run at Certain DNS/IPaddress and Port Number
3. Every Server Side Program must be configred in such way that how many clients it can
communicate.
4. Every Server Side Program must ACCEPT Client Side Program request
5. Every Server Side Program must READ Client Side Program Request
6. Every Server Side Program must PROCESS Client Side Program Request
7. Every Server Side Program must gives Response back to Client Side Program

NOTE: As long as Client Requests are comming, Server Side Program Performs Step-4,5,6,7.

449 manojalladi23@[Link]
Steps for Developing Client-Side Program

1. import socket module


2. Every Client Side Proram must get a connection from Server-Side Program by passing (DNS
and port Number or IPAddress and Port Number ).
3. Every Client Side Proram must send a Request to Server-Side Program
4. Every Client Side Proram must Receive Response from Server-Side Program

NOTE: As long as Client Side Program is interested to communicate with Server Side Program,
it has to Perform step-(3) and (4)

Module Name for Developing Server-Side Program and Client Side Applications

=>To develop Server-Side Program and Client Side Programs, we must use a pre-defined
module called "socket".

Functions present in socket module

1)socket()

=>This function is used for creating an object socket and acts as bi-directional communication
object between Server-client Side Programs.
Syntax:- varname=[Link]()
=>Here varname is an object <class, 'socket'> which will exist both at client and Server Side
Programs
=>Examples:- s=[Link]()

2) bind():

=>This Function is used Making Server Side Program to bind at Certain DNS/IPaddress and
port number.
=>Syntax: [Link]( ("DNS",portno) )
(OR)
[Link]( ("IPAddress",portno) )

=>Examples: [Link]( ("localhost",9999) )


[Link]( ("[Link]",9999) )

450 manojalladi23@[Link]
3) listen()

=>This function is used for configuring The Server Side Program in such way that to how many
clients the server side program can communicate.
=>Syntax: [Link]([Link] clients)
=>Examples: [Link](2)

4) accept()

=>This Function is used for accepting Client Side Program Request by Server Side Program .
=>In Otherwords, accpeting client request by Server Side Program is nothing but obtaining
Client Socket object and its address.
Syntax: ClientSocketobj,ClientAddress=[Link]()

Examples: cs,ca=[Link]()

5) recv() with decode()

=>This Function is used for reading Client Request at Server Side and it can also used at Client
Side Program for reading Response of Server Side Program
Syntax: varname=[Link](1024/2048/4096).decode()
Here var name is an object of str
Examples: data=[Link](1024).decode()

6) send() with encode()

=>This Function is used for sending Client Side Program Request to Server Side Program and it
can also to be used for Sending Server Side Program Response to Client Side Program.
=>Syntax:- [Link]( [Link]() )
=>Example: [Link]("Hello Server/Client".encode())

7) connect()

=>This Function is used for obtaining connection from Server Side Program by the client side
program by passing (DNS,port no) or (IPAddress, portno)
=>Syntax:- [Link](("DNS",port no))
(OR)
[Link](("IPAddress",port no))
=>Examples: [Link]( ("localhost",8888))

451 manojalladi23@[Link]
#This Program considered as Client Side Program, It Sends the Messages Server Side
Program and gets Answer as Response by client side Program from server side program
#[Link] ---- Program-(B)
import socket,sys
while(True):
s=[Link]()
[Link]( ("localhost",9999) )
csdata=input("Student-->")
if([Link]()=="bye") :
[Link]("Bye KVR, I have some work!".encode())
[Link]()
else:
[Link]([Link]())
ssdata=[Link](1024).decode()
print("KVR-->{}".format(ssdata))

#This Program considered as Server Side Program, It receives the Messages from Client
Side Program and Gives Answer as Response to client side Program
#[Link] ---- Program-(A)
import socket
s=[Link]()
[Link]( ("localhost",9999) )
[Link](1)
print("SSP is ready to accept any CSP:")
print("-"*40)
while(True):
cs,addr=[Link]()
csdata=[Link](1024).decode()
print("Student Msg-->{}".format(csdata))
sdata=input("KVR-->")
[Link]([Link]())

#write a client side program which will accept employee [Link] keyboard,send to the
server and get employee name,salry and disignation from server side program.
#[Link]
import socket
s=[Link]()
[Link](("[Link]",3600))
print("CSP got Connection From SSP:")
empno=input("\nEnter Employee Number:")

452 manojalladi23@[Link]
[Link]([Link]())
sdata=[Link](1024).decode()
print(" ")
print("Result from Server about Employee:")
print(" ")
print(sdata)
print(" ")

# Client side program to send a Numerical no. to the Server Side Program & get its Square
from the Server Side Prog.
#[Link]
import socket # step-1
s=[Link]()
[Link](("localhost",8888)) # Line-4 and 5 ---- step-2
print("CSP got Connection from SSP:")
n=input("\nEnter a number:")
[Link]([Link]()) # step-3
sdata=[Link](1024).decode()
print("Square({})={}".format(n,sdata))

# Write a server side program which will accept employee number from client, retrieve
empname, salary and designation from emp table.
#[Link] ---------- Program-(A)
import socket
import cx_Oracle
s=[Link]()
[Link](("[Link]",3600))
[Link](2)
print("SSP is Ready to accept CSP request:")
while(True):
try:
cs,ca=[Link]()
eno=int([Link](1024).decode())
#PDBC
oracon=cx_Oracle.connect("scott/tiger@localhost/orcl")
print("SSP connectd to Oracle DB")
cur=[Link]()
[Link]("select ename,sal,cname from employee where eno=%d" %eno)
record=[Link]()
if(record==None):

453 manojalladi23@[Link]
[Link]("Employee Record Does not Exist".encode())
else:
[Link](str(record).encode())
except ValueError:
[Link]("Don't enter strs,Symbols and alph-numerics for empno".encode() )
except cx_Oracle.DatabaseError as db:
[Link]("Prob in DB"+str(db).encode())
except :
[Link]("OOOOPs Some went wrong".encode())

#Server Program for accepting a number from Client and gives its square to client as
response
#[Link]
import socket # Step-1
s=[Link]()
[Link](("localhost",8888)) # Line-3 and 4 ----- step-2
[Link](2) #step-3
print("SSP is ready to Accept any CSP ")
while(True):
try:
cs,ca=[Link]() #step-4
cdata=float([Link](1024).decode()) # step-5
print("Client Data At Server={}".format(cdata))
res=cdata**2 # Step-6
[Link](str(res).encode() ) # Step-7
except ValueError:
[Link]("Don't enter strs,sybols and alnums".encode())

# Python program to read json file


#[Link]
import json
# Opening JSON file
try:
fp = open('[Link]')
# returns JSON object as a dictionary
data = [Link](fp)
# Iterating through the json list
for i,j in [Link]():
print("{}--->{}".format(i,j))
except FileNotFoundError:

454 manojalladi23@[Link]
print("Json File does not exist")

#[Link]
import json
# JSON string
employee = ' {"id":"09", "name": "Rossum", "department":"IT"} '
print("Json String data=",employee)
# Convert string to Python dict
employee_dict = [Link](employee)
print("Dict Data=",employee_dict)
for k,v in employee_dict.items():
print("{}-->{}".format(k,v))

# Python program to write JSON to a file


#[Link]
import json
# Data to be written
dictionary ={
"name" : "Rossum",
"rollno" : 56,
"cgpa" : 8.6,
}
with open("[Link]", "w") as fp:
[Link](dictionary, fp)
print("Data written to file--verify")

{"name": "Rossum", "rollno": 56, "cgpa": 8.6}

455 manojalladi23@[Link]
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 with JSON data, Python has a built-in module called json.

Parse JSON (Convert from JSON to Python)

[Link]() method can parse a json string and converted into Python dictionary.
Syntax:
dictobj=[Link](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 = [Link](employee)
print(employee_dict)

Python--- read JSON file

=>[Link]() method can read a file which contains a JSON object.


Consider a file named
[Link] which contains a JSON object.
Syntax:
[Link](file_object)

456 manojalladi23@[Link]

You might also like