Python by K V Rao - NareshIT HYD
Python by K V Rao - NareshIT HYD
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
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)”
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):
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.
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 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 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.
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
10. Embedded
=>Python Programming can call other languages coding segments for fastest execution
=>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.
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
=>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:
>>> 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
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
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
=>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
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'?
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
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
=>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
=>Types of Strings:
17 manojalladi23@[Link]
[Link] Line String Data
=>Single String data must be enclosed within Single Quotes or Double Quotes only
Examples:
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:
=>Multi Line String data must be enclosed within Tripple Single Quotes or Tripple Double
Quotes only
=>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'>
>>> 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
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
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'
=>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[ : ]
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 .
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
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'
>>> 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 :
=>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 :
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
>>> 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'>
>>> 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'>
>>> 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)
>>> a=12
>>> print(a,type(a))
29 manojalladi23@[Link]
12 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))
(12+0j) <class 'complex'>
>>> a=12.34
>>> print(a,type(a))
12.34 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))
(12.34+0j) <class 'complex'>
>>> 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:
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'
Mutability:
=>A Mutable object is one which allows to modify / update its Value / Content at Same
Address.
Examples:
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)
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
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
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)
37 manojalladi23@[Link]
5
6
7
8
9
38 manojalladi23@[Link]
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
39 manojalladi23@[Link]
... print(i)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
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:
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:
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
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():
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()
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
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()
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():
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']
Examples:
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
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
append()
insert()
clear()
remove()
pop(index)
pop()
copy()
reverse()
sort()
extend()
=>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:
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
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()
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():
>>> 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()
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():
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:
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
>>> 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
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=================================
=>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()
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'}
>>> 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()
>>> 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
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'
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()
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()
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.
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
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)
Syntax1:- print(val1,val2...val-n)
(OR)
print(var1,var2...var-n)
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)
Examples:
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum=",c) ------------- sum= 30
>>> print(c," is the sum")--------30 is the sum
>>> print('sum of ',a,' and ',b,'=',c)-------sum of 10 and 20 = 30
>>> 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
=>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
=>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("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)
78 manojalladi23@[Link]
print("Enter Length and Breadth:")
ar=float(input())*float(input())
print("Area of Rect=",ar)
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:
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)
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)
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
=>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.
#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)
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:
=>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
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
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)
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 :
Examples:
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.
Examples:
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:
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:
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
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 ( << ):
>>> 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 ( | ):
0 0 0
1 0 1
0 1 1
1 1 1
Examples:
>>>a=4 0100
>>>b=3 0011
>>> 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 (& ):
0 0 0
1 0 0
0 1 0
1 1 1
Examples:
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
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
0 0 0
1 0 1
0 1 1
1 1 0
96 manojalladi23@[Link]
Examples:
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:
2) not in Operator:
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
=>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:
2) is not:
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
>>> 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.
=>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!")
108 manojalladi23@[Link]
109 manojalladi23@[Link]
#Program for accepting a digit and print its name
#[Link]
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)
case label-n:
block of statements-n
case _ : # default case block
default block of statements
111 manojalladi23@[Link]
Other statements in Program
Explanation:
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")
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:")
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)
116 manojalladi23@[Link]
2. for loop or for ...else loop
Syntax1:-
Syntax2:
else:
Explanation:
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")
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 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)
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:
if (test cond):
break
=>Syntax2:
while(Test Cond-1):
if (test cond-2):
break
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")
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:-
if ( Test Cond):
continue
statement-1 # written after continue statement
statement-2
statement-n
=>Syntax:-
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 ")
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
else:
else:
-
Other statements in Program
else:
else:
127 manojalladi23@[Link]
=>Syntax3:(while loop in for loop)
for varnam1 in Iterbale_object1: # Outer for loop
else:
else:
else:
else:
===============================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:
"""
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
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:
“””
131 manojalladi23@[Link]
Value of j--inner while loop:3
Out of inner while loop
#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:
"""
132 manojalladi23@[Link]
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
"""
#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)
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
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
=>In the context of Functions, we have two types of Programming Languages. They are
1. Un-Structured Programming Languages.
2. Structured Programming Languages.
Examples: GW-BASIC
Functions in Python
=>The purpose of Functions concept is that " To perform certain Operations and Provides Code
Re-Usability ."
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
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
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
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:
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))
=>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)
=>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.
functionname(arg1,arg2. .. arg-n)
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)
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).
#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)
#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)
#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)
#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)
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()
=>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.
def functionname(param1,param2...param-n):
functionname(param-n=val-n,param1=val1,param-n-1=val-n-1, ..... )
=>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'>.
=>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)
#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
154 manojalladi23@[Link]
disp(10,20) # Function Call-2
#[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")
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")
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'>.
=>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:
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))
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)
=>Syntax:
Var1=Val1
Var2=Val2
Var-n=Val-n
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()
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
var1=val11
var2=val22
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:
#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:
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.
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
#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)
#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
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]
#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
#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".
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()]
#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:
=>Types of 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.
=>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
=>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:
=>'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
=>This syntax imports single module and aliased with another name
=>This syntax imports multiple modules and aliased with another names
=>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.
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
=>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.
=>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]
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]
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)
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.
=>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:
Example:
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
Syntax:
----------- [Link]("Absolute Path of Package")
Example:
[Link]("E:\\KVR-PYTHON-6pM\\ACKAGES\\BANK")
(or)
[Link]("E:\KVR-PYTHON-6PM\ACKAGES\BANK")
(or)
[Link]("E:\KVR-PYTHON-6PM/ACKAGES/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
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
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:
#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
=>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:
a) Logic Errors:
b) Runtime Errors:
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)
=>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.
=>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
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 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.
3. Save the abovedevelopment on the file name with an extension .py ([Link])
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)
#[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.
if (Test Cond):
raise <exception-class-name>
202 manojalladi23@[Link]
Examples:
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")
class ZeroError(BaseException):pass
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]
#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:")
=>As part of exception Handling, except block can be in different forms. They are
try:
except <exception-class-name>:
try:
try:
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
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:
#[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:
#[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:
#[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:
#[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:
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:
#[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))))
#[Link]
import random as r
for i in range(10,21):
print("SBI"+str([Link](1000,1500)))
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))
#[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
=>os module
219 manojalladi23@[Link]
=>CSV in Pandas
=>JSON FILES in Python
================================x==============================
=>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.
Def. of File:
=>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
1. Write Operation:
=>The purpose of write operation is that "To transfer Temporary data from main memory into
file of secondary memory".
=>Steps:
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
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
=>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():
Explanation:
225 manojalladi23@[Link]
------Block of statements-out of with Indentation-----
Explanation:
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
227 manojalladi23@[Link]
finally:
print("\ni am from finally block")
[Link]() # we are closing the file manually
print("Is file closed=",[Link]) # True
228 manojalladi23@[Link]
print("="*50)
print("\nI am from out of 'with open() as indentation block ")
print("Line-15-->Is file closed=",[Link]) # True
=>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():
2) writelines():
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")
=>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")
=>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.
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.
#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
Examples:
2) Creating a Folder
238 manojalladi23@[Link]
Examples:
Examples:
4) Remove a Folder:
239 manojalladi23@[Link]
Examples:
Examples:
240 manojalladi23@[Link]
Examples:
7) Rename a Folder
Examples;
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")
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")
243 manojalladi23@[Link]
Working with CSV Files in Python
=>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()
=>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)
=>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)
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")
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
Nikhil CSE 2 9
Aditya IT 2 9.3
Sagar SE 1 9.5
Sahil EP 2 9.1
KVR CSE 2 9
247 manojalladi23@[Link]
Name Branch Year cgpa
Nikhil COE 2 9
Aditya IT 2 9.3
Sagar SE 1 9.5
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")
# field names
csvfields = ['name', 'branch', 'year', 'cgpa']
249 manojalladi23@[Link]
# name of csv file
filename = "[Link]"
=>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).
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.
=>In order to write python program to communicate with Oracle Database, we must follow 6
steps. They are
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.
=>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")
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 )
=>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
=>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:
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 )
=>This query is used for removing the table from Database Software
=>Syntax:- SQL> drop table <table-name>
=>Example:- SQL> drop table employee
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()
#main program
aftercolumnsizes()
=>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
2. update
=>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;
#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")
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")
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)
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()
Index:
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
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
[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
=>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.
=>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:
class <clsname>:
Class Level Data Members
def instancemethod(self, list of formal params if any):
@classmethod
def classlevelmethod(cls,list of formal params if any):
@staticmethod
def staticmethod(list of formal params if any):
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.
=>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
=>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(" ")
#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(" ")
#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):
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
=>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()
#main program
s=Sum()
[Link]()
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(" ")
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(" ")
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):
#[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.
Block of Statements--Initlization
=>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:
Garbage Collector
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:
=>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 ( _ _ )
(OR)
class <ClassName>:
def init (self):
self. Data MemberName1=Value1
self. Data MemberName2=Value2
class <ClassName>:
def methodname(self):
[Link] MemberName1=Value1
[Link] MemberName2=Value2
[Link] MemberName-n=Value-n
Example1:
305 manojalladi23@[Link]
self. bal=34.56
[Link]="SBI"
self. pin=1234
[Link]=4444444
#here acno,bal and pin are encapsulated
Example2:
Data Abstraction:
=>The Process of retrieving / extracting Essential Details without considering Hidden Details is
called Data Abstraction.
Example1:
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.
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"
308 manojalladi23@[Link]
print("Account Branch Name:{}".format([Link]))
print("-"*50)""" # can't access
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).
varname=classname()
309 manojalladi23@[Link]
so=Student()
Example:- create an object Employee
eo=Employee()
Class:
Objects:
Inheritance
=>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>:
312 manojalladi23@[Link]
Explanation
#[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]()
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
=>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)".
=>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.
=>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.
=>By using ClassName approach, we can call any base class method / constructor name from the
context of derived class method / constructor names.
#[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:")))
323 manojalladi23@[Link]
2) findall()
3) search()
4) start()
5) end()
6) group()
=>Programming Examples
=>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 .
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()
1) finditer():
=>This function is used for searching the "search pattern" in given data iteratively and it returns
table of entries which contains start index , end index and matched value based on the search
pattern.
2) group():
3) start():
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():
=>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():
=>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]()))
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]
"""
-
#[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]
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]
-
#[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]
"""
#[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]
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]
"""
-
#[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]
"""
-
#[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]
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]
-
#[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]
-
#[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]
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]
"""
-
#[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]
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]
-
#[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]
#[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]
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)
"""
339 manojalladi23@[Link]
1) \s ---------------- > Search for space character
#[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]
"""
#[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]
"""
-
#[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]
"""
#[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]
-
#[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]
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)
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:
=>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.
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.
=>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.
Note:
=>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:
-
>>> 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]]]
>>> [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>
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:
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:
[[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)
Examples:
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()
359 manojalladi23@[Link]
Examples:
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():
Examples:
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():
Examples:
-
>>> 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():
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()
=>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.
=>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]
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]]
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] ]
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]],
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]]]]
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.
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
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
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]]])
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
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]
Examples:
[[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
a) amax():
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)
>>> 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():
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()
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():
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:
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 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.
Example
=>In the case append() , view() does not reflect the changes
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]
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,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]])
=>To select any element from ndarray object, we have two approaches. They are
Approach-1:
=>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.
Approach-2:
=>In this approach, we directly pass Boolean array values to the ndarray for getting required
elements based on condition.
Examples:
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
Creating a Series
Explanation:-
-
Examples:- Create a series for 10 20 30 40 50 60
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]'>
>>> 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]'>
Examples:
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
================================================
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)
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.
>>>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
=>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:
393 manojalladi23@[Link]
>>> print(df)
Names Subjects Ages
1 Rossum Python 65
2 Gosling Java 80
3 Ritche C 85
4 McKinney Pandas 55
>>> 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
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. ..........] ]
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] )
1) dataframeobj.drop_duplicates()
2) dataframeobj.drop_duplicates(inplace=True)
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,
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.
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.
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,
[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.
Output
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,
Output:
=>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.
For example
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.
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,
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.
Output:
—
ID Name Age City Experience
—
13 Aadi 46 Mumbai 11
16 Shaunak 42 Mumbai 17
19 Samir 42 Mumbai 15
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,
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.
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.
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.
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,
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,
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)
=>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():
Examples:
2) title():
=>This Function is used for getting all words First Characters as capital.
=>Syntax:- varname=[Link]()
Examples:
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
Examples:
Examples:
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:
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:
#[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))
=>In the context of Programming Languages, we have 2 types of Languages. They are
a) Process Based Applications
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.
415 manojalladi23@[Link]
Intruduction to Thread Based Applications
=>Def. of thread:
=>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()
2) active_count():
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():
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):
Examples:
420 manojalladi23@[Link]
2. By using Object Oriented Approach without Inheritance
Examples:
#[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
#main program
t1=[Link](target=generate) # step-3
[Link]()
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.
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()
2) active_count():
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():
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
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]()
Examples:
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
Examples:
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())
#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.
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]()
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]()
438 manojalladi23@[Link]
[Link]()
#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]()
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:-
#main program
result=square( getval )
r=result()
print("Result=",r)
442 manojalladi23@[Link]
#Program for decorator
#[Link]
@square
def getval(): # Defined by Rajesh
return 5
#main program
result=getval()
print("result=",result)
def getval():
return (float(input("Enter a number:")))
#main program
res=squareroot(getval)
r=res()
print("Square root={}".format(r))
443 manojalladi23@[Link]
#Program for decorator
#[Link]
@squareroot
def getval():
return (float(input("Enter a number:")))
#main program
res=getval()
print("Result=",res)
#main program
getsquare()
getsqroot()
444 manojalladi23@[Link]
Iterators in Python
=>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
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
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
=>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.
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)
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
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".
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) )
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]()
=>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()
=>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())
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))
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.
[Link]() method can parse a json string and converted into Python dictionary.
Syntax:
dictobj=[Link](json_string)
Examples:
456 manojalladi23@[Link]