Complete Python Course
Complete Python Course
History of Python:
a) Python Programming Language foundation conceived in the year 1980.
b) Python Programming Language implementation starts in the year 1989.
c) Python Programming Language officially released on 20 Feb 1991.
d) Python Programming Language developed by “Guido Van Rossum”.
e) Python Programming Language developed at Centrum Wiskunde &
Informatica (CWI) in Neither-Land.
d) The Predecessor of Python language is called ABC Programming Language
And successor of ABC language is called Python language.
Versions of Python language: (Details information available on Wikipedia)
a) Python programing contains three versions:-
1. Python 1.x--- Here x---> 1, 2, 3…...6. Only. (1 is called major version & x is
Called minor version)
2. Python 2.x--- Here x---> 1, 2, 3…..7. Only. (Abolished in 2020)
3. Python 3.x--- Here x---> 1, 2, 3….12. Only.
b) Python 3.x does not contain backward compatibility with python 2.x
c) Python software and its updates and maintained by a Non-Commercial
Organization called “Python Software Foundation” (PSF).
d) To download Python 3.x software www.python.org
a) Compile Time Error: Due to Syntaxes are not followed (.py to .pyc).
b) Logical Error: Due to wrong representation of logical (at Execution time).
c) Run time Error: Run time error are those error which are occurring
during implementation level. And also due to invalid “INPUT” entered by
the End-User/Application User.
To use Third Party APIs, we must install them by using tool called
“PIP, PIP3, and PIP3.10”.
b) Identifiers or Variables: Once Application user enters the data from Key
board to program, it is the responsible of programmer to store data in the
form of Identifiers or Variables.
Hence all Literals or values or data must store in main memory in the
form of Identifiers or variables otherwise we can’t process the data.
Data representation in python
Examples: >>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)--------10 20 30
b) The variable name must starts with either Alphabet or Special Symbol
(Underscore _ ).
Examples: 123sal=4.5--------invalid
-sal=56.56--------invalid
sal=5.6-----------valid
_sal=67.89--------valid
sal123=6.7--------valid
sal12_=7.8--------valid
__name="Rossum"---valid
c) Within Variable name, Special Symbol are not allowed except underscore ( _ ).
Examples:
emp$sal=5.6-------invalid
emp-sal=5.6-------invalid
emp sal=6.7-----invalid
empsal=6.7-------valid
sal=34------------valid
sal#emp=56--------valid because the symbol # is used in
python as commenting Symbol.
Data representation in python
d) No Keywords to be used as variable name (Keywords are reserved words which
will have some special meaning to the language compiler).
Examples:
if=34------------inavlid
else=5.6-----inavlid
if1=34-----------valid
_else=5.6---------valid
int=23---------valid bcoz all the class
names are not keywords.
e) All the variables in python are Case Sensitive.
Examples:
>>> age=99----valid
>>> AGE=98---valid
>>> Age=97---valid
>>> aGe=96--valid
>>> print(age,AGE,Age,aGe)----99 98 97 96
Data Types in Python
The Purpose of Data Types in Python is that “To allocate memory space for
the input Literals to store in main memory of computer”.
The “ int ” data can also store various number system values.
In Python Programming, we have 4 Types of number system. They are:
Examples:
>>> a=0b1010
>>> print(a, type(a))-----10 <class 'int'>
>>> a=0B1111
>>> print(a)--------------------15
>>> a=0b10102------SyntaxError: invalid digit '2' in
binary literal
Ⅲ. Octal Number System:
======================================================================
Data Types in Python
=========================================================================
The Purpose of float data type is “To store Real Constant Values or floating
point values (Number with Decimal places)”.
Examples: 3.14, 98.46, 0.9999 ... etc.
float data type does not supports Binary, Octal and Hexa Decimal Number
System. float data type supports Scientific Notation(Mantissa-e-Exponent)
and whose advantage is to taking less memory space for Larger Number
Floating Point Values.
Data Types in Python
Examples:
>>> a=12.34
>>> print(a)--------------------12.34
>>> print(type(a))----------<class 'float'>
>>> print(id(a))-------------1671845431216
Or
>>> print(a,type(a), id(a))----12.34 <class
'float'> 1671845431216
---------------------------------------------------
>>> b=0.3
>>> print(b,type(b),id(b))----0.3 <class 'float'>
1671845435856
---------------------------------------------------
>>> a=0b1111.0b1010-------------SyntaxError:
invalid decimal literal
>>> b=0o23.0b1111----------SyntaxError: invalid
decimal literal
>>> c=0xAC.0xBEE--------SyntaxError: invalid
decimal literal
---------------------------------------------------
Examples:
>>> a=4e2
>>> print(a,type(a))-------400.0 <class 'float'>
>>> a=10e-2
>>> print(a)------------0.1
>>> a=0.000000000000000000005
>>> print(a)------------5e-21
>>> a=0.00000000000000000000000008
>>> print(a,type(a))-------8e-26 <class 'float'>
>>> a=2.3e3
>>> print(a)---------------2300.0
Here True and False are the Keywords and Values for bool data type.
So that we can’t assign values to True and False.
Data Types in Python
Examples:
>>> a=True
>>> print(a,type(a))---------True <class 'bool'>
>>> b=False
>>> print(b,type(b))---------False <class 'bool'>
>>> c=true--------------NameError: name 'true' is not
defined. Did you mean: 'True'?
>>> d=false-------------NameError: name 'false' is not
defined. Did you mean: 'False'?
------------------------------------------------------
>>> True=10--------SyntaxError: cannot assign to True
>>> False=45-------SyntaxError: cannot assign to False
------------------------------------------------------
>>> print(True+True)---------------2
>>> print(True+False)--------------1
>>> print(True-False)--------------1
>>> print(2*True+3*False)----------2
>>> print(True+0b1010)-------------11
>>> print(False+True*0b1010)-------10
>>> print(True+0b1111)-------------16
>>> print(True+0o23)---------------20
>>> print(True+0xBEE)--------------3055
>>> print(True+1.1)----------------2.1
------------------------------------------------------
>>> print(True/False)-----ZeroDivisionError: division
by zero
>>> print(False/True)------0.0
The type of Real and Imaginary Parts are by-default belongs “float”.
To Extract Real Part from Complex object, we use “real” attribute /
variable of complex object.
The purpose of sequence category data type is that “To Organize or store
Sequence of Values”.
We have 4 data types in sequence category, they are:
a) str b) bytes c) byte array d) range
a) str :
Purpose of str.
Types of str.
Memory management of str.
Operations on str ----- a) Indexing b) slicing
Data Types in Python
“str” is one of the pre-defined class in sequence datatype.
The purpose of “str” data is that “To store sequence or collection of
character(s) or special symbols or digits within ‘single quotes’ or “double
quotes” or ‘’’triple single quotes ’’’ or “””triple double quotes”””.
a) Single Line String Data: Single Line String Data must be enclosed within
‘single quotes’ or “double quotes”.
Syntax: strobj= “Single line string data” or ‘Single line string data’ .
Examples:
>>> s1="Python Program"
>>> print(s1,type(s1))---Python Program <class 'str'>
>>> s2="K"
>>> print(s2,type(s2))---------K <class 'str'>
>>> s3='K'
>>> print(s3,type(s3))---------K <class 'str'>
>>> s4="$#%^&@!"
>>> print(s4,type(s4))-------- $#%^&@! <class 'str'>
>>> s5="123456"
>>> print(s5,type(s5))--------123456 <class 'str'>
Note: The single quotes and double quotes can organized or store single line
string data but unable to store multi line string data.
Invalid Examples:
-------------------------------
>>> s1="Python is an oop lang
Error Name---->SyntaxError: unterminated string
literal (detected at line 1)
>>> s2='Pythin is an oop lang
Error Name---->SyntaxError: unterminated string
literal (detected at line 1)
b) Multi Line String Data: Multi Line String Data must be enclosed within ‘’’ triple
single quotes ‘’’ or “”” triple double quotes “””. Only
Data Types in Python
Syntax: strobj= """
String Data -1
String Data -2
-------------------
-------------------
String Data -n """
(OR
Here ‘’’ triple single quotes ‘’’ or “”” triple double quotes “”” can be both
Single and Multi-lines String data.
Examples:
Examples:
>>> s="PYTHON"
>>> print(s,type(s))-----------PYTHON <class 'str'>
>>> s[0]---------------'P'
>>> s[1]---------------'Y'
>>> s[2]----------------'T'
>>> s[4]---------------'O'
>>> s[-1]---------------'N'
>>> s[-6]--------------'P'
>>> s[-2]---------------'O'
>>> s[-3]---------------'H'
>>> s[-33]---------IndexError: string index out of range
>>> s[12]----------IndexError: string index out of range
Data Types in Python
--------------------------------------------------------
>>> s="Mango"
>>> print(s[0])--------------M
>>> print(s[-1])-------------o
>>> print(s[-3])----------n
>>> print(s[2])------------n
>>> print(s[22])---IndexError: string index out of range
>>> print(s[-22])--IndexError: string index out of range.
Examples:
-------------------
>>> s="PYTHON"
>>> s[0:4]----------------'PYTH'
>>> print(s[0:4])---------PYTH
>>> print(s[4:0])------ No Output
(OR)
>>> s[4:0]-------- ' ' Indicates No Output
---------------------------------------------
>>> s="PYTHON"
>>> s[2:5]----------------'THO'
>>> s[0:5]---------------'PYTHO'
>>> s[0:3]---------------'PYT'
>>> s[4:6]----------------'ON'
>>> s[-6:-4]---------------'PY'
>>> s[-4:-1]------------------'THO'
>>> s[-5:-1]---------------'YTHO'
>>> s[-3:-5]---------------' ' Indicates No Output
--------------------------------------------------------
Special case:
-------------------------------------
>>> s="PYTHON"
>>> print(s)-------------PYTHON
>>> s[2:-2]------------'TH'
>>> s[2:-1]----------'THO'
Data Types in Python
Syntax-2: strobj [ Begin : ]
In this Syntax, we have Begin Index and not specified End Index.
Syntax give range of character from Begin Index to End Index Taken as
Len( strobj )-1.
Examples:
----------------------
>>> s="PYTHON"
>>> print(s)-----------------PYTHON
>>> s[3:]-----------------'HON'
>>> s[2:]------------------'THON'
>>> s[1:]------------------'YTHON'
>>> s[0:]------------------'PYTHON'
>>> s[-4:]-----------------'THON'
>>> s[-6:]-------------------'PYTHON'
>>> s[-2:]--------------------'ON'
In This Syntax, we have End Index and not specified Begin Index.
Syntax gives range of character from first character (initial positive Index)
to End Index -1.
Examples:
----------------
>>> s="PYTHON"
>>> s[:4]---------------------'PYTH'
>>> s[:5]--------------------'PYTHO'
>>> s[:2]-------------------'PY'
>>> s[:-4]------------------'PY'
>>> s[:-1]-------------------'PYTHO'
Syntax-4: strobj [ : ]
Note: All the above Syntaxes are Moving in Forward Direction with equal Interval.
Syntax- 5: strobj[Begin : End : step]
1) Here Begin, End and Step can be either +ve or –ve or Both.
2) If Step value is +ve then PVM takes Range of character from Begin Index to
End Index-1 in forward direction provided Begin index < End Index.
3) If step value is –ve then PVM takes Range of character from Begin Index to
End Index +1 in backward direction provided Begin Index > End Index.
4) In Forward Direction, if End Index is 0 then we never get any Output ( ‘ ’ ).
5) In backward direction, if End Index is -1 then we never get Output ( ‘ ’ )
Examples:
-----------------------
>>> s="PYTHON"
>>> s[0:5:2]----------------'PTO'
>>> s[0:6:3]----------------'PH'
>>> s[::]-------------------'PYTHON'
>>> s[::2]------------------'PTO'
>>> s[::3]------------------'PH'
>>> s[3::2]-----------------'HN'
>>> s[-6:-1:2]--------------'PTO'
>>> s[-4:-1:3]--------------'T'
>>> s="PYTHON"
>>> s[0:6:-1]---------------''
>>> s[5:2:-1]---------------'NOH'
>>> s[::-1]-----------------'NOHTYP'
>>> s[::-2]-----------------'NHY'
>>> s[-1:-6:-1]-------------'NOHTY'
>>> "PROG"[::-1]------------'GORP'
>>> "PROG"[::-1][::]--------'GORP'
>>> "PROG"[::-1][::-1]------'PROG'
Data Types in Python
>>> s="PYTHON"
>>> s[:0:-1]----------------'NOHTY'
>>> s[:0:1]----------------- ''
>>> s[:-1:-1]--------------- ''
>>> s="MADAM"
>>> s==s[::-1]-------------- True
>>> "LIRIL"=="LIRIL"[::-1]------True
Data Types in Python
The purpose of type casting techniques is that “To convert one possible
type of value into another possible types of value.
1) int(): int() is used to converting one possible type of value into “int”
type value.
Syntax: varname= int( float / bool / complex / str)
Examples:float Type Value into int Type Value-->Possible
-------------------
>>> a=10.23
>>> print(a,type(a))-----------10.23 <class 'float'>
>>> b=int(a)
>>> print(b, type(b))-----------10 <class 'int'>
--------------------------------------------------------
Examples:bool Type Value into int Type Value-->Possible
--------------------------------------------------------
>>> a=True
>>> print(a,type(a))-------------True <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------ 1 <class 'int'>
>>> a=False
>>> print(a,type(a))-------------False <class 'bool'>
>>> b=int(a)
>>> print(b, type(b))------------0 <class 'int'>
Data Types in Python
Examples : Complex Type Value into int Type Value-----
---->Not Possible
--------------------------------------------------------
>>> a=2+3j
>>> print(a,type(a))----(2+3j) <class 'complex'>
>>> b=int(a)----------TypeError: int() argument should
not be 'complex'
--------------------------------------------------------
Examples :
--------------------------------------------------------
>>> a="12" # int str into int type ------>Possible
>>> print(a,type(a))-------------12 <class 'str'>
>>> b=int(a)
>>> print(b, type(b))------------12 <class 'int'>
*********************************************
>>> a="12.34" # float str into int type --- Not Possible
>>> print(a,type(a))--------------12.34 <class 'str'>
>>> b=int(a)----ValueError: invalid literal for int()
with base 10: '12.34'
*********************************************
>>> a="True" # bool str into int type --- Not Possible
>>> print(a,type(a))-------------True <class 'str'>
>>> b=int(a)-------ValueError: invalid literal for int()
with base 10: 'True'
**************************************************
>>> a="2+3j" # complex str into int type ---- Not Possible
>>> print(a,type(a))-------------2+3j <class 'str'>
>>> b=int(a)--------ValueError: invalid literal for
int() with base 10: '2+3j'
****************************************************
>>> a="PYTHON" # Pure Str into int type --- Not Possible
>>> print(a,type(a))------------PYTHON <class 'str'>
>>> b=int(a)----------ValueError: invalid literal for
int() with base 10: 'PYTHON'
===========================================================
2) float(): float() is used to converting one possible type of value into float
type value.
Syntax: varname = float( int / bool / complex / str )
Data Types in Python
3) bool(): bool() is used to convert one possible type of value into bool
type value.
Syntax: varname= bool ( int / float / complex / str )
>>> a=-12
>>> print(a,type(a))----------- -12 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))--------------True <class 'bool'>
>>> a=0
>>> print(a,type(a))---------- 0 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))-------------False <class 'bool'>
-----------------------------------------------------
Examples: float type value into bool type-->Possible
>>> a=12.45
>>> print(a,type(a))---------12.45 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))----------True <class 'bool'>
>>> a=0.00000000000000000004
>>> print(a,type(a))-----------4e-20 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>
>>> a=0.0
>>> print(a,type(a))------------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-------------False <class 'bool'>
Data Types in Python
--------------------------------------------------------
Examples: complex type value into bool type---->Possible
--------------------------------------------------------
>>> a=2+3j
>>> print(a,type(a))---------(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))---------0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))---------False <class 'bool'>
--------------------------------------------------------
Examples:
---------
>>> a="123"
>>> print(a,type(a))---------123 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a="12.34"
>>> print(a,type(a))---------12.34 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------True <class 'bool'>
>>> a="0+j"
>>> print(a,type(a))---------0+j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a="12+3.4j"
>>> print(a,type(a))--------12+3.4j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a="False"
>>> print(a,type(a))--------False <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a="Python"
>>> print(a,type(a))--------Python <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
>>> a=" "
>>> print(a,type(a))--------<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------True <class 'bool'>
========================================================
Data Types in Python
Special Point
------------------------------------------------
>>> a=""
>>> print(a,type(a))-------<class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------False <class 'bool'>
On the object of bytes, we can perform both indexing and slicing operations.
An object of bytes belong to immutable because bytes object does not
support item assignment.
Data Types in Python
An object of bytes maintains Insertion Order (Nothing but
whichever order, we insert the data in the same order elements will be
displayed).
Examples:
-----------------------------------------------------
>>> l1=[10,20,34,0,256]
>>> print(l1,type(l1))---[10, 20, 34, 0, 256] <class 'list'>
>>> b=bytes(l1)---ValueError: bytes must be in range(0, 256)
-----------------------------------------------------
>>> l1=[10,-20,34,0,255]
>>> print(l1,type(l1))---[10, -20, 34, 0, 255] <class 'list'>
>>> b=bytes(l1)-----ValueError: bytes must be in range(0, 256)
-------------------------------------------------------
>>> l1=[10,20,34,0,255]
>>> print(l1,type(l1))---[10, 20, 34, 0, 255] <class 'list'>
>>> b=bytes(l1)
>>> print(b,type(b))---b'\n\x14"\x00\xff' <class 'bytes'>
>>> for val in b:
... print(val)
...
10
20
34
0
255
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
Examples:
-----------------
>>> r=range(20,26)
>>> print(r,type(r))---range(20, 26) <class 'range'>
>>> for i in r:
... print(i)
...
20
21
22
23
24
25
Data Types in Python
>>> for i in r[::-1]:
... print(i)
...
25
24
23
22
21
20
>>> for i in r[0:3]:
... print(i)
...
20
21
22
>>> print(r[0])--------------20
Note: The above two syntaxes are generating range of values in forward
direction with default step or interval as 1.
Syntax-3: varname= (Begin, End, Step)
This syntax generates range of values from Begin to End-1 with equal
interval value of “Step”.
Examples:
-------------------
>>> r=range(50,101,10)
>>> for i in r:
... print(i)
...
50
60
70
80
90
100
-------------------------------------------------------
Data Types in Python
>>> for i in range(10,31,5):
... print(i)
...
10
15
20
25
30
------------------------------------------------------
>>> for val in range(100,1001,100)[::-1]:
... print(val)
...
1000
900
800
700
600
500
400
300
200
100
Special Examples:
-----------------
>>> range(100,1001,100)[2]-------300
>>> range(100,1001,100)[-2]------900
===========================x===========================
Examples:
----------
Q1) 0 1 2 3 4 5 6 7 8 9------------range(10)
Q3) 20 22 24 26 28 30---------range(20,31,2)
>>> for val in range(20,31,2):
... print(val)
...
20
22
24
26
28
30
-----------------------------------------------------
The purpose of List Category of Data Type is that “To store Collections
of values or Multiples Values either of Same Type, different Type or Both of
the types with Unique and Duplicate.”
We have two data types in List Category. They are:
1) list 2) tuple
1) list: ‘list’ is one of the pre-defined class and treated as list data type.
a) empty list: Am empty list is one, which does not contain any elements
and length is 0.
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
1) Shallow Copy: In this Shallow Copy process, the following Points will satisfy:
Syntax: obj2=obj1.copy()
Examples:
----------
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))---[10, 'Rossum'] 1843503104896
>>> l2=l1.copy()
>>> print(l2,id(l2))---[10, 'Rossum'] 1843499592064
>>> l1.append("Python")
>>> l2.insert(1,"Django")
>>> print(l1,id(l1))---[10,'Rossum','Python'] 1843503104896
>>> print(l2,id(l2))---[10,'Django','Rossum'] 1843499592064
2) Deep Copy: In deep copy process, the following points will satisfy:
Examples:
---------
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))-----[10, 'Rossum'] 1843498922432
>>> l2=l1 # Deep Copy with Assignment Operator
>>> print(l2,id(l2))-----[10, 'Rossum'] 1843498922432
>>> l1.append("Python")
>>> print(l1,id(l1))---[10,'Rossum','Python'] 1843498922432
>>> print(l2,id(l2))---[10,'Rossum','Python'] 1843498922432
>>> l2.insert(2,"Django")
>>> print(l1,id(l1))--[10,'Rossum','Django','Python']
1843498922432
>>> print(l2,id(l2))--[10, 'Rossum', 'Django', 'Python']
1843498922432
1) append (): This function is used for adding the value to the list object
always at the end.
Syntax: listobj.append(value)
Examples:
----------------------
>>> l1=[]
>>> print(l1,len(l1), id(l1))-----[] 0 2722448959936
>>> l1.append(10)
>>> l1.append(10.5)
>>> print(l1,len(l1), id(l1))---[10, 10.5] 2 2722448959936
>>> l1.append("Rossum")
>>> print(l1,len(l1), id(l1))---[10, 10.5, 'Rossum']
3 2722448959936
>>> l1.append(True)
>>> print(l1,len(l1), id(l1))----
[10, 10.5, 'Rossum', True] 4 2722448959936
Data Types in Python
2) insert() : This function is used for inserting the values at valid existing
index.
Syntax: listboject. Insert (index, value)
(Here index can either +ve or –ve.)
Examples:
--------------------
>>> l2=[10,"Rossum",34.56,True]
>>> print(l2,id(l2))-----[10, 'Rossum', 34.56, True]
2722448006784
>>> l2.insert(2,"Python")
>>> print(l2,id(l2))-----[10, 'Rossum', 'Python',
34.56, True] 2722448006784
>>> l2[-2]=96.66
>>> print(l2,id(l2))-----[10, 'Rossum', 'Python',
96.66, True] 2722448006784
Syntax: listobj.clear()
Examples:
-----------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)--[100, 'Rossum', 45.56, 'Python', True]
>>> len(l1)-----5
>>> l1.clear()
>>> print(l1)-------[]
>>> len(l1)-----------0
5) pop(index): This function is used for removing the element from list
based on Index. The index can be either +ve or –ve.
Examples:
-------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)----[100, 'Rossum', 45.56, 'Python', True]
>>> del l1[2] # Index Based Removal
>>> print(l1)----[100, 'Rossum', 'Python', True]
>>> del l1[1:3] # Slicing Based Removal
>>> print(l1)----[100, True]
>>> del l1 # Removing entire object
>>> print(l1)----NameError: name 'l1' is not defined.
Data Types in Python
9) copy(): This function is used for copying the content of one object into
another object (implements Shallow Copy).
Syntax: listobj2=listobj1.copy()
Data Types in Python
Examples:
-------------------
>>> l1=[10,"Rossum"]
>>> print(l1,id(l1))---[10, 'Rossum'] 1843503104896
>>> l2=l1.copy() # shallow Copy
>>> print(l2,id(l2))---[10, 'Rossum'] 1843499592064
>>> l1.append("Python")
>>> l2.insert(1,"Django")
>>> print(l1,id(l1))--[10, 'Rossum', 'Python'] 1843503104896
>>> print(l2,id(l2))--[10, 'Django', 'Rossum'] 1843499592064
-----------------------------------------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> l2=l1[1:4] # Slice Based Copy is called Shallow Copy
>>> print(l1,id(l1))----
[100, 'Rossum', 45.56, 'Python', True] 1843499592064
>>> print(l2,id(l2))----
['Rossum', 45.56, 'Python'] 1843503104896
-----------------------------------------------------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> l2=l1[::] # Slice Based Copy is called Shallow Copy
>>> print(l1,id(l1))
[100, 'Rossum', 45.56, 'Python', True] 1843498922432
>>> print(l2,id(l2))
[100, 'Rossum', 45.56, 'Python', True] 1843499592064
11) sort(): This function is used for sorting the data in either ascending
Order or descending order.
By-default we get in ascending order.
Syntax: listobject.sort(reverse=True or False)
Data Types in Python
Examples:
--------------------
>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1)-----[10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> l1.sort() # default value of reverse=False
>>> print(l1)-----[-4, 0, 2, 3, 10, 12, 14, 34, 56]
-----------------------------------------------------
>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1)-----[10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> l1.sort(reverse=False)
>>> print(l1)-----[-4, 0, 2, 3, 10, 12, 14, 34, 56]
-----------------------------------------------------
>>> l1=[10,3,2,-4,14,12,56,0,34]
>>> print(l1)-----[10, 3, 2, -4, 14, 12, 56, 0, 34]
>>> l1.sort(reverse=True)
>>> print(l1)-----[56, 34, 14, 12, 10, 3, 2, 0, -4]
-----------------------------------------------------
Examples:
-------------------
l1=["Trump","Biden","Putin","Modi","Rossum","Adam"]
>>> print(l1)---['Trump', 'Biden', 'Putin', 'Modi',
'Rossum', 'Adam']
>>> l1.sort(reverse=False)
>>> print(l1)---['Adam', 'Biden', 'Modi', 'Putin',
'Rossum', 'Trump']
l1=["Trump","Biden","Putin","Modi","Rossum","Adam"]
>>> print(l1)---['Trump', 'Biden', 'Putin', 'Modi',
'Rossum', 'Adam']
>>> l1.sort(reverse=True)
>>> print(l1)---['Trump', 'Rossum', 'Putin', 'Modi',
'Biden', 'Adam']
----------------------------------------------------
Examples:
---------
>>> l1=[100,"Rossum",45.56,"Python",True]
>>> print(l1)------
[100, 'Rossum', 45.56, 'Python', True]
>>> l1.sort()-----TypeError: '<' not supported
between instances of 'str' and 'int'
Data Types in Python
12) extend(): This function is used for adding the content of one list
object to another list object.
Syntax: listobj1.extend(listobj2)
here listobj2 are added to listobj1
Examples:
------------------
>>> l1=[10,20,30]
>>> l2=["RS","DR","TS"]
>>> print(l1)------------[10, 20, 30]
>>> print(l2)------------['RS', 'DR', 'TS']
>>> l1.extend(l2)
>>> print(l1)---------[10, 20, 30, 'RS', 'DR', 'TS']
>>> print(l2)------------['RS', 'DR', 'TS']
Data Types in Python
The process of defining one list inside another list is called inner list /
nested list.
On the inner list, we can perform both indexing and slicing operations.
On the inner list object, we can apply all pre-defined functions of list.
2) tuple: ‘tuple’ is the one of the pre-defined class and treated as list data type.
a) empty tuple: An empty tuple is one, which does not contain any
element and its length is 0.
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
Examples:
------------------------
>>> t1=(10,20,30,40,10,10)
>>> print(t1,type(t1))------(10, 20, 30, 40, 10, 10)
<class 'tuple'>
>>> t2=(10,"Ram",34.56,True,2+4.5j)
>>> print(t2,type(t2),id(t2))---(10, 'Ram', 34.56,
True, (2+4.5j)) <class 'tuple'> 2328568492208
>>> t2[0]----------------10
>>> t2[1]------------------'Ram'
>>> t2[-1]-----------------(2+4.5j)
>>> t2[1:4]---------------------('Ram', 34.56, True)
>>> t2[2]=56.78-----------TypeError: 'tuple' object
does not support item assignment
Data Types in Python
--------------------------------------------------
>>> t1=()
>>> print(t1,len(t1))------------() 0
(OR)
>>> t2=tuple()
>>> print(t2,len(t2))------------() 0
-----------------------------------------------------
>>> l1=[10,"Rossum"]
>>> print(l1,type(l1))---[10, 'Rossum'] <class 'list'>
>>> t1=tuple(l1)
>>> print(t1,len(t1))----(10, 'Rossum') 2
-----------------------------------------------------
>>> a=10,"KVR","Python",True # wi8thout braces ( )
>>> print(a,type(a))---(10, 'KVR', 'Python', True)
<class 'tuple'>
>>> a=10,
>>> print(a,type(a))-------(10,) <class 'tuple'>
>>> a=10
>>> print(a,type(a))-------10 <class 'int'>
>>> t=tuple(a)---TypeError: 'int' object is not iterable
>>> t=tuple(a,)--TypeError: 'int' object is not iterable
>>> t=tuple((a))--TypeError: 'int' object is not iterable
>>> t=(a,) # correct conversion
>>> print(t,type(t))--------(10,) <class 'tuple'>
>>> print(a,type(a))---------10 <class 'int'>
Examples:
----------------------
>>> t1=(10,"Ram",10,"Ram","python")
>>> t1-----------(10, 'Ram', 10, 'Ram', 'python')
>>> t1.count(10)---------2
>>> t1.index("Ram")------1
Examples:
-------------------------
>>> t1=(10,"Rossum",(14,17,16),(56,34,78),"OUCET")
>>> print(t1,type(t1))---(10, 'Rossum', (14, 17, 16),
(56, 34, 78), 'OUCET') <class 'tuple'>
>>> t1[2]-----------------(14, 17, 16)
>>> t1[3]------------------(56, 34, 78)
-----------------------------------------------------
>>> t1=(10,"Rossum",[14,17,16],(56,34,78),"OUCET")
>>> print(t1,type(t1))-----(10, 'Rossum', [14, 17,
16], (56, 34, 78), 'OUCET') <class 'tuple'>
>>> t1[2]-----------------[14, 17, 16]
>>> print(t1[2],type(t1[2]))---[14, 17, 16] <class 'list'>
>>> t1[2].sort()
>>> print(t1,type(t1))-----(10, 'Rossum', [14, 16,
17], (56, 34, 78), 'OUCET') <class 'tuple'>
>>> del t1[3]--------------TypeError: 'tuple' object
doesn't support item deletion
The purpose of set Category Data type is that “To store Collection
or multiple values either of same type or different type or both the types
with unique values (No duplicates are allowed)”.
We have two data types in set category, they are:
1) set (mutable and immutable) 2) frozenset (immutable)
1) set (mutable and immutable): “set” is one of the pre-defined class and
treated as set data type.
By using set class, we have two types of set objects, they are:
a) empty set: An empty set is one, which doen not contain any elements
and whose length is 0.
To convert one type of object into set type object, we use set().
Examples:
-----------------------
>>> s1={10,20,30,40,50,10,10,20,75}
>>> print(s1,type(s1))-----------------{50, 20, 40,
10, 75, 30} <class 'set'>
>>> s1={10,20,25,35,10,20}
>>> print(s1,type(s1))-------------------{25, 10, 35,
20} <class 'set'>
>>> s1[0]----------------TypeError: 'set' object is
not subscriptable
>>> s1[0:3]--------------TypeError: 'set' object is
not subscriptable
-----------------------------------------------------
-------
>>> s1={10,20,30,40,50}
>>> print(s1,id(s1))-------------------------------
{50, 20, 40, 10, 30} 1473821509440
>>> s1[0]=100-------------TypeError: 'set' object
does not support item assignment
>>> s1.add("KVR")
>>> print(s1,id(s1))------------------{50, 20, 40,
10, 'KVR', 30} 1473821509440
-----------------------------------------------------
>>> s1=set()
>>> print(s1,type(s1))------------------{} <class
'set'>
>>> len(s1)------------0
>>> s2={10,20,30,10,20}
>>> print(s2,type(s2))---------------{10, 20, 30}
<class 'set'>
>>> len(s2)-------------------3
-----------------------------------------------------
Data Types in Python
>>> l1=[10,20,10,20,"Python",23.45]
>>> s1=set(l1)
>>> print(s1)-----------------{10, 20, 23.45,
'Python'}
>>> t1=tuple(s1)
>>> print(t1,type(t1))------------(10, 20, 23.45,
'Python') <class 'tuple'>
>>> t1=list(s1)
>>> print(t1,type(t1))------------[10, 20, 23.45,
'Python'] <class 'list'>
1) add(): This function is use for adding the elements to set object.
Examples:
----------------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))--------------{10,
'Rossum'} <class 'set'> 1473821509888
>>> s1.add("python")
>>> s1.add(34.56)
>>> print(s1,type(s1),id(s1))-------{10, 'Rossum',
34.56, 'python'} <class 'set'> 1473821509888
2) clear(): This function is use for removing all the elements from the set.
Syntax: setobj.clear()
=>Examples:
------------------------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))------------{10,
'Rossum'} <class 'set'> 1473821508992
>>> s1.clear()
>>> print(s1,type(s1),id(s1))-------------set()
<class 'set'> 1473821508992
Data Types in Python
3) remove(): This function is used for removing an element from set object.
Syntax: setobj.remove(value)
Syntax: setobj.discard(value)
If the value does not exists in setobj then we never get any error.
Examples:
----------------
>>> s1={10,"Rossum"}
>>> print(s1,type(s1),id(s1))--------------------{10,
'Rossum'} <class 'set'> 1473821509664
>>> s1.discard(10)
>>> print(s1,type(s1),id(s1))---------------
{'Rossum'} <class 'set'> 1473821509664
>>> s1.discard(100)----------No Error will come
>>> print(s1,type(s1),id(s1))---------------
{'Rossum'} <class 'set'> 1473821509664
>>> s1.discard("Rossum")
>>> print(s1,type(s1),id(s1))---------------set()
<class 'set'> 1473821509664
>>> s1.discard(100)------------No Error will come
-----------------------------------------------------
Data Types in Python
5) pop(): This function is used for removing any arbitrary element from setobj.
Syntax: setobj.pop()
Examples:
----------------------
>>> s1={10,"Rossum",23.45,"Python",True,2+3j} # No
output is shown
>>> s1.pop()------------True
>>> len(s1)----------------5
>>> s1.pop()-----------23.45
>>> len(s1)-------------4
>>> s1.pop()-------------'Python'
>>> len(s1)-------------3
>>> s1.pop()-----------10
>>> len(s1)--------------2
>>> s1.pop()------------'Rossum'
>>> len(s1)-----------1
>>> s1.pop()-----------(2+3j)
>>> len(s1)-------------0
>>> print(s1)-------------set()
>>> s1.pop()-------KeyError: 'pop from an empty set'
>>> set().pop()----KeyError: 'pop from an empty set'
>>> set().discard(10) # No Error
>>>set().remove(10)----------KeyError :10
-----------------------------------------------------
Special Note:
----------------------
>>> s2={10,20,20,30,50,"python",34.56}
>>> print(s2)---------{34.56, 50, 20, 10, 'python',
30} Output Shown
>>> s2.pop()----------34.56
>>> print(s2)-----------{50, 20, 10, 'python', 30}
>>> s2.pop()------------50
>>> print(s2)------------{20, 10, 'python', 30}
>>> s2.pop()-------------20
>>> print(s2)-------------{10, 'python', 30}
>>> s2.pop()-------------10
>>> print(s2)-------------{'python', 30}
>>> s2.pop()---------------'python'
>>> print(s2)------------{30}
>>> s2.pop()-------------30
>>> print(s2)----------------set()
>>> s2.pop()------KeyError: 'pop from an empty set'
-----------------------------------------------------
Data Types in Python
6) copy(): This function is used for copying the content of one setobject
into another set object.
7) union(): This function is used for obtaining all Unique values from setobj1
and setobj2 and placed them in setobj3.
Examples:
------------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.union(s2)
>>> print(s3)------------{40, 10, 15, 20, 25, 30}
OR
>>> s1.union(s2)-------------{40, 10, 15, 20, 25, 30}
-----------------------------------------------------
>>> s1={"Python","Django","DS"}
>>> s2={10,"Python",23.45}
>>> s3=s1.union(s2)
>>> print(s3)---{'Python', 'Django', 23.45, 10, 'DS'}
-----------------------------------------------------
Examples:
----------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.intersection(s2)
>>> print(s3)------------------{10, 20}
-----------------------------------------------------
>>> s1={"Python","Django","DS"}
>>> s2={10,"Python",23.45}
>>> s3=s1.intersection(s2)
>>> print(s3)-------------{'Python'}
>>> s1={10,20,30,40}
>>> s2={15,25,100,200}
>>> s3=s1.intersection(s2)
>>> print(s3)--------------set()
-----------------------------------------------------
Data Types in Python
This function also removes the common element from setobj2 and
setobj1 and takes remaining element from setobj2 and placed them in setobj3.
Examples:
-----------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.difference(s2)
>>>print(s3)-------------{40, 30}
--------------------------------------------------
>>> s3=s2.difference(s1)
>>> print(s3)------------{25, 15}
----------------------------------------------------
Examples:
-----------------
>>> s1={10,20,30,40}
>>> s2={15,25,10,20}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3)-----------------------{40, 15, 25, 30}
-----------------------------------------------------
>>> s4=s2.symmetric_difference(s1)
>>> print(s4)-----------------{40, 15, 25, 30}
-----------------------------------------------------
Data Types in Python
Special Examples:
-----------------------------------------
>>> tp={"Kohli","Ram","Rossum"}
>>> allcptp=cp.union(tp)
>>> print(allcptp)--------------{'Sachin', 'Ram',
'Rohit', 'Kohli', 'Rossum'}
>>> allcptp=cp|tp # Bitwise OR
>>> print(allcptp)----------------{'Sachin', 'Ram',
'Rohit', 'Kohli', 'Rossum'}
--------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp)--------------{'Kohli'}
>>> bothcptp=cp&tp # Bitwise AND
>>> print(bothcptp)---------------{'Kohli'}
-----------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> onlycp=cp.difference(tp)
>>> print(onlycp)------------------{'Sachin',
'Rohit'}
>>> onlycp=cp-tp # Arithmetic Operator -
>>> print(onlycp)------------{'Sachin', 'Rohit'}
---------------------------------------------
>>> onlytp=tp.difference(cp)
>>> print(onlytp)----------{'Ram', 'Rossum'}
>>> onlytp=tp-cp # Arithmetic Operator -
>>> print(onlytp)-----------{'Ram', 'Rossum'}
-----------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Ram","Rossum"}
>>> cptponly=cp.symmetric_difference(tp)
>>> print(cptponly)--------------{'Sachin', 'Ram',
'Rohit', 'Rossum'}
>>> cptponly=cp^tp # Bitwise XOR
>>> print(cptponly)--------------{'Sachin', 'Ram',
'Rohit', 'Rossum'}
-----------------------------------------------------
Data Types in Python
11) update(): This function updates the setobj1 values with setobj2 values.
Syntax: setobj.update(setobj2)
Examples:
>>> s1={10,20,30}
>>> s2={"python","Java","Data Science","IOT"}
>>> s3=s1.update(s2)
>>> print(s3)-------------None
>>> print(s1)---------{20, 'python', 'IOT', 10,
'Java', 30, 'Data Science'}
>>> print(s2)----------{'Java', 'python', 'IOT',
'Data Science'}
-----------------------------------------------------
>>> ur={10,"Ram"}
>>> skill={"Python","Java","IOT",10}
>>> ur.update(skill)
>>> print(ur)----{'Python', 'Ram', 'IOT', 10, 'Java'}
>>> print(skill)----{'Python', 10, 'Java', 'IOT'}
-----------------------------------------------------
The element set must be organised with curly braces { } and value
separated by comma and those value can be converted into frozenset by
using frozenset().
Syntax: frozensetobj1=frozenset(setobj)
frozensetonj1= frozenset(listobj)
frozensetobj1= frozenset(tupleobj)
Examples:
l1=[10,20,30,40,10]
fs=frozenset(l1)
print(fs,type(fs))---frozenset({40, 10, 20, 30})
<class 'frozenset'>
fs.add(100)------------AttributeError: 'frozenset'
object has no attribute 'add'
fs[0]=345------------TypeError: 'frozenset' object
does not support item assignment
-----------------------------------------------------
Examples:
-----------------------------------------------------
>>> s1={10,20,30,40}
>>> s2={15,25,30,40}
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1)-------frozenset({40, 10, 20, 30})
>>> print(fs2)-------frozenset({40, 25, 30, 15})
>>> fs3=fs1.union(fs2)
>>> print(fs3)----frozenset({40, 10, 15, 20, 25, 30})
>>> fs4=fs1.intersection(fs2)
>>> print(fs4)-------frozenset({40, 30})
>>> fs5=fs1.difference(fs2)
>>> print(fs5)-------frozenset({10, 20})
>>> fs6=fs2.difference(fs1)
>>> print(fs6)-------frozenset({25, 15})
Data Types in Python
>>> fs7=fs2.symmetric_difference(fs1)
>>> print(fs7)-------frozenset({10, 15, 20, 25})
>>> fs7=fs1.symmetric_difference(fs2)
>>> print(fs7)-------frozenset({10, 15, 20, 25})
-----------------------------------------------------
>>> s1={10,20,30,40}
>>> fs1=frozenset(s1)
>>> fs2=fs1.copy()
>>> print(fs1,id(fs1))---frozenset({40, 10, 20, 30})
2299638113984
>>> print(fs2,id(fs2))---frozenset({40, 10, 20, 30})
2299638113984
Data Types in Python
>>> cp={"sachin","rohit","kohli"}
>>> tp={"rossam","kohli","ram"}
>>> ap= cp.union(tp)
>>> print("all players=",ap)---all players= {'rohit', 'ram', 'sachin', 'rossam', 'kohli'}
>>> ct= cp.intersection(tp)
>>> print("cricket and tennis player",ct)----cricket and tennis player {'kohli'}
>>> oc= cp.difference(tp)
>>> print("only cricket player=",oc)----only cricket player= {'sachin', 'rohit'}
>>> ot= tp.difference(cp)
>>> print("only tennis player=",ot)-----only tennis player= {'ram', 'rossam'}
>>> ex= cp.symmetric_difference(tp)
>>> print("exclusive player of cricket and tennis=",ex)------
exclusive player of cricket and tennis= {'rohit', 'sachin', 'ram', 'rossam'}
Data Types in Python
The purpose of dict category data type is that “To organise the data
in the form of kyes:values”.
‘dict’ is one of the predefined class and treated as dict category data
type.
a) empty dict: An empty dict is one, which does not contains any
element and whose length is 0.
Dictobj[key1]=value1
Dictobj[key2=value2
---------------------------
Dictonj[key-n]=value-n
Data Types in Python
b) non-empty dict: A non-empty dict is one, which contains element and
whose length is >0.
Syntax: dictobj={key1:val1,key2:val2…key-n:val-n}
Here key1,key2…key-n are kyes and they are unique and they can be
either strs or numerics.
Examples:
--------------------
>>> d1={}
>>> print(d1,type(d1))-------{} <class 'dict'>
>>> len(d1)---------------0
>>> d2={10:1.2,20:2.5,30:2.5,40:4.5}
>>> print(d2,type(d2))----{10: 1.2, 20: 2.5, 30: 2.5,
40: 4.5} <class 'dict'>
>>> len(d2)------------4
-----------------------------------------------------
>>> d3=dict()
>>> print(d3,type(d3),len(d3))----{}<class 'dict'> 0
>>> d1={"Rossum":"Python","Ritche":"C",
"Gosling":"Java"}
>>> print(d1,type(d1))----{'Rossum': 'Python',
'Ritche': 'C', 'Gosling': 'Java'} <class 'dict'>
>>> d2={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d2)-----{10: 'Apple', 20: 'Mango', 30:
'Kiwi', 40: 'Sberry'}
-----------------------------------------------------
>>> print(d2[0])--------KeyError: 0
>>> print(d2[10])---------Apple
>>> print(d2[40])--------Sberry
>>> print(d2[400])--------KeyError: 400
-----------------------------------------------------
>>> d1={}
>>> print(d1,type(d1),len(d1), id(d1))----{} <class
'dict'> 0 2299637840384
>>> d1[100]="Rossum"
>>> d1[101]="Ritche"
>>> d1[102]="Travis"
>>> d1[103]="MCKinney"
Data Types in Python
>>> print(d1,type(d1),len(d1), id(d1))----{100:
'Rossum', 101: 'Ritche', 102: 'Travis', 103:'MCKinney'}
<class 'dict'> 4 2299637840384
>>> d1[100]="Guido"
>>> print(d1,type(d1),len(d1), id(d1))-----{100:
'Guido', 101: 'Ritche', 102: 'Travis',
103:'MCKinney'} <class 'dict'> 4 2299637840384
1) clear(): This function is used for removing all the elements from dict.
Syntax: dictobj.clear()
Examples:
-----------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))----------------{100: 'Rossum',
101: 'Gosling', 102: 'Ritche'} 3
>>> d1.clear()
>>> print(d1,len(d1))--------------{} 0
-----------------------------------------------------
Syntax: dictobj.pop(key)
Examples:
------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))------------------{100:
'Rossum', 101: 'Gosling', 102: 'Ritche'} 3
>>> d1.pop(100)---------------'Rossum'
>>> print(d1,len(d1))------------{101: 'Gosling',
102: 'Ritche'} 2
>>> d1.pop(101)------------'Gosling'
Data Types in Python
>>> print(d1,len(d1)-------{102: 'Ritche'} 1
>>> d1.pop(103)--------------KeyError: 103
-----------------------------------
>>> dict().pop(100)----------------KeyError: 100
>>> {}.pop(101)----------KeyError: 101
-----------------------------------------------------
Syntax: dictobj.popitem()
Examples:
------------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1,len(d1))--------------{100: 'Rossum',
101: 'Gosling', 102: 'Ritche'} 3
>>> d1.popitem()----------------(102, 'Ritche')
>>> print(d1,len(d1))-------------{100: 'Rossum',
101: 'Gosling'} 2
>>> d1.popitem()----------(101, 'Gosling')
>>> print(d1,len(d1))-----------{100: 'Rossum'} 1
>>> d1.popitem()--------------(100, 'Rossum')
>>> print(d1,len(d1))--------------{} 0
>>> d1.popitem()---------------KeyError: 'popitem():
dictionary is empty'
--------------------------------------------------------
>>> {}.popitem()---KeyError:'popitem():dictionary is empty'
>>> dict().popitem()----KeyError: 'popitem():
dictionary is empty'
4) copy(): This function copy the contain of dict object into another dict
object(Implementing as shallow copy)
Syntax: dictobj2=dictobj1.copy()
Examples:
--------------------
>>> d1={100:"Rossum",101:"Gosling"}
>>> print(d1,id(d1))---------------{100: 'Rossum',
101: 'Gosling'} 2002260856320
>>> d2=d1.copy() # shallow copy
Data Types in Python
>>> print(d2,id(d2))-----------{100: 'Rossum', 101:
'Gosling'} 2002260855808
>>> d1[110]="Travis"
>>> d2[210]="Kinney"
>>> print(d1,id(d1))---{100: 'Rossum', 101:
'Gosling', 110: 'Travis'} 2002260856320
>>> print(d2,id(d2))---{100: 'Rossum', 101:
'Gosling', 210: 'Kinney'} 2002260855808
-----------------------------------------------------
5) get(): This function is user for getting value of values by passing value
of key.
If the value of key does not exists then we get Non as resultant value.
Syntax: dictobj.get(key)
Examples:
----------------
>>> d1={100:"Rossum",101:"Gosling",102:"Ritche"}
>>> print(d1)--------------{100: 'Rossum', 101:
'Gosling', 102: 'Ritche'}
>>> d1[100]------------------'Rossum'
>>> d1[101]-----------------'Gosling'
>>> d1[102]------------------'Ritche'
>>> d1.get(100)------------'Rossum'
>>> d1.get(101)------------'Gosling'
>>> d1.get(102)-----------'Ritche'
>>> d1[103]---------------KeyError: 103
>>> d1.get(103)---------------No Result
>>> print(d1.get(103))---None--kwd--value of NoneType
-----------------------------------------------------
>>> vals=d1.values()
>>> print(vals)-------------dict_values(['Rossum',
'Gosling', 'Ritche'])
>>> for v in vals:
... print(v)
...
Rossum
Gosling
Ritche
-----------------------------------------------------
>>> kvs=d1.items()
>>> print(kvs)-----------dict_items([(100, 'Rossum'),
(101, 'Gosling'), (102, 'Ritche')])
>>> for k,v in kvs:
... print(k,"==>",v)
...
100 ==> Rossum
101 ==> Gosling
102 ==> Ritche
-----------------------------------------------------
Data Types in Python
9) update (): This function is used for updating dictobj1 values with
dictobj2 values.
Synatax: dictobj1.update(dictobj2)
Examples:
-----------------
>>> d1={10:"Python",20:"Java"}
>>> d2={30:"Django",40:"DS"}
>>> print(d1)------{10: 'Python', 20: 'Java'}
>>> print(d2)------{30: 'Django', 40: 'DS'}
>>> d1.update(d2)
>>> print(d1)-----------{10: 'Python', 20: 'Java',
30: 'Django', 40: 'DS'}
----------------------------------------------
>>> d1={10:"Python",20:"Java"}
>>> d2={10:"Django",20:"DS"}
>>> print(d1)-------------{10: 'Python', 20: 'Java'}
>>> print(d2)-------------{10: 'Django', 20: 'DS'}
>>> d1.update(d2)
>>> print(d1)------------{10: 'Django', 20: 'DS'}
-----------------------------------------------------
>>> d1={10:"Python",20:"Java"}
>>> d2={20:"Django",30:"DS"}
>>> print(d1)----------{10: 'Python', 20: 'Java'}
>>> print(d2)----------{20: 'Django', 30: 'DS'}
>>> d1.update(d2)
>>> print(d1)--{10: 'Python', 20: 'Django', 30: 'DS'}
=====================================================
Special Examples:
------------------------------
d1={1:["Python","DS","Django"],2:("Java","Servlets","
Spring"),3:{"Oracle","MySql","MongoDB"} }
>>> print(d1)------
{1: ['Python', 'DS', 'Django'], 2: ('Java',
'Servlets', 'Spring'), 3: {'MySql', 'Oracle',
'MongoDB'}}
Examples:
------------------
>>> a=None
>>> print(a,type(a))------------None <class
'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType'
is not defined
-----------------------------------------------------
Approaches to develop python program
In real time, to develop any python program, we have two approaches.
They are:
a) Interactive Mode b) Batch Mode
Examples Software’s:
Syntax2: print(messages)
This Syntax displays all values along with messages on the console.
Examples:
------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum=",c)--------------sum= 30
>>> print(c," is the sum")--------30 is the sum
>>> print('sum of ',a,' and ',b,'=',c)-------sum of
10 and 20 = 30
--------------------------------
Python program developing
>>> a=1
>>> b=2
>>> c=3
>>> d=a+b+c
>>> print("sum of ",a,",",b," and ",c,"=",d)---------
sum of 1 , 2 and 3 = 6
=====================================================
This Syntax displays all values along with messages with format() on console.
Examples:
-------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum=",c)-------------Sum= 30
>>> print("sum={}".format(c))-----sum=30
>>> print("{} is the sum".format(c))----30 is the sum
>>> print("sum of {} and {}={}".format(a,b,c))-------
sum of 10 and 20=30
>>> a=1
>>> b=2
>>> c=3
>>> d=a+b+c
>>> print("Sum of {},{} and {}={}".format(a,b,c,d))--
------Sum of 1,2 and 3=6
=====================================================
%d------------------------int value
%f-------------------------float value
%s------------------------str value
If any data type does not contain any specifier than we must convert it into str().
Python program developing
Examples:
---------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum=%d" %c)-------------------Sum=30
>>> print("Sum=%f" %c)------------Sum=30.000000
>>> print("Sum=%0.2f" %c)----------Sum=30.00
>>> print("Sum=%0.3f" %c)----------Sum=30.000
>>> print("Sum of %d and %d=%d" %(a,b,c) )--------Sum
of 10 and 20=30
>>> sno=10
>>> sname="Rossum"
>>> print("My Number is %d and Name is %s"
%(sno,sname))---My Number is 10 and Name is Rossum
-----------------------------------------------------
>>> lst=[10,"KVR","OUCET",11.11,True]
>>> print(lst)-----[10, 'KVR', 'OUCET', 11.11, True]
>>> print("List Elements=",lst)------------List
Elements= [10, 'KVR', 'OUCET', 11.11, True]
>>> print("List Elements={}".format(lst))-----List
Elements=[10, 'KVR', 'OUCET', 11.11, True]
>>> print("List Elements=%s" %str(lst) )--List
Elements=[10, 'KVR', 'OUCET', 11.11, True]
=====================================================
MiSc Examples:
-------------------------------
>>> per=98
>>> print("My Percent %d %s " %(per,"%"))---My Percent 98 %
-----------------------
>>> per="98%"
>>> print("My percent=%s" %per)------My percent=98%
-----------------------------------------------------
>>> # =====
>>> s="="
>>> s=s+s+s+s+s
>>> print(s)------------- =====
>>>
>>> print("="*5)---------- =====
>>> print("="*20)---- ====================
>>> print("*"*5)----------- *****
>>> print("#"*15)--- ###############
---------------------------------------------------
>>> lst=[10,"Ram"]
>>> print(lst*3)-----[10, 'Ram', 10, 'Ram', 10, 'Ram']
----------------------------------------------------
Python program developing
>>> print("*"*50)----
**************************************************
=======================X=============================
ASSIGNMENT-1:
WAPP TO GET AREA OF RECTANGLE:
WAY-1==============================================
print("Enter Length:")
l=input()
print(l, type(l))
print("Enter Breadth:")
b=input()
print(b, type(b))
#conver l and b value into float
length=float(l)
breadth=float(b)
#calculate area of rect
ar=length*breadth
print("Area of Rect=",ar)
WAY-2=================================================
WAY-3==================================================
print("Enter Length and Breadth:")
length=float(input())
breadth=float(input())
#calculate area of rect
ar=length*breadth
print("Area of Rect=",ar)
WAY-4==========================================================
print("Enter Length and Breadth:")
ar=float(input())*float(input())
print("Area of Rect=",ar)
Python program developing
WAY-5================================================
print("Enter Length and Breadth:")
print("Area of Rect=",float(input())*float(input()))
WAY-6================================================
print("Area of Rect=",float(input("Enter Length:"))*
float(input("Enter Breadth:")))
WAY-7================================================
#program for cal area of rect
length=12
breadth=23
ar=length*breadth
print("="*50)
print("Area of Rect")
print("="*50)
print("Length={}".format(length))
print("Breadth={}".format(breadth))
print("Area of Rect={}".format(ar))
print("="*50)
==================================X================================
1) input(): This function is used for reading any type of data from keyboard
in the form of str only.
Syntax: varname=input()
(OR)
(OR)
2) input(message): This function is used for reading any type values from
keyboard in the form of str type additionally with this function we can
give user-prompting message.
Programmatically, to convert str type into other type, we use type-
casting techniques.
Python program developing
Syntax: varname= input(message)
Examples:
------------------------------
r=float(input("Enter Radious:"))
ac=3.14*r*r
pc=2*3.14*r
print("Area of Circle={}".format(ac))
print("Perimeter of Circle=%0.2f" %pc)
=====================================================
# Program for accepting Length and Breadth and find
area of rectangle
#DataRead1.py
-----------------------------------------------------
l=input("Enter Length:")
b=input("Enter breadth:")
print(l, type(l))
print(b, type(b))
#convert l and b into float
length=float(l)
breadth=float(b)
area=length*breadth
print("Area of Rect={}".format(area))
=================================================================
# Program for accepting Length and Breadth and find
area of rectangle
#DataRead2.py
-----------------------------------------------------
l=float(input("Enter Length:"))
b=float(input("Enter breadth:"))
area=l*b
print("Area of Rect=",area)
=================================================================
#program for cal simple intrest
#simpleint.py
-----------------------------------------------------
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
Python program developing
#calculate si
si=(p*t*r)/100
totamt=p+si
#display the result
print("="*50)
print("\tSimple Interest Calculations:")
print("="*50)
print("\tPrinciple Amount:{}".format(p))
print("\tTime:{}".format(t))
print("\tRate of Interest:{}".format(r))
print("\tSimple Interest:{}".format(si))
print("\tTotal Amount to pay:{}".format(totamt))
print("="*50)
===========================================================
Opertors and Expressions in Python
Opertors and Expressions in Python
==============================================================
SLNO Symbol Meaning Examples a=10 b=3
==============================================================
1. + Addition print(a+b)------ 13
2. - Substraction print(a-b)-------- 7
3. * Multiplication print(a*b)------- 30
4. / Division print(a/b)---3.3333333333333335
(float Quotient)
5. // Floor Division print(a//b)------ 3
(Integer Quotient)
6. % Modulo Division print(a%b)----1
7. ** Exponentiation print(a**b)---1000
==============================================================
#Special Case
----------------
>>> a=100
>>> b=30
>>> print(a/b)--------------3.3333333333333335
>>> print(a//b)-------------3
-----------------------------------------------------
>>> a=100.0
>>> b=30.0
>>> print(a/b)--------------3.3333333333333335
>>> print(a//b)----------- 3.0
=====================================================
#Program for demonstrating Arithmetic Operators
#aop.py
-----------------------------------------------------
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("-"*50)
print("\tArithmetic Operators and Results")
print("-"*50)
print("\tsum({},{})={}".format(a,b,a+b) )
print("\tsub({},{})={}".format(a,b,a-b))
print("\tmul({},{})={}".format(a,b,a*b))
print("\tDiv({},{})={}".format(a,b,a/b))
print("\tFloor Div({},{})={}".format(a,b,a//b))
print("\tMod Div({},{})={}".format(a,b,a%b))
print("\tExpo({},{})={}".format(a,b,a**b))
print("-"*50)
================================================================
Opertors and Expressions in Python
#program for cal square root of a given number
#sqroot.py
-----------------------------------------------------
n=int(input("Enter a number:"))
res=n**0.5
print("squareroot({})={}".format(n,round(res,3)))
print("-------------OR-------------")
print("squareroot(%d)=%0.3f" %(n,res))
================================================================
#program for cal square root of a given number
#sqroot1.py
-----------------------------------------------------
n=int(input("Enter a number:"))
res=n**0.5
print("squareroot({})={}".format(n,res))
print("-------------OR-------------")
print("squareroot(%d)=%s" %(n,str(res)))
========================================================
Ass-2
---------
1) WAPP to calculate the area of Rectangle:
-------------------------------------------------------------------------------------------
print("\tArea of Rectangle is:",float(input("\tEnter the Length of
Rectangle:")) * float(input("\tEnter the Length of Rectangle:")))
========================================================
2) WAPP to calculate simple interest calculation and total Amount payable.
-------------------------------------------------------------------------------------------
p=float(input("Emter the Principle Amount:"))
r=float(input("Enter the Rate of Intrest:"))
t=float(input("Enter the Time Period:"))
print("Payable Amount:",((p*r*t)/100)+p)
========================================================
3) WAPP to calculate the circumference of circle.
-------------------------------------------------------------------------------------------
print("Circumference of Circle is:",(float(input("Enter the Radious of
Circle:")))*2*3.14)
========================================================
Opertors and Expressions in Python
4) WAPP to calculate the area of circle.
-------------------------------------------------------------------------------------------
r=float(input("Enter the Radious of Circle:"))
print("Area of Circle is:",(r**2)*3.14)
========================================================
5) WAPP to calculate area of triangle.
-------------------------------------------------------------------------------------------
print("The Area of Triangle is:",(float(input("Enter the base of
Triangle:"))*float(input("Enter the height of Triangle:")))*0.5)
========================================================
6) WAPP to calculate the sqrt of a user input number.
------------------------------------------------------------------------------------------
print("SQRT of Given Number is:",float(input("Enter the number to
find SQRT:"))**0.5)
========================================================
7) WAPP to calculate the cube root of user input number.
-------------------------------------------------------------------------------------------
print("SQRT of Given Number is:",float(input("Enter the number to
find SQRT:"))**(1/3))
========================================================
Opertors and Expressions in Python
=========================X===========================
Opertors and Expressions in Python
Opertors and Expressions in Python
Opertors and Expressions in Python
2) Assignment Operator: The purpose of assignment is that “To assign or
transfer Right Hand Side (RHS) Value / Expression Value to the Left Hand
Side (LHS) Variable”.
The symbol for Assignment Operator is single equal to ( = ).
In Python Programming, we use Assignment Operator in two ways:
With Single line assignment at a time we can assign one RHS Value or
Expression to the single LHS Variable Name.
Examples:
-----------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)------------10 20 30
-----------------------------------------------------
Examples:
-------------------
>>> a,b=10,20
>>> print(a,b)------------10 20
>>> c,d,e=a+b,a-b,a*b
>>> print(c,d,e)-------------30 -10 200
=========================X===========================
Opertors and Expressions in Python
#Program for swapping of any two values by using
Multi line assignment
=====================================================
#Swap.py
-----------------------------------------------------
a,b=input("Enter Value of a:"),input("Enter Value of b:")
print("="*40)
print("Original Value of a={}".format(a))
print("Original Value of b={}".format(b))
print("="*40)
#swapping Logic
a,b=b,a # Multi line assigment.
print("Swapped Value of a={}".format(a))
print("Swapped Value of b={}".format(b))
print("="*40)
====================================================
3) Relational Operators: The purpose of relational Operators is that “To
Compare Two or More Values”.
If two or more object or variables connected with Relational Operators
then it is called relational Expression.
Relational Expression is also called Test Condition and the result of
Relational Expression is either True or False.
In Python Programming, we have 6 relational operators and they are
given in the following table.
=====================================================
SLNO Symbol Meaning Example
=====================================================
1. > greater than print(100>20)-----True
print(100>200)----False
2. < Less than print(100<20)------False
print(100<200)-----True
3. == Equality print(10==10)------True
(Double Equal to) print(10==5)-------False
4. != Not Equal to print(10!=4)------True
print(10!=10)-----False
5. >= greater than print(10>=2)------True
or equal to print(10>=20)-----False
6. <= Less than print(10<=20)----True
or equal to print(10<=2)------False
=====================================================
Opertors and Expressions in Python
#relational Operators Functionality
-----------------------------------------------------
a=float(input("Enter Value of a:"))
b=float(input("Enter Value of b:"))
print("-"*50)
print("\tResult of Relational Operators")
print("-"*50)
print("\t {} > {} = {}".format(a,b,a>b))
print("\n\t {} < {} = {}".format(a,b,a<b))
print("\n\t {} == {} = {}".format(a,b,a==b))
print("\n\t {} != {} = {}".format(a,b,a!=b))
print("\n\t {} >= {} = {}".format(a,b,a>=b))
print("\n\t {} <= {} = {}".format(a,b,a<=b))
print("-"*50)
================================================================
#Python Ternary Operator
-----------------------------------------------------
a=int(input("Enter Value of a:")) # a=100
b=int(input("Enter Value of b:")) # b=30
result= a if a>b else b
print("Big({},{})={}".format(a,b,result))
================================================================
#Python Ternary Operator
-----------------------------------------------------
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:")) # b=10
result="BOTH VALUES ARE EQUAL" if (a==b) else a if
(a>b) else b
print("Big({},{})={}".format(a,b,result))
print("--------------------------------------")
result="BOTH VALUES ARE EQUAL" if (a==b) else a if
(a<b) else b
print("small({},{})={}".format(a,b,result))
==========================X=============================
Opertors and Expressions in Python
Ass-3
======
1) WAPP which accept any two values and interchange them or swap
them by using multiline assignment operator.
------------------------------------------------------------------------------------------
a=int(input("Enter first Value A="))
b=int(input("Enter secound Value B="))
a,b=b,a
print("swaped values of A=",a)
print("swaped values of B=",b)
========================================================
2) WAPP which will accept two values and find the biggest/smallest or
equal number among them.
------------------------------------------------------------------------------------------
a=int(input("Enter first Value:"))
b=int(input("Enter secound Value:"))
print("="*40)
res="Both values are Equal" if (a==b) else a if (a>b) else b
print("Biggest among them:",res)
print("="*40)
reslt="Both Values are Equal" if (a==b) else a if (a<b) else b
print("Smallest among them:",reslt)
print("="*40)
========================================================
.
Opertors and Expressions in Python
True False
=====================================================
Opertors and Expressions in Python
Examples:
----------------
>>> a=10
>>> b=20
>>> a==b-----------False
>>> not(a==b)-----------True
>>> print( not (10==2 or 20==3 or 5>=50))------True
---------------------------------------------------
>>> a=True
>>> not a-------------False
>>> not False-----------True
-----------------------------------------------------
Special Examples:
------------------
>>> 100>20 and 100>40---------------True
>>> 100>20 or 100>40-----------True
=====================================================
>>> 100 and -100---------- -100
>>> 100 and 0-------------- 0
>>> -100 and -225--------- -225
>>> 0 and 100-------------- 0
>>> 100 and -1234567------- -1234567
>>> 100 and 0------------- 0
>>> 0 and 345----------- 0
>>> 0 and 0--------------- 0
>>> 100 or 200-------------- 100
>>> -100 or -223----------- -100
>>> 0 or -223------------ -223
>>> 0 or 0----------------- 0
>>> not (0 or 0)------------- True
===========================X========================
Opertors and Expressions in Python
2) not in operator: The “not in” operator returns True provided “value”
not present in Iterable object. And also returns False if value present in
the iterable object.
Syntax: value not in Iterable_object
Opertors and Expressions in Python
Examples:
-----------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))
PYTHON <class 'str'>
>>> "P" in s
True
>>> "O" in s
True
>>> "o" in s
False
>>> s="PYTHON"
>>> "T" in s
True
>>> "T" not in s
False
>>> "t" not in s
True
>>> "K" not in s
True
>>> s="PYTHON"
>>> "PY" in s
True
>>> "PYTH" in s
True
>>> "PYTH" not in s
False
>>> "PYT" not in s
False
>>> "PYTHO" not in s
False
>>> "PYTHO" in s
True
>>> s="PYTHON"
>>> "PYO" not in s
True
>>> "PYN" not in s
True
>>> "PYN" in s
False
>>> "HON" in s
True
>>> "NOH" not in s
True
Opertors and Expressions in Python
1) is : “is” operator returns True when obj1 and obj2 contains same
memory address. And also returns False when obj1 and obj2
contains different memory address.
2) is not: “is not” operator returns True when obj1 and obj2 contains
different memory address. And also returns False when obj1
and obj2 contains same memory address.
Examples:
-----------------------
>>> a=None
>>> b=None
>>> print(a,type(a),id(a))---------None <class
'NoneType'> 140709278021624
>>> print(b,type(b),id(b))-------None <class
'NoneType'> 140709278021624
>>> a is b----------True
>>> a is not b---------False
----------------------------------------------------
>>> d1={10:"Apple",20:"Mango"}
>>> d2={10:"Apple",20:"Mango"}
>>> print(d1,type(d1),id(d1))---{10: 'Apple', 20:
'Mango'} <class 'dict'> 1872666607552
>>> print(d2,type(d2),id(d2))---{10: 'Apple', 20:
'Mango'} <class 'dict'> 1872666640512
>>> d1 is d2---------False
>>> d1 is not d2---True
-----------------------------------------------------
Opertors and Expressions in Python
>>> s1={10,20,30}
>>> s2={10,20,30}
>>> print(s1,type(s1),id(s1))---{10, 20, 30} <class
'set'> 1872670853824
>>> print(s2,type(s2),id(s2))---{10, 20, 30} <class
'set'> 1872670854272
>>> s1 is s2-------False
>>> s1 is not s2---True
-------------------
>>> fs1=frozenset({10,20})
>>> fs2=frozenset({10,20})
>>> print(fs1,type(fs1),id(fs1))
frozenset({10, 20}) <class 'frozenset'> 1872670855616
>>> print(fs2,type(fs2),id(fs2))
frozenset({10, 20}) <class 'frozenset'> 1872670854496
>>> fs1 is fs2
False
>>> fs1 is not fs2
True
-----------------------------------------------------
>>> l1=[10,"KVR"]
>>> l2=[10,"KVR"]
>>> print(l1,type(l1),id(l1))
[10, 'KVR'] <class 'list'> 1872666654784
>>> print(l2,type(l2),id(l2))
[10, 'KVR'] <class 'list'> 1872667375104
>>> l1 is l2
False
>>> l1 is not l2
True
-----------
>>> t1=(10,0)
>>> t2=(10,0)
>>> print(t1,type(t1),id(t1))
(10, 0) <class 'tuple'> 1872667061632
>>> print(t2,type(t2),id(t2))
(10, 0) <class 'tuple'> 1872667278336
>>> t1 is t2
False
>>> t1 is not t2
True
-----------------------------------------------------
Opertors and Expressions in Python
>>> r1=range(10,21)
>>> r2=range(10,21)
>>> print(r1,type(r1),id(r1))
range(10, 21) <class 'range'> 1872666787392
>>> print(r2,type(r2),id(r2))
range(10, 21) <class 'range'> 1872666787344
>>> r1 is r2
False
>>> r1 is not r2
True
-----------------------------------------------
>>> ba1=bytearray([10,20])
>>> ba2=bytearray([10,20])
>>> print(ba1,type(ba1),id(ba1))
bytearray(b'\n\x14') <class 'bytearray'>
1872670887088
>>> print(ba2,type(ba2),id(ba2))
bytearray(b'\n\x14') <class 'bytearray'>
1872670887536
>>> ba1 is ba2
False
>>> ba1 is not ba2
True
-----------------------
>>> b1=bytes((10,20))
>>> b2=bytes((10,20))
>>> print(b1,type(b1),id(b1))
b'\n\x14' <class 'bytes'> 1872666783360
>>> print(b2,type(b2),id(b2))
b'\n\x14' <class 'bytes'> 1872666781008
>>> b1 is b2
False
>>> b1 is not b2
True
-----------------------------------------------------
"Same String data with Same Case, Meaning and Order then they are
treated as String Constant and they contains Same Memory Address
otherwise we get Different Address".
>>> s1="INDIA"
>>> s2="INDIA"
>>> print(s1,type(s1),id(s1))
INDIA <class 'str'> 1872670887728
>>> print(s2,type(s2),id(s2))
Opertors and Expressions in Python
INDIA <class 'str'> 1872670887728
>>> s1 is s2
True
>>> s1 is not s2
False
>>> s1="INDIA"
>>> s2="INDIa"
>>> print(s1,type(s1),id(s1))
INDIA <class 'str'> 1872670887728
>>> print(s2,type(s2),id(s2))
INDIa <class 'str'> 1872670887600
>>> s1 is s2
False
>>> s1 is not s2
True
-----------------------------------------------------
>>> a=2+3j
>>> b=2+3j
>>> print(a,type(a), id(a))
(2+3j) <class 'complex'> 1872662488464
>>> print(b,type(b), id(b))
(2+3j) <class 'complex'> 1872662488304
>>> a is b
False
>>> a is not b
True
-----------------------------------------------------
>>> a=True
>>> b=True
>>> print(a,type(a), id(a))
True <class 'bool'> 140709277969256
>>> print(b,type(b), id(b))
True <class 'bool'> 140709277969256
>>> a is b
True
>>> a is not b
False
---------------------------------------
>>> a=True
>>> b=False
>>> print(a,type(a), id(a))
True <class 'bool'> 140709277969256
>>> print(b,type(b), id(b))
False <class 'bool'> 140709277969288
>>> a is b------------------ False
>>> a is not b------------- True
Opertors and Expressions in Python
-----------------------------------------------------
>>> a=1.2
>>> b=1.2
>>> print(a,type(a), id(a))
1.2 <class 'float'> 1872662481552
>>> print(b,type(b), id(b))
1.2 <class 'float'> 1872662485456
>>> a is b
False
>>> a is not b
True
---------------------------------------------------
Most Important:
---------------------------
1) 0 to 256 in multiple objects of int type contains same memory address.
2) More Than 256 in multiple objects of int type contains different
memory address
3) -1 to -5 in multiple objects of int type contains same memory address
4) Less than -5 in multiple objects of int type contains different
memory address
-----------------------------------------------------
>>> a=10
>>> b=10
>>> print(a,type(a), id(a))
10 <class 'int'> 1872661447184
>>> print(b,type(b), id(b))
10 <class 'int'> 1872661447184
>>> a is b
True
>>> a is not b
False
>>> a=256
>>> b=256
>>> print(a,type(a), id(a))
256 <class 'int'> 1872661455056
>>> print(b,type(b), id(b))
256 <class 'int'> 1872661455056
>>> a is b
True
>>> a is not b
False
>>> a=257
>>> b=257
>>> print(a,type(a), id(a))
Opertors and Expressions in Python
257 <class 'int'> 1872662488464
>>> a is not b
False
>>> a,b=30000,30000
>>> print(a,type(a), id(a))
30000 <class 'int'> 1872662484944
>>> print(b,type(b), id(b))
30000 <class 'int'> 1872662484944
>>> a is b
True
>>> a is not b
False
>>> a,b=3,4
>>> print(a,type(a), id(a))
3 <class 'int'> 1872661446960
>>> print(b,type(b), id(b))
4 <class 'int'> 1872661446992
>>> a is b
False
>>> a is b
False
------------------------------------------------
>>> a,b=-10,-10
>>> print(a,type(a), id(a))
-10 <class 'int'> 1872662484944
>>> print(b,type(b), id(b))
-10 <class 'int'> 1872662484944
>>> a is b
True
>>> a is not b
False
============================================
>>> a=1.5
>>> b=1.5
>>> print(a,type(a), id(a))
1.5 <class 'float'> 1872662481552
>>> print(b,type(b), id(b))
1.5 <class 'float'> 1872662485840
>>> print("%0.20f" %a)
1.50000000000000000000
>>> print("%0.60f" %a)
1.500000000000000000000000000000000000000000000000000
000000000
>>> a is b
False
>>> a is not b
Opertors and Expressions in Python
True
>>> a,b=1.2,1.2
>>> print(a,type(a), id(a))
1.2 <class 'float'> 1872662485232
>>> print(b,type(b), id(b))
1.2 <class 'float'> 1872662485232
>>> a is b
True
>>> a is not b
False
>>> a,b=2+3j,2+3j
>>> print(a,type(a), id(a))
(2+3j) <class 'complex'> 1872662488464
>>> print(b,type(b), id(b))
(2+3j) <class 'complex'> 1872662488464
>>> a is b
True
>>> a is not b
False
==========================X==========================
Flow Control Statements in Python (OR)
Control Structures in Python
The purpose of Flow Control Statements in Python is that “To perform
Certain Operation only once (Perform X-Operation in the case of True or
Y-Operation in the case of False) OR Perform Certain Operation
Repeatedly for finite number of time until Test Condition Become False.”
========================================================
#This Program find biggest of three nums.
-----------------------------------------
a=int(input("Enter Value of a:"))# a=100
b=int(input("Enter Value of b:")) # b=200
c=int(input("Enter Value of c:")) # c=300
#biggest logic
if(c<a>b):
print("big({},{},{})={}".format(a,b,c,a))
if(a<b>c):
print("big({},{},{})={}".format(a, b, c, b))
if(a<c>b ):
print("big({},{},{})={}".format(a, b, c, c))
if(a==b==c):
print("ALL VALUES ARE EQUAL")
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
#program for finding biggest among 3 numbers
---------------------------------------------
#bigex3.py
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:"))#b=10
c=int(input("Enter Value of c:"))# c=10
#biggest logic
if (a>b and a>c):
print("big({},{},{})={}".format(a,b,c,a))
else:
if(b>a and b>c):
print("big({},{},{})={}".format(a,b,c,b))
else:
if(a<c>b):
print("big({},{},{})={}".format(a,b,c,c))
else:
print("ALL VALUES ARE EQUAL:")
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
#Program for accepting a digit and print its name
--------------------------------------------------
d=int(input("Enter a Digit:"))#d --> 0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is ZERO".format(d))
else:
if(d==1):
print("{} is ONE".format(d))
else:
if(d==2):
print("{} is TWO".format(d))
else:
if(d==3):
print("{} is THREE".format(d))
else:
if(d==4):
print("{} is FOUR".format(d))
else:
if(d==6):
print("{} is SIX".format(d))
else:
if(d==5):
print("{} is FIVE".format(d))
else:
if(d==7):
print("{} is SEVEN".format(d))
else:
if(d==8):
print("{} is EIGHT".format(d))
else:
if(d==9):
print("{} is NINE".format(d))
else:
print("{} is
number:".format(d))
=====================================================
Flow Control Statements in Python (OR)
Control Structures in Python
#Program for accepting a digit and print its name
---------------------------------------------------
d=int(input("Enter a Digit:")) # d----> 0 1 2
3 4 5 6 7 8 9
if d in range(0,10):
print("{} is a digit:".format(d))
else:
print("{} is a number:".format(d))
========================================================
#Program for accepting a digit and print its name
--------------------------------------------------
d1={1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SI
X",7:"SEVEN",8:"EIGHT",9:"NINE",0:"ZERO"}
dig=int(input("Enter a Digit:"))
res=d1.get(dig)
if(res!=None):
print("{} is {}".format(dig,res))
else:
print("{} is a number:".format(dig))
=======================================
#program for deciding even or odd
----------------------------------
n=int(input("Enter a number:"))
if(n%2==0):
print("{} is EVEN".format(n))
if (n%2!=0):
print("{} is ODD".format(n))
=======================================
#Program for accepting a number and decides whether
it is even or odd
---------------------------------------------------
n=int(input("Enter a number:"))
if(n%2==0):
print("{} is EVEN:".format(n))
else:
print("{} is ODD" .format(n))
print("Program execution Completed:")
=======================================
Flow Control Statements in Python (OR)
Control Structures in Python
Pictorial Explanation of if else Statement:
case 7:
print("Thnaks for using this program")
exit()
case _: # default case block
print("Ur Selection of Operations is wrong")
To deal with any looping statements, we have to follow 3-steps. They are:
1. Initialization part
2. Conditional part
3. Updation part(Incrimination or Decrimination)
========================================================
1. Program for generating 1 to n numbers where n is +ve.
--------------------------------------------------------
n=int(input("Enter Value of n:")) # n= 5
if(n<=0):
print("{} is invalid input".format(n))
else:
print("="*50)
print("Numbers within {}".format(n))
print("="*50)
i=1 # Initlization part
while(i<=n): # Cond Part
print("\t{}".format(i))
i=i+1 # Updation Part
print("="*50)
print("\nProgram execution completed:")
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
Syntax1:-
-----------
for varname in Iterable_object:
--------------------------------
Indentation block of stmts
--------------------------------
-------------------------------------
Other statements in Program
-------------------------------------
---------------
Syntax2:
---------------
for varname in Iterable_object:
--------------------------------
Indentation block of stmts
--------------------------------
else:
--------------------------------
else block of statements
--------------------------------
-------------------------------------
Other statements in Program
-------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
Explanation:
Here 'for' and 'else' are keywords.
Here Iterable_object can be Sequence (bytes, bytearray, range, str),
List (list, tuple), set (set, frozenset) and dict.
The execution process of for loop is that "Each of Element of
Iterable_object selected, placed in varname and executes Indentation
block of statements". This Process will be repeated until all elements of
Iterable_object completed.
After execution of Indentation block of statements, PVM executes
else block of statements which are written under else block and later
PVM executes other statements in Program.
Writing else block is optional.
===========================================================
1. WAPP to generate 1 to n numbers where n is +ve integer.
------------------------------------------------------------------------------------------------
n=int(input("Enter Value of n:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
for i in range(1,n+1):
print("\t{}".format(i))
else:
print("i am from else block")
print("Program execution completed")
===========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
n=int(input("Enter a number:"))
if(n<0):
print(" factorial not defined for negative values")
else:
k=1
for i in range(1,n+1):
k=k*i
else:
print("Factorial({})={}".format(n,k))
print("===============OR=====================")
k=1
t=n
while(n>0):
k=k*n
n=n-1
else:
print("Factorial({})={}".format(t,k))
========================================================
9. Program to deciding whether the given number or name is palindrome
or no
-----------------------------------------------------------------------
val=input("Enter a Number or Word:")
if(val==val[::-1]):
print("Given Number or word is Palindrome")
else:
print("Given Number or word is not Palindrome")
========================================================
10. Program for converting Ordinary Number into Roman Eqv.
------------------------------------------------------------------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
n=int(input("Enter a number:"))
if(n<=0):
print("No Roman Number:")
else:
while(n>=1000):
print("M",end="")
n=n-1000
if(n>=900):
print("CM",end="")
n=n-900
if(n>=500):
print("D",end="")
n=n-500
if(n>=400):
print("CD",end="")
n=n-400
while(n>=100):
print("C",end="")
n=n-100
if(n>=90):
print("XC",end="")
n=n-90
if(n>=50):
print("L",end="")
n=n-50
if(n>=40):
print("XL",end="")
n=n-40
while(n>=10):
print("X",end="")
Flow Control Statements in Python (OR)
Control Structures in Python
n=n-10
if(n>=9):
print("IX",end="")
n=n-9
if(n>=5):
print("V",end="")
n=n-5
if(n>=4):
print("IV",end="")
n=n-4
while(n>=1):
print("I",end="")
n=n-
=========================x=======================
break statement
Syntax2:
---------
while(Test Cond-1):
------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
if (test cond-2):
break
------------------------------
------------------------------
===========================x===========================
continue statement
continue is a keyword.
continue statement is used for making the PVM to go to the top of the
loop without executing the following statements which are written after
continue statement for that current Iteration only.
continue statement to be used always inside of loops.
When we use continue statement inside of loop then else part of
corresponding loop also executes provided loop condition becomes false.
Syntax:-
----------
for varname in Iterable-object:
------------------------------------
if ( Test Cond):
continue
statement-1 # written after
continue statement
statement-2
statement-n
-------------------------------------
------------------------------------
Syntax:-
----------
Flow Control Statements in Python (OR)
Control Structures in Python
while (Test Cond):
-------------------------------
if ( Test Cond):
continue
statement-1 # written after
continue stateemnt
statement-2
statement-n
-------------------------------------
-------------------------------------
========================X============================
========================================================
5. Program for deciding whether the number is prime or not.
------------------------------------------------------------------------------------------------
n=int(input("Enter a number:")) #n=5
if(n<=1):
print("{} is invalid input ".format(n))
else:
result="prime"
for i in range(2,n):
if(n%i==0):
result="notprime" # for not prime
break
if(result=="prime"):
Flow Control Statements in Python (OR)
Control Structures in Python
print("{} is a prime".format(n))
else:
print("{} is not a prime".format(n))
=====================================================
------------------------------------------
Other statements in Program
-----------------------------------------
================================================================
Syntax2: (while loop in while loop)
-----------------
-------------------------------------
while(Test Cond1): # Outer while loop
Flow Control Statements in Python (OR)
Control Structures in Python
--------------------------------------
--------------------------------------
while(Tesd Cond2): #Inner while loop
---------------------------------
---------------------------------
else:
--------------------------------
else:
--------------------------------------
-------------------------------------------
Other statements in Program
-------------------------------------------
================================================================
=============================X==================================
Flow Control Statements in Python (OR)
Control Structures in Python
1. Program for demonstrating inner or nested loop --- for loop in for
loop
#innerloopex1.py
-------------------------------------------------------------------------------------------
for i in range(1,6):
print("Value of i--outer for loop:{}".format(i))
print("-"*40)
for j in range(1,4):
print("\tValue of j--inner for loop:{}".format(j))
else:
print("Out of inner for loop")
print("-"*40)
else:
print("Out of outer for loop")
print("-"*40)
print("\n Program Execution Completed!")
"""
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex1.py
Value of i--outer for loop:1
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:2
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:3
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:4
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:5
----------------------------------------
Value of j--inner for loop:1
Flow Control Statements in Python (OR)
Control Structures in Python
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Out of outer for loop
----------------------------------------
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex1.py
Value of i--outer for loop:1
----------------------------------------
Value of j--inner for loop:1
Value of j--inner for loop:2
Value of j--inner for loop:3
Out of inner for loop
----------------------------------------
Value of i--outer for loop:2
----------------------------------------
========================================================
Flow Control Statements in Python (OR)
Control Structures in Python
2. Program for demonstrating inner or nested loop --- while loop in
while loop
#innerloopex2.py
--------------------------------------------------------------------------------------------
i=1 # Initlization for outer while loop
while(i<6):
print("Value of i--outer while loop:{}".format(i))
print("-"*40)
j=1 # Initlization for inner while loop
while(j<=3):
print("\tValue of j--inner while
loop:{}".format(j))
j=j+1 # Updation for inner while loop
else:
i=i+1 # Updation for outer while loop
print("Out of inner while loop")
print("-"*40)
else:
print("Out of outer while loop")
print("-"*40)
print("\n Program Execution Completed!")
"""
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex2.py
Value of i--outer while loop:1
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Value of i--outer while loop:2
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Value of i--outer while loop:3
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Value of i--outer while loop:4
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Flow Control Statements in Python (OR)
Control Structures in Python
Out of inner while loop
----------------------------------------
Value of i--outer while loop:5
----------------------------------------
Value of j--inner while loop:1
Value of j--inner while loop:2
Value of j--inner while loop:3
Out of inner while loop
----------------------------------------
Out of outerwhile loop
----------------------------------------
========================================================
3. Program for demonstrating inner or nested loop --- while loop in for
loop
#innerloopex3.py
------------------------------------------------------------------------------------------
for i in range(5,0,-1):
print("Value of i--outer for loop:{}".format(i))
print("-"*40)
j=3
while(j>=1):
print("\tValue of j--inner while
loop:{}".format(j))
j=j-1
else:
print("Out of inner while loop")
print("-"*40)
else:
print("Out of outer for loop")
print("-"*40)
print("\n Program Execution Completed!")
"""
E:\KVR-PYTHON-6PM\LOOPS>py innerloopex3.py
Value of i--outer for loop:5
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:4
----------------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:3
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:2
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Value of i--outer for loop:1
----------------------------------------
Value of j--inner while loop:3
Value of j--inner while loop:2
Value of j--inner while loop:1
Out of inner while loop
----------------------------------------
Out of outer for loop
----------------------------------------
Program Execution Completed!
"""
==============================================================
4. Program for demonstrating inner or nested loop --- for loop in while
loop
#innerloopex4.py
------------------------------------------------------------------------------------------
i=1 # Initlization for outer while loop
while(i<6):
print("Value of i--outer while
loop:{}".format(i))
print("-"*40)
for j in range(3,0,-1):
print("\tValue of j--inner for
loop:{}".format(j))
else:
i=i+1 # Updation for outer while loop
print("Out of inner for loop")
print("-"*40)
Flow Control Statements in Python (OR)
Control Structures in Python
else:
print("Out of outer while loop")
print("-"*40)
print("\n Program Execution Completed!")
=====================================================
5. Program for accepting list of value and generate mul tables for all
+ve numbers
#multables.py
-------------------------------------------------------------------------------------------
n=int(input("Enter How many mul tables u want to
generate:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
# accept 'n' number of values in list
lst=[] # create empty list
for i in range(1,n+1):
val=int(input("Enter {}Value:".format(i)))
lst.append(val)
else:
print("-"*50)
print("Given List of Elements:{}".format(lst))
# [10, 6, -5, 19, 2]
print("-"*50)
#Generate Mul tables for list of values.
for n in lst: # Outer for loop
if(n<=0):
print("{} not value mul
table:".format(n))
else:
print("-"*50)
Flow Control Statements in Python (OR)
Control Structures in Python
print("Mul Table for {}".format(n))
print("-"*50)
for i in range(1,11): #Inner for loop
print("\t{} x {} =
{}".format(n,i,n*i))
else:
print("-"*50)
=====================================================
"""
E:\KVR-PYTHON-6PM\LOOPS>py forforforloopex1.py
i=1
j=10
k=50
Flow Control Statements in Python (OR)
Control Structures in Python
k=51
j=11
k=50
k=51
i=2
j=10
k=50
k=51
j=11
k=50
k=51
"""
9. Program for accepting age of citizen and decide eligible to vote or not.
#VoterEx1.py
--------------------------------------------------------------------------------------------
age=int(input("Enter ur age:"))
if(age>=18) and (age<=100):
print("{} year old citizen eligible to
vote".format(age))
else:
print("citizen not eligible to vote")
========================================================
10. Program for accepting age of citizen and decide eligible to vote or not
#VoterEx2.py
--------------------------------------------------------------------------------------------
while(True):
age=int(input("Enter ur age:"))
if(age>=18) and (age<=100):
break
print("Ur age is invalid")
print("{} year old citizen eligible to
vote".format(age))
========================================================
Problem statements:
----------------------------------
Flow Control Statements in Python (OR)
Control Structures in Python
1) aceept sno,name, marks in three subjects (cm-100,cpp-100,pym-100)
2) cal total marks (totmarks=cm+cppm+pym)
3) cal percentage of marks (percent=(totmarks/300)*100 )
4) Give Grade=Fail provided the student secures less than 40 atleast
in one subject
5) Give Grade="Distinction " provided totmarks>=250 and totmarks<=300
6) Give Grade="First " provided totmarks>=200 and totmarks<=249
7) Give Grade="Second" provided totmarks>=150 and totmarks<=199
8) Give Grade="Third" provided totmarks>=120 and totmarks<=149\
9) Display Student Marks Memo.
--------------------------------------------------------------
------------------------------------------------------------
"""
#Program display student Marks report
#studentmarksreport.py
#accept student number
while(True): # validation student number
sno=int(input("Enter the Student Number(500--600):"))
if(sno>=500) and (sno<=600):
break
print("Invalid Student Number")
#accept student name
while(True):
sname=input("Enter Student Name:")
if(sname.isalpha() ):
break
print("Invalid Student Name")
#validation of C Marks
while(True):
cm=int(input("Enter Marks in C(0-100):"))
if(cm>=0) and (cm<=100):
break
print("Invalid Marks in C")
Examples: GW-BASIC
Functions in Python
1) Function definition
2) Function Call
1. Taking INPUT
2. Doing the PROCESS.
3. Giving OUTPUT/RESULT.
Functions in Python
Syntax for defining functions and Explanation:
Approach-1:
Input: Function Call
Process: Function Body
Output: Function Call
Functions in Python
Example:
#Approach1.py
def addop(a,b): # Here 'a' and 'b' are called Formal params
c=a+b # here 'c' is called Local Variable
return c
#main program
#Taking Input
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
res=addop(x,y) # Function Call--
print("Sum=",res) # disp the result
Apporach-2:
Example:
#Approach2.py
def addop():
#taking Input
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#Process
c=a+b
#disp the Result / Output
print("sum({},{})={}".format(a,b,c))
#main program
addop() # Function Call
Approach-3:
Input: Function Call
Process: Function Body
Output: Function Body
Functions in Python
Example:
#Approach3.py
def addop(k,v):
r=k+v
print("sum({},{})={}".format(k,v,r))
#main program
k=float(input("Enter First Value:"))
v=float(input("Enter Second Value:"))
addop(k,v)#Function call
Approach-4:
Input: Function Body
Process: Function Body
Output: Function Call
Example:
#Approach4.py
def addop():
#taking Input
k=float(input("Enter First Value:"))
v=float(input("Enter Second Value:"))
#process
r=k+v
#return result
return k,v,r # In Python return statement can return one
or more values
#main program
a,b,result=addop() # Function Call with multi line assigment
print("sum({},{})={}".format(a,b,result))
print("-----------------OR----------------------")
result=addop() # Function Call.
# Here result variable is holding 3 values returned by
Function Defintion and variable result is of type tuple
#print(result, type(result)) ---- (3.4, 12.5, 15.9) <class
'tuple'>
print("sum({},{})={}".format(result[0],result[1],result[2]))
Functions in Python
===================================================================
Prog 1(a): WAPP to accept the values from user and arrange it in ascending and
descending order using function.
--------------------------------------------------------------------------------------------------------------
def readvalues():
n=int(input("Enter how many number u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def sortvalues():
result=readvalues()
if(result==None):
print("No Elements are present and nothing to sort")
else:
print("Original Elements")
for val in result:
print("\t{}".format(val))
#sort the data--ASC Irder
result.sort()
print("Sorted Elements--Asending Order")
for val in result:
print("\t{}".format(val))
#sort the data--ASC Irder
result.sort(reverse=True)
print("Sorted Elements--Decending Order")
for val in result:
print("\t{}".format(val))
#main program
sortvalues()
===================================================================
Functions in Python
Prog 1(b): WAPP to accept the values from user and arrange it in ascending and
descending order using function.
------------------------------------------------------------------------------------------------------------
def readvalues():
n=int(input("Enter how many number u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def dispvalues(lst):
print("="*50)
for val in lst:
print("\t{}".format(val))
print("="*50)
def sortvalues():
result=readvalues() # Function Chaining
if(result==None):
print("No Elements are present and nothing to sort")
else:
print("Original Elements")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
result.sort()
print("Sorted Elements--Asending Order")
dispvalues(result) # Function Chaining
#sort the data--ASC Irder
result.sort(reverse=True)
print("Sorted Elements--Decending Order")
dispvalues(result) # Function Chaining
#main program
sortvalues()
===================================================================
Functions in Python
Prog 2: Program for accepting list of values and find sum and avg.
-----------------------------------------------------------------------------------------------
def readvalues():
n=int(input("Enter how many number u have:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
lst=[]
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
return lst
def computersumavg(result):
if(result==None):
print("No Values present and we can't cal sum and avg")
else:
s=0
for val in result:
print("\t{}".format(val))
s=s+val
else:
print("Sum={}".format(s))
print("Avg={}".format(s/len(result)))
#main program
result=readvalues()
computersumavg(result)
===================================================================
Functions in Python
Prog 3: Program for finding max and min from list of values by using Functions.
#maxminvalue.py
------------------------------------------------------------------------------------------------
def readvalues():
print("\nEnter List of values separated by space:")
lst=[ int (val) for val in input().split() ]
return lst
def findmaxvalue():
lst=readvalues()
maxv=lst[0] # maxv=10
for i in range(1,len(lst)):
if(lst[i]>maxv):
maxv=lst[i]
return maxv
def findminvalue():
lst=readvalues()
minv=lst[0] # minv=10
for i in range(1,len(lst)):
if(lst[i]<minv):
minv=lst[i]
return minv
#main program
maxv=findmaxvalue()
print("Max Element={}".format(maxv))
minv=findminvalue()
print("Min Element={}".format(minv))
===================================================================
Functions in Python
Prog 4: Program for finding max and min from list of values by using Functions.
#maxminvaluewithlib.py
-----------------------------------------------------------------------------------------------
def readvalues():
print("\nEnter List of values separated by space:")
lst=[ int (val) for val in input().split() ]
return lst
def findmaxvalue():
lst=readvalues()
return max(lst)
def findminvalue():
lst=readvalues()
return min(lst)
#main program
maxv=findmaxvalue()
print("Max Element={}".format(maxv))
minv=findminvalue()
print("Min Element={}".format(minv))
===================================================================
Functions in Python
List comprehension
The purpose of List comprehension is that “To read the values dynamically
from key board separated by a delimiter (space, comma, colon…etc)”.
List comprehension is the most effective way for reading the data
for list instead traditional reading the data.
Examples:
----------------------
print("Enter List of values separated by space:")
# [10 2 22 50 10 4 55 -3 0 22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst)
Examples:
------------------
lst=[4,3,7,-2,6,3]
newlst=[ val*2 for val in lst ]
print("new list=",newlst) # [ 8, 6, 14,-4,12,6 ]
===================================================================
Functions in Python
#listcompre.py
----------------------------------------------------------------
print("Enter List of values separated by space:") #
[10,2,222,50,10,4,55,-3,0,22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst)
print("============OR================")
ls=[]
n=int(input("Enter how many values u want to be list:"))
if(n<=0):
print("{} is invalid input:".format(n))
else:
print("Enter {} values:".format(n))
for i in range(1,n+1):
val=int(input())
ls.append(val)
else:
print("content of lst",ls)
================================================================
#listcompre1.py
----------------------------------------------------------------
print("Enter List of values separated by space:") #
[10,2,222,50,10,4,55,-3,0,22]
lst= [float(val) for val in input().split() ]
print("content of lst",lst) # [3.0, 5.0, 2.0, 7.0, 3.0, 9.0,
6.0]
print("-"*40)
newlst=[]
for val in lst:
newlst.append(val*2)
else:
print("new list=",newlst)
print("-"*40)
print("==============OR=================")
newlst=[ val*2 for val in lst]
print("new list=",newlst)
===================================================================
Functions in Python
Prog 1: This program accept list of values dynamically by using list
comprehension and sort them.
#listsortcompre.py
------------------------------------------------------------------------------------------------
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)
def sortelements(lst):
print("Original Elements")
disp(lst)
lst.sort()
print("Sorted Elements in Ascending Order")
disp(lst)
lst.reverse() # or lst.sort(reverse=True)
print("Sorted Elements in Decending Order")
disp(lst)
#main program
print("Enter List of values separated by space:") #
[10,2,222,50,10,4,55,-3,0,22]
lst= [ int(val) for val in input().split() ]
sortelements(lst)
===================================================================
Functions in Python
Prog 2: This program accept list of names dynamically by using list
comprehension and sort them.
#listsortcompre1.py
----------------------------------------------------------------------------------------------
def disp(k):
print("-"*40)
for val in k:
print("\t{}".format(val))
else:
print("-"*40)
def sortelements(lst):
print("Original Elements")
disp(lst)
lst.sort()
print("Sorted Elements in Ascending Order")
disp(lst)
lst.reverse() # or lst.sort(reverse=True)
print("Sorted Elements in Decending Order")
disp(lst)
#main program
print("Enter List of Names separated by comma:")
lst= [ str(val) for val in input().split(",") ]
sortelements(lst)
===================================================================
Prog 3: Program for finding max and min from list of values by using Functions.
#indexvalue.py
-----------------------------------------------------------------------------------------------
def readvalues():
print("\nEnter List of values separated by space:")
lst=[ int (val) for val in input().split() ]
return lst
def findindex():
lst=readvalues()
indval=-1
sk=int(input("Enter which value u want to search:"))
for i in range(0,len(lst)):
if(sk==lst[i]):
indval=i
break
if(indval>-1):
print("{} Found at {} Index:".format(sk,indval))
else:
print("{} does not exist in list".format(sk))
#main program
findindex()
================================================================
Functions in Python
===================================================================
#listcomprehenex2.py
-----------------------------------------------------------------------------------------------
print("Enter List of values separated by space:")
lst=[ int (val) for val in input().split() ] # 10 20 34 -45 -
56 23
print("\nGiven List of elements:{}".format(lst))
print("================OR=====================")
print("Enter List of values separated by comma:")
lst=[ int (val) for val in input().split(",") ]
print("\nGiven List of elements:{}".format(lst))
===============================x====================================
Functions in Python
1. Formal Parameters
2. Local Parameters
Formal Parameters are always used in Function Heading and they are
used for storing Input Values coming from Function call.
Local Parameters are always used inside of Function Body and they
are used for storing Temporary results.
Arguments are the variables used in Function Calls.
-----------------------------------------------------
-----------------------------------------------------
Syntax for Function Call:
functionname(list of arguments)
When there is a Common Value for family of Function Call then such
type of Common Value(s) must be taken as default Parameter with
Common Value (but not recommended to pass by using Positional
Parameters).
Functions in Python
Syntax for Function Definition with Default Parameters:
Examples:
--------------
#ArgsParams.py
--------------------
def disp(a,b):
print("val of a={}".format(a))
print("val of b={}".format(b))
#main program
x=input("Enter Val of x:")
y=input("Enter Val of y:")
disp(x,y)
===========================================================
Prog 1: Program for demonstrating Possitional Arguments concept
#PosArgsex1.py
-----------------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks):
print("\t{}\t{}\t{}".format(stno,sname,marks))
#main program
print("="*50)
print("\tStno\tName\tMarks")
print("="*50)
dispstudinfo(10,"RS",34.56) # Function Call
dispstudinfo(20,"TS",54.56) # Function Call
dispstudinfo(30,"MC",14.16) # Function Call
dispstudinfo(40,"RT",56.78) # Function Call
print("="*50)
=======================================================
Functions in Python
Prog 2: Program for demonstrating Positional Arguments concept
#PosArgsex2.py
-----------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks,crs):
print("\t{}\t{}\t{}\t{}".format(stno,sname,marks,crs))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
dispstudinfo(10,"RS",34.56,"PYTHON") # Function Call
dispstudinfo(20,"TS",54.56,"PYTHON") # Function Call
dispstudinfo(30,"MC",14.16,"PYTHON") # Function Call
dispstudinfo(40,"RT",56.78,"PYTHON") # Function Call
print("="*50)
=========================================================
Prog 3: Program for demonstrating Default Arguments concept
#DefArgsex1.py
----------------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(stno,sname,marks,crs))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse")
print("="*50)
dispstudinfo(10,"RS",34.56) # Function Call
dispstudinfo(20,"TS",54.56) # Function Call
dispstudinfo(30,"MC",14.16) # Function Call
dispstudinfo(40,"RT",56.78) # Function Call
dispstudinfo(50,"XR",26.78,"JAVA")# Function Call
dispstudinfo(60,"SR",26.78)
print("="*50)
==========================================================
Functions in Python
Prog 4: Program for demonstrating Default Arguments concept
#DefArgsex2.py
---------------------------------------------------------------------------------------
def dispstudinfo(stno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(stno,sname,marks,crs
,cnt))
#main program
print("="*50)
print("\tStno\tName\tMarks\tCourse\tCountry")
print("="*50)
dispstudinfo(10,"RS",34.56) # Function Call
dispstudinfo(20,"TS",54.56) # Function Call
dispstudinfo(30,"MC",14.16) # Function Call
dispstudinfo(40,"RT",56.78) # Function Call
dispstudinfo(50,"XR",26.78,"JAVA")# Function Call
dispstudinfo(60,"SR",26.78)
dispstudinfo(70,"TR",16.78,"Django","USA")
print("="*50)
===========================================================
Prog 5: Program for demonstrating Default Arguments concept
#DefArgsex3.py
---------------------------------------------------------------------------------------
def disp(a=10,b=20,c=30):
print("\t{}\t{}\t{}".format(a,b,c))
#main program
print("="*50)
print("\ta\tb\tc")
print("="*50)
disp()
disp(100)
disp(100,200)
disp(100,200,300)
print("="*50)
================================================================
Functions in Python
Prog 6: Program for demonstrating Default Arguments concept
#DefArgsex4.py
---------------------------------------------------------------------------------------
def area(r,pi=3.14):
ar=pi*r**2
print("Area of Cirtcle={}".format(ar))
def peri(r,pi=3.14):
pr=2*pi*r
print("Perimeter of Cirtcle={}".format(pr))
#main program
area(float(input("Enter Radious for area cal:")))
peri(float(input("\nEnter Radious for peri cal:")))
==========================================================
#main program
print("="*50)
print("\tEmpno\tName\tSal\tDesg")
print("="*50)
dispempinfo(10,"RS",1.2,"Author") # Function Call with
Possitional args
dispempinfo(sal=2.3,dsg="SE",eno=20,ename="DR")# Function Call
with kwd args
dispempinfo(dsg="TL",eno=30,sal=4.5,ename="TR") # Function
Call with kwd args
dispempinfo(40,"RT",dsg="TRINER",sal=2.3)# Function Call with
Pos args and kwd args
print("="*50)
============================================================
Functions in Python
===========================================================
#kwdargsex3.py
def dispempinfo(eno,ename,sal,dsg,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}\t{}".format(eno,ename,sal,dsg,cr
s))
#main program
print("="*50)
print("\tEmpno\tName\tSal\tDesg\tCourse")
print("="*50)
dispempinfo(10,"RS",1.2,"Author") # Function Call with
Possitional args
dispempinfo(sal=2.3,dsg="SE",eno=20,ename="DR")# Function Call
with kwd args
dispempinfo(dsg="TL",eno=30,sal=4.5,ename="TR") # Function Call
with kwd args
dispempinfo(40,"RT",dsg="TRINER",sal=2.3)# Function Call with
Pos args and kwd args
dispempinfo(50,"MC",1.5,"Jr.SE","JAVA")
dispempinfo(sal=3.4,crs="D.Sci",eno=60,dsg="PM",ename="DT")
print("="*50
===========================================================
#Varargsex2.py------This Program will execute as it is written
def disp(a): # Function Definition-1
print(a)
disp(10) # Function call-1
Here *param is called Variable Length Parameter and it can hold any number
of arguments values or variable number of argument values and *param
type is <class, ‘tuple’>.
Rule: The *param must always written at last part of function heading and it
must be only one (but not multiple)
#main program
disp(10) # Function call-1
disp(10,20) # Function Call-2
disp(10,20,30) # Function Call-3
disp(10,20,30,40) # Function Call-4
===========================================================
#Varargsex2.py------This Program will execute as it is written
def disp(a): # Function Definition-1
print(a)
disp(10) # Function call-1
#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")
=============================================================
Rule: The **param must always written at last part of Function Heading and
it must be only one (but not multiple)
Final Syntax:
dispinfo(tno=1000,tname="KVR",sub1="PYTHON", sub2="JAVA") # #
Function Call-3
Functions in Python
==========================================================
#Program demonstrating Keyword Variable length Arguments
#purekwdvarlenargsex1.py
def dispinfo( **k ):
print("-"*50)
for k,v in k.items():
print("\t{}-->{}".format(k,v))
print("-"*50)
#main program
dispinfo(sno=10,sname="RS",marks=22.22) # Function Call-1
dispinfo(eno=100,ename="TR") # Function Call-2
dispinfo(tno=1000,tname="KVR",sub1="PYTHON", sub2="JAVA") # #
Function Call-3
dispinfo(cid=1,cname="XR",Hobby1="Reading",
Hobby2="Practcing",Hobby3="Sleeping")
================================================
#Program for finding total marks of different students who are
studying in different class and securing in different subjects.
#purekwdvarlenargsex2.py
def findtotalmarks(sno,sname,cls,**submarks):
print("="*50)
print("Student Number={}".format(sno))
print("Student Name={}".format(sname))
print("Student Class Name={}".format(cls))
totmarks=0
for sn,sm in submarks.items():
print("\t{}--->{}".format(sn,sm))
totmarks=totmarks+sm
if(totmarks>0):
print("Total Marks={}".format(totmarks))
per=(totmarks / (len(submarks)*100))*100
print("Percentage={}".format(per))
print("="*50)
else:
print("Total Marks={}".format(totmarks))
print("Percentage={}".format(0))
print("="*50)
#main program
findtotalmarks(10,"Surya","X",Eng=50,Hindi=60,Telugu=67,Maths=60
,Sci=80,Soc=70)
findtotalmarks(20,"Pradip","XII",Mathematics=70,Physics=58,Chemi
stry=54)
findtotalmarks(30,"Manaiah","B.Tech(CSE)",CM=70,Python=60)
findtotalmarks(40,"Rossum","Research")
===============================================
Functions in Python
#purekwdvarlenargsex3.py
def disp(no,sname,*n,**hyd):
print("="*50)
print("\tNumber={}".format(no))
print("\tName={}".format(sname))
print("Variable Argument Values:")
for v in n:
print("\t{}".format(v))
print("Keyword Variable Argument Values:")
for k,v in hyd.items():
print("\t{}-->{}".format(k,v))
print("="*50)
#main program
disp(1,"RS",10,20,30,a=100,b=200)
disp(2,"TR",50,60,x=1,y=2,z=3)
disp(3,"MC",10,20,30,40,p=-1,q=-2,r=-3,k=-4)
===============================================
#purekwdvarlenargsex4.py
def disp(no,sname,*n,city="HYD",**hyd):
print("="*50)
print("\tNumber={}".format(no))
print("\tName={}".format(sname))
print("\tLiving City={}".format(city))
print("Variable Argument Values:")
for v in n:
print("\t{}".format(v))
print("Keyword Variable Argument Values:")
for k,v in hyd.items():
print("\t{}-->{}".format(k,v))
print("="*50)
#main program
disp(1,"RS",10,20,30,a=100,b=200)
disp(2,"TR",50,60,x=1,y=2,z=3)
disp(3,"MC",10,20,30,40,p=-1,q=-2,r=-3,k=-4)
disp(300,"MR",40,50,city="Bang")
disp(400,"MX",4,5,6,7,-8,city="USA",hobby="Playing",job="SE")
disp(99,"KV", 4,city="AP",district="PRAKASHAM",PINCODE=533369)
disp(99,"KV", 4, district="PRAKASHAM",PINCODE=533369,city="AP")
disp(99,"KV", 4, district="PRAKASHAM",PINCODE=533369)
==================x====================
Functions in Python
Local variables are those which are defined / used inside of function.
Local variable can be used for storing temporary result of function.
The values of Local variables can be used inside of same Function Definition
but not possible to access in other part of the program and in other
Function Definition.
Global variables are those which are used for representing common values
for multiple different function calls and saves the memory space.
Global variables must be defined before all function calls. So that we can
access the Global variable values in all the function definitions. Otherwise
we can’t access.
Syntax:
Var1=Val1
Var2=Val2
-------------
Var-n=Val-n
def functionname1(.....):
var22=val22
var23=val23
------------------
def functionname2(.....):
var32=val32
var33=val33
Here Var1, Var2… Var-n are called Global variable for functionname1() and
functionname2().
Here Var22, Var23… are called Local Variables for functionname1().
Here Var32, Var33… are called Local Variables for functionname2().
Functions in Python
Examples:
=============================================================
#globallocalvarex3.py
---------------------
def learnML():
sub1="Machine Learning" # here sub1 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub1,lang))
#print(sub2,sub3)---Error bcoz sub2 and subj3 are local
variables in other Functions
def learnDL():
sub2="Deep Learning" # here sub2 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub2,lang))
#print(sub1,sub3)---Error bcoz sub1 and subj3 are local
variables in other Functions
def learnIOT():
sub3="IOT" # here sub3 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub3,lang))
#print(sub1,sub2)---Error bcoz sub1 and subj1 are local
variables in other Functions
#main program
lang="PYTHON" # Global Variable
learnML()
learnDL()
learnIOT()
=================================================
#globallocalvarex4.py
----------------------
def learnML():
sub1="Machine Learning" # here sub1 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub1,lang))
def learnDL():
sub2="Deep Learning" # here sub2 is called Local
Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub2,lang))
def learnIOT():
sub3="IOT" # here sub3 is called Local Variable
print("\nTo Learn and Code in '{}' , we use '{}'
Programming ".format(sub3,lang))
Functions in Python
#main program
learnML()
learnDL()
learnIOT()
lang="PYTHON" # Global Variable --here we can' t access
Variable lang in learnML(), learnDL() and LearnIOT() bcoz It
is defined after Function Call.
===============================================
#globallocalvarex1.py
----------------------
lang="Python" # Here lang is called Global variable
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
learnDS()
learnML()
learnDL()
=================================================
#globallocalvarex2.py
----------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
lang="Python" # Here lang is called Global variable
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
Functions in Python
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
learnDS()
learnML()
learnDL()
============================================================
#globallocalvarex3.py
---------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
lang="Python" # Here lang is called Global variable
#main program
learnDS()
learnML()
learnDL()
=================================================================
#globallocalvarex4.py
----------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
Functions in Python
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
lang="Python" # Here lang is called Global variable
learnDS()
learnML()
learnDL()
================================================================
#globallocalvarex5.py
----------------------
def learnDS():
sub1="DSCI" # here sub1 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub1,lang))
#print(sub2,sub3)-----error, bcoz sub2 and sub3 are
local to learnML() and LearnDL()
def learnML():
sub2="ML" # here sub2 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub2,lang))
#print(sub1,sub3)-----error, bcoz sub1 and sub3 are
local to learnDS() and LearnDL()
def learnDL():
sub3="DL" # here sub3 is called Local Variable
print("To learn '{}', we use '{}'
programming".format(sub3,lang))
#print(sub1,sub2)-----error, bcoz sub1 and sub2 are
local to learnML() and LearnDS()
#main program
#learnDS() # We can't access 'lang' variable' value in
learnDS()
lang="Python" # Here lang is called Global variable
learnML() # We can access 'lang' variable' value in learnML()
and learnDL()
learnDL()
=================================================================
Functions in Python
Syntax:
-----------
var1 = val1
var2 = val2
var-n = val-n # var1, var2... var-n are called global variable names.
------------------
def fun1():
------------------------
global var1, var2... var-n
# Modify var1, var2.... var-n
--------------------------
def fun2():
------------------------
global var1, var2... var-n
# Modify var1, var2.... var-n
--------------------------
================================================================
Examples:
================================================================
#globalvarex1.py
----------------
a=10
def access1():
print("Val of a=",a) # Here we are accessing the global
variable 'a' and No Need to use global kwd.
#main program
access1()
---------------------------------------
Functions in Python
#globalvarex2.py
a=10
def access1():
global a # refering global Varaible before its updation
/ Modification
a=a+1 # Here we are modifying the global variable value
then we need to use
global keyword.
print("Val of a inside of access1()=",a) # 11
#main program
print("Val of a in main before access1():",a) # 10
access1()
print("Val of a in main after access1():",a) # 11
==============================================================
#globalvarex3.py
------------------
def update1():
global a,b # refering global Variables.
a=a+1 #updating global Variable a
b=b+1 #updating global Variable b
def update2():
global a,b # refering global Variables.
a=a*10 #updating global Variable a
b=b*10 #updating global Variable b
#main program
a,b=1,2 # here a and b are called Global Variables
print("Val of a={} and Value of b={} in main program before
update functions :".format(a,b))
# Val of a=1 and Value of b=2 in main program before update
functions :
update1()
print("Val of a={} and Value of b={} in main program after
update1():".format(a,b))
#Val of a=2 and Value of b=3 in main program after update1():
update2()
print("Val of a={} and Value of b={} in main program after
update2():".format(a,b))
#Val of a=20 and Value of b=30 in main program after update1():
================================================================
#globalkwdex1.py
-----------------
Functions in Python
a=10 # Here 'a' is called global Variables
def accessvalue1():
print("Val of a in accessvalue1() ={}".format(a))
def accessvalue2():
print("Val of a accessvalue2()={}".format(a))
#main program
accessvalue1()
accessvalue2()
==================================================================
#globalkwdex2.py
-----------------
a=10 # here 'a' is global Variable
def increment():
global a # refering global variable value
a=a+1
#main program
print("Val of a in main program before incrment()=",a) # 10
increment()
print("Val of a in main program after incrment()=",a) # 11
=================================================================
#globalkwdex3.py
----------------
a=10 # here 'a' is global Variable
b=20 # here 'b' is global Variable
def increment():
global a,b # refering global variable value
a=a+2
b=b+2
#main program
print("Val of a in main program before incrment()=",a) # 10
print("Val of b in main program before incrment()=",b) # 20
increment()
print("Val of a in main program after incrment()=",a) # 12
print("Val of b in main program after incrment()=",b) # 22
==================================================================
#globalkwdex4.py
----------------
a=2
b=3
def update1():
global a,b
a=a+1
b=b+1
def update2():
global a,b
a=a*10
b=b*10
#main program
print("Val of a in main program before update1()=",a) # 2
Functions in Python
print("Val of b in main program before update1()=",b) # 3
update1()
print("Val of a in main program after update1()=",a) # 3
print("Val of b in main program after update1()=",b) # 4
update2()
print("Val of a in main program after update2()=",a) # 30
print("Val of b in main program after update2()=",b) # 40
==================================================================
When we come across same global variable names and Local variable
name in same function definition then PVM gives preference for Local
variables but not for Global variables.
In this context, to extract/retrieve the value of global variables name
along with local variable, we must use globals() and returns an object of
<class, ‘dict’> and this object stores all global variable name as Keys and
global variable values of value.
Syntax:
var1 = val1
var2 = val2
---------------
var-n = val-n #var1, var2…var-n are called Global Variables.
def functionname():
-------------------------
var1 = val11
var2 = val22
----------------
var-n = val-n #var1, var2,…var-n are called Local Variables.
#Extract the Global Variable values.
Dictobj = globals()
globalval1 = dictobj[‘var1’] # or
Functions in Python
dictobj.get("var1") or
globals()['var1']
globalval2=dictobj['var2'] # or
dictobj.get("var2") or
globals()['var2']
==========================================================
Examples:
==========================================================
#globalsfunex3.py
-------------------
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================
#main program
operations()
Functions in Python
==================================================
Examples:
-----------------------
#Program for demonstrating globals()
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()[
'c']+globals()['d']
print(res)
#main program
operation()
=========================================================
#globalsfunex1.py
-------------------
a=10
b=20
c=30
d=40 # here 'a' 'b' 'c' and 'd' are called global Variables
def operation():
a=1
b=2
c=3
d=4 # here 'a' 'b' 'c' and 'd' are called local
Variables
print("val of a-local=",a)
print("val of b-local=",b)
print("val of c-local=",c)
print("val of d-local=",d)
print("val of a-global=",globals().get('a'))
print("val of b-global=",globals().get('b'))
print("val of c-global=",globals()['c'])
print("val of d-global=",globals()['d'])
res=a+b+c+d+globals().get('a')+globals().get('b')+global
s()['c']+globals()['d']
print("result=",res)
#main program
operation()
==========================================================
#globalsfunex2.py
------------------
Functions in Python
a=10
b=20
c=30
d=40 # here 'a' 'b' 'c' and 'd' are called global Variables
def fun1():
kvr=globals()
for k,v in kvr.items():
print("\t{}\t{}".format(k,v))
print("---------------------------------")
print("val of a=",kvr['a'])
print("val of b=",kvr['b'])
print("-----------OR----------------------")
print("val of a=",kvr.get('a'))
print("val of b=",kvr.get('b'))
print("-----------OR----------------------")
print("val of a=",globals().get('a'))
print("val of b=",globals().get('b'))
print("-----------OR----------------------")
print("val of a=",globals()['a'])
print("val of b=",globals()['b'])
#main program
fun1()
==========================================================
Anonymous Function are those, which does not contains the any name
explicitly.
The purpose of Anonymous function is that “To perform Instant
Operation”.
Instant Operations are those, which are used at that point of time and
no longer interested to use in further applications.
To define anonymous function, we use a keyword lambda and
Anonymous Function are also called Lambda Function.
Anonymous Function contains single executable statement but not
containing block of statements.
Anonymous Function returns the result automatically (no need to use
write return statement explicitly).
Functions in Python
Syntax: varname = lambda params-list : expression
Explanation:
Here “varname” is an object and itself act as function Name because
varname is an object of <class, ‘function’>.
Lambda is a keyword used for defining Anonymous Function.
params-list represents list of variable names used for Holding or storing
input values coming from Function Calls.
Expression represents single executable statement and it performs
Instant Operation and whose result returned automatically.
======================================
#Normal Function Definition and Function Call
-------------------------------------------------------------
Def sumop(a,b):
res1=sumop(10,20)
c=a+b
print(“sum=”,res1)
return c
------------------------------------------------------------------
#Anonymous Function Definition and Function call
-------------------------------------------------------------------
Sumop=lambda a,b: a+b
res1= sumop(100,200)
print(“sum=”,res1)
----------------------------------------------------------------------------
#Program for performing sum of two number by using Anonymous
Functions
#AnonymouseFunEx1.py
--------------------------------------------------------------
def sumop(a,b): # Normal Function
c=a+b
return c
addop=lambda k,v: k+v # Anonymous Function
#main program
print("type of sumop obj=",type(sumop)) # type of sumop obj=
<class 'function'>
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res1=sumop(a,b) # Normal Function Call
print("Sum=",res1)
Functions in Python
print("-----------------------------------------------------")
print("type of addop obj=",type(addop)) # type of addop obj=
<class 'function'>
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res2=addop(a,b) # Anonymous Function call
print("Sum=",res2)
======================================================================
#Program for performing Temporature conversions.
#AnonymouseFunEx2.py
---------------------------------------------
ft=lambda ct:(9/5)*ct+32 # Anonymous Function1
kt=lambda ct: ct+273 # Anonymous Function2
#main program
ct=float(input("Enter Temporatue in Celciou:"))
fttemp=ft(ct) # Anonymous Function call-1
print("Foreign Heat Temp({}
celcious)={}".format(ct,fttemp))
kttemp=kt(ct) # Anonymous Function call-2
print("Kelvin Temp({}
celcious)={}".format(ct,kttemp))
==========================================
#Program for performing finding biggest and smallest
among two numbers
#AnonymouseFunEx3.py
-----------------------------------------------------
findmaxval=lambda k,v : k if k>v else v
findminval=lambda k,v : k if k<v else v
#main program
a,b=float(input("Enter First
Value:")),float(input("Enter Second Value:"))
print("Max
Value({},{})={}".format(a,b,findmaxval(a,b)))
print("Min
Value({},{})={}".format(a,b,findminval(a,b)))
==================================================================
Functions in Python
#Program for performing finding biggest and smallest
among two numbers
#AnonymouseFunEx4.py
-----------------------------------------------------
findmaxval=lambda k,v : "Both Values are Equal" if
(k==v) else k if (k>v) else v
findminval=lambda k,v : "Both Values are Equal" if
(k==v) else k if (k<v) else v
#main program
a,b=float(input("Enter First
Value:")),float(input("Enter Second Value:"))
print("Max
Value({},{})={}".format(a,b,findmaxval(a,b)))
print("---------------------------------------")
a,b=float(input("Enter First
Value:")),float(input("Enter Second Value:"))
print("Min
Value({},{})={}".format(a,b,findminval(a,b)))
==========================================================
#write a python program which will accept a three
numerical values and find the biggest and smallest
among them
#AnonymouseFunEx5.py
-----------------------------------------------------
findmaxval=lambda k,v,r: "ALL Values are Equal" if
(k==v==r) else k if(v<k>r) else v if(k<v>r) else r
findminval=lambda k,v,r: "ALL Values are Equal" if
(k==v==r) else k if(v>k<r) else v if(k>v<r) else r
#main program
a,b,c=float(input("Enter First
Value:")),float(input("Enter Second
Value:")),float(input("Enter Third Value:"))
max1=findmaxval(a,b,c)
min1=findminval(a,b,c)
print("max({},{},{})={}".format(a,b,c,max1))
print("min({},{},{})={}".format(a,b,c,min1))
===================================================
Functions in Python
#write a python program which will accept list of
numerical values and find max and min by using
anonymous functions
#AnonymouseFunEx6.py
-----------------------------------------------------
maxv=lambda lst:max(lst)
minv=lambda lst:min(lst)
#main program
print("Enter List of Values Separated by Space:")
lst=[ float(val) for val in input().split()]
bv=maxv(lst)
print("max({})={}".format(lst,bv))
sv=minv(lst)
print("min({})={}".format(lst,sv))
Functions in Python
1) Filter(): It is used for “Filtering out some element from list of elements
by applying to function”.
Explanation:
Here ‘varname’ is an object of type <class,’filter’> and we can convert into
any iterable object by using type casting functions.
def negative(n):
if n<0:
return True
else:
return False
#main program
lst=[10,20,-56,78,0,-45,-79,-34,56]
obj1=filter(positive,lst) # Filter() filtering Possitive
Values
print(obj1, type(obj1)) # <filter object at
0x000001F1246604C0> <class 'filter'>
pslist=list(obj1) # Converting filter object into list type
print("Original Elements=",lst)
print("Possitive Elements=",pslist)
obj2=filter(negative,lst) # Filter() filtering Negative
Values
print(obj2, type(obj2)) # <filter object at
0x000002B3ED927F10> <class 'filter'>
nstpl=tuple(obj2)
print("Negative Elements=",nstpl)
============================================================
#Program for filtering Possitive and Negative Elements from
list of elements by using Anonymous Functions
#FilterEx2.py
print("\nOriginal Elements=",lst)
print("Possitive Elements=",pslist)
print("Negative Elements=",nslist)
============================================================
#Program for filtering Possitive and Negative Elements from
list of elements by using Anonymous Functions
#FilterEx3.py
print("Enter List of elements separated by space:")
lst=[int(val) for val in input().split()]
print("\nOriginal Elements=",lst)
print("Possitive Elements=",pslist)
print("Negative Elements=",nslist)
==============================================================
#Program for filtering Odd and Even Elements from list of
elements by using Anonymous Functions and Normal Functions.
#FilterEx4.py
def even(n):
if n%2==0:
return True
else:
return False
#main program
line=input("Enter a line of text:") # Python3
print("\nGiven Line=",line)
vwlist=list(filter(lambda ch: ch in
['a','e','i','o','u','A','E','I','O','U'],line))
conslist=list(filter(cons,line))
print("Vowels List=",vwlist)
print("Number of Vowels=",len(vwlist))
print("Cons list=",conslist)
print("Number of consonats=",len(conslist))
============================================================
2) Map(): It is used for obtaining new iterable object from existing iterable
object by applying old iterable object element to the function.
In the other word, map() is used for obtaining new list of elements from
existing list of element by applying old list element to the function.
Explanation:
Here ‘varname’ is an object of type <class, map> and we can convert
into any iterable object by using type-casting functions.
#main program
lst=[2,4,5,-3,6,7]
obj1=map(square,lst)
print(obj1,type(obj1)) # <map object at 0x00000218FF330310>
<class 'map'>
sqlist=list(obj1)
print("Original List=",lst)
print("Square List=",sqlist)
==============================================================
#Program for obtaining Square for every element of list by
using map() with Anonymous Function
#mapex2.py
--------------------------------------------------------------
print("Enter List of elements separated by space:")
lst=[int(val) for val in input().split()]
sqlist=list(map(lambda x: x**2,lst))
sqrtlist=list(map(lambda x: x**0.5,lst))
print("\nOriginal List=",lst)
print("Square List=",sqlist)
print("Square Root List=",sqrtlist)
==============================================================
#Program for obtaining new sal list from oldsal list by giving
10% hike by using map()
#mapex3.py
print("Enter List of elements separated by space:")
oldsal=[int(val) for val in input().split()]
newsal=list(map(lambda sal:sal+sal*10/100,oldsal ))
print("\nOld Salary List=",oldsal)
print("\nNew Salary List=",newsal)
==============================================================
Step1: reduce() select two first values of iterable object and place
them in first var and second var.
Step4: repeat step2 and step3 until all element completed in iterable
object and return the result of first var.
Examples:
========================================================
#Program for reading list of values and obtains sum by using
reduce()
#reduceex1.py
--------------------------------------------------------------
import functools
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
result=functools.reduce(lambda x,y: x+y,lst)
print("Sum({})={}".format(lst,result))
=============================================
Functions in Python
#Program for reading list of values and obtains sum by using
reduce()
#reduceex2.py
-----------------------------------------------------------
import functools
def sumop(x,y):
c=x+y
return c
#main program
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
result=functools.reduce(sumop,lst)
print("Sum({})={}".format(lst,result))
=======================================================
#write a python program which will accept list of names or
words and concatnet them
#reduceex3.py
--------------------------------------------------------------
import functools as k
print("Enter List of words separated by comma:")
lst=[str(val) for val in input().split(",")]
line=k.reduce(lambda a,b: a+" "+b, lst)
print("\nGiven words=",lst)
print("Concatination of words=",line)
========================================================
#write a python program which will accept list of values and
find max and min values by using reduce()
#reduceex4.py
--------------------------------------------------------------
import functools as k
print("Enter List of values separated by comma:")
lst=[int(val) for val in input().split(",")]
maxv=k.reduce(lambda a,b: a if a>b else b, lst)
minv=k.reduce(lambda a,b: a if a<b else b, lst)
print("\nmax({})={}".format(lst,maxv))
print("min({})={}".format(lst,minv))
========================================================
#write a python program which will accept list of values and
find max and min values by using reduce()
#reduceex5.py
-------------------------------------------------------------
import functools as k
print("Enter List of words separated by comma:")
lst=[str(val) for val in input().split(",")]
maxv=k.reduce(lambda a,b: a if a>b else b, lst)
minv=k.reduce(lambda a,b: a if a<b else b, lst)
print("\nmax({})={}".format(lst,maxv))
print("min({})={}".format(lst,minv))
========================================================
Functions in Python
#write a python program which will accept list of numericle
values and find squares for positive numbers and cubes for
negative numbers
#filtermapex.py
------------------------------------------------------------
print("Enter List of Values seperated by space:")
lst=[int(val) for val in input().split()]
Purpose of Modules
Definition of Module
Types of Modules—a) Pre-defined Modules
b) Programmer-defined Modules
Development Programmer-defined Modules
Techniques for re-using the Modules
a) By using import statement (4-Syntaxes)
b) By using from… import statement (3-Syntaxes)
Programming Examples
Re-loading the Modules
Programming Examples
Modules in Python
Modules in Python:
To re-use the functions and global variables across the programs, we must
use the concept of Modules.
-----------------------------------------------------------------------
Syntax-2:
import module name1, module name2....Module name-n
This syntax imports multiple modules
Example: import icici , aop, mathsinfo
--------------------------------------------------------------------------------------------
Syntax-3:
import module name as alias name
This syntax imports single module and aliased with another name
Example: import icici as i
import aop as a
import mathsinfo as m
--------------------------------------------------------------------------------------------
Modules in Python
Syntax-4:
import module name1 as alias name, module name2 as alias
name......module name-n as alias name
This syntax imports multiple modules and aliased with another names
Hence after importing all the variable names, Function names and
class names by using "import statement" , we must access variable
names, Function names and class names w.r.t Module Names or alias
names.
Module Name.Variable Name
Module Name.Function Name
Module Name.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name
=======================================================================
3) By using from.... import statement.
-----------------------------------------------
Here "form" "import" are the key words
The purpose of from.... import statement is that " To refer or access
the variable names, function names and class names in current
program directly without writing module name."
we can use from.... import statement in 3 ways.
Syntax-1:
from module name import Variable Names,Function Names, Class
Names
This syntax imports the Variable Names,Function Names, Class Names
of a module.
Modules in Python
Example: from calendar import month
from aop import addop,subop
from mathinfo import pi,e
from icici import bname,loc,l simpleint
--------------------------------------------------------------------------------------------
Syntax-2:
from module name import Variable Names as alias name,Function
Names as alias name , Class Names as alias names.
This syntax imports the Variable Names, Function Names, Class
Names of a module with alias Names
Variable Name
Function Name
Class Name
Modules in Python
Hence with "import statement” we can give alias name for module
names only but not for Variables Names, Function Names and Class
Names. Whereas with "from ... import statement" we can give alias
names for Variables Names, Function Names and Class Names but not
for Module Name.
=========================================X============================================
Examples:
-------------
#aop.py---file name and itself acts as module name
--------------------------------------------------------------
def sumop(a,b): # Function Def-1
c=a+b
print("sum({},{})={}".format(a,b,c))
def subop(a,b): # Function Def-2
c=a-b
print("sub({},{})={}".format(a,b,c))
def mulop(a,b): # Function Def-3
c=a*b
print("mul({},{})={}".format(a,b,c))
==========================================================
#Approach1.py
import aop
aop.sumop(10,20)
==========================================
#Approach2.py
import icici, aop
icici.simpleint()
aop.sumop(10,20)
==========================================================
#Approach3.py
i
import aop as a
a.sumop(10,20)
==========================================================
#Approach4.py
import icici as ic, aop as a
ic.simpleint()
a.sumop(10,20)
==========================================================
Modules in Python
#Approach5.py
from icici import bname, loc, simpleint
print("\nBank Name:{}".format(bname))
print("\nBank Location:{}".format(loc))
simpleint()
==========================================================
#Approach6.py
from icici import bname as bn, loc as l, simpleint as si
print("\nBank Name:{}".format(bn))
print("\nBank Location:{}".format(l))
si()
==============================================
#Approach7.py
from icici import *
print("\nBank Name:{}".format(bname))
print("\nBank Location:{}".format(loc))
simpleint()
==============================================
Modules in Python
Purpose/Situation:
reload () reload a previously imported module. If we have edited the module
source file by using an external editor and we want to use the changed
values/update values/new version of previously loaded module then we use
reload().
Examples:
===================================
#shares.py---file name and acts as module name
def sharesinfo():
d={"IT":401,"Pharma":301,"Fin":371,"Auto":150}
return d
-------------------------------------------------------------------------
#sharesdemo.py
import time
import shares
import importlib #imp module deprecated in favour of importlib
def dispshares(d):
print("="*50)
print("\tShare Name\tShare Value")
print("="*50)
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("="*50)
Modules in Python
#main program
dt=shares.sharesinfo()
dispshares(dt)
print("Line-16-->PVM is going to sleep for 20 secs")
time.sleep(20) # PVM pause the execution
print("Line-18-->PVM is commig out of sleep ")
importlib.reload(shares)
dt=shares.sharesinfo()
dispshares(dt)
===============================================
Package in Python
Package in Python
Examples:
sys.path.append("D:\\python")
(or)
sys.path.append("D:\python")
Index
Define Exception.
Define Exception Handling.
Types of Exceptions.
a) Per-defined or Built-in Exceptions
b) Programmer/User/Custom defined Exceptions
Handling Exceptions
Keyword for Handling Exceptions
1) Try
2) Except
3) Else
4) Finally
5) Raise
1) When the application user enters invalid input then we get Runtime Errors.
(Invalid Input -----> Runtime Error)
7) In order to perform step (a), step (b) & step (c), internally PVM
creates an object of appropriate exception class.
try:
block of statements
generating exception
except <exception-class-name-1>
black of statements
generating User-friendly Error Messages
except <exception-class-name-2>:
black of statements
generating User-friendly Error Messages
----------------------------------------------------------
----------------------------------------------------------
except <exception-class-name-n>:
black of statements
generating User-friendly Error Messages
else:
Block of statements recommended
Generate result
Finally:
Block of statements executes compulsorily
Irrespective exception occurs or not.
Exception Handling in Python
Explanation:
1. try block:
It is the block in which we write block of statements to generates
exceptions. In other words, which are all the statements generating
exception those statements must be written within the try block and
hence try block is called exception monitoring block.
When an exception occurs in try block, PVM comes out of try block and
execute appropriate except block.
Once PVM execute except block then PVM never goes to try block for
executing the rest of the statements.
Every try block must contain at least one except block and
recommended to write multiple except block for generating multiple
user-friendly error messages.
2. except block:
Even we write multiple except blocks, PVM will execute only one
appropriate except block depends on type of exception.
Exception Handling in Python
The place of writing except block is after try block and before else block
(if we write else block).
3. else block:
This block will execute when there is no exception in the try block.
Writing else block is optional.
The place of writing else block is that after except block and before
finally block (if we write finally block).
4. finally block:
Examples:
#This Program accept two numerical values from KBD and find
div.
#Div1.py
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
#convert s1 and s2 into int type
a=int(s1) #------------------------------------------------X
b=int(s2) #------------------------------------------------X
c=a/b #-----------------------------------------------X
print("Div=",c)
==========================================================
Exception Handling in Python
#This Program accept two numerical values from KBD and find
div.
#Div2.py
try:
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
#convert s1 and s2 into int type
a=int(s1) #-----------------------------------------X
b=int(s2) #-----------------------------------------X
c=a/b #----------------------------------------X
except ZeroDivisionError:
print("\nDON'T ENTER ZERO FOR DEN....")
except ValueError:
print("\nDon't enter strs , symbols and alpha-numerics")
else:
print("------------------------------------")
print("Val of a=",a)
print("Val of b=",b)
print("Div=",c)
print("------------------------------------")
finally:
print("\nI am from finally block")
==========================================================
Exception Handling in Python
Examples:
#kvr.py ------- file name and acts as module name
Class KvrDivisionError(Exception): pass
#divdemo.py
from Div import division
from kvr import KvrDivisionError
try:
a=int(input(“Enter First Value:”))
b=int(input(“Enter second Value:”))
res= division(a/b)
except KvrDivisionError:
print(“\nDon’t Enter Zero as Denominator”)
except ValueError:
print(“\nDon’t Enter strs, symbols and alpha-numerics”)
else:
print(“Div=”,res)
finally:
print(“I am from finally block”)
Purpose of Files.
Types of Applications in the context of Files.
Definition of File.
Types of operations on Files:
a) Write Operation b) Read Operation
Types of Files:
a) Text Files b) Binary Files
Files Opening Modes:
1) r 2) w 3) a 4) r+ 5) w+ 6) a+ 7) x
Syntax for Opening Files:
a) by using open()
b) by using ‘with open() as’
Programming examples
os module
Working with CSV files.
csv module:
1) csv reader
2) csv writer
3) csv dict reader
4) csv dict writer
Programming examples
CSV in Pandas
JSON FILES in Python
Files in Python
The purpose of Files in any programming language is that “To maintain
Data Persistency”.
The Process of storing the data permanently is called Data Persistency.
In the context of, we can develop two types of Applications, they are:
1) Non-Persistent Application
2) Persistent Application
Examples:
All our previous examples comes under Non-persistent Application.
Operations on Files
Steps:
1. Choose the file name.
2. Open the file name in write mode.
3. Perform cycle of write operations.
2) Read Operation: The purpose of read operation is that “To read data
from file of secondary memory into object of main memory”.
Steps:
1. Chose the file name.
2. Open the file name in read mode.
3. Perform cycle of read operations.
1) Text File: A text file is one which contains Alphabets, Digits and
Special Symbols.
2) Binary file: A binary file always contains data in the form of binary
data format.
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.
1. r mode: This mode is use for opening the file name in read mode . it
is one of the default file mode. If we open the file name in ‘r’ mode
and if the file does not exist then we get ‘FileNotFoundError’.
2. w mode: This mode is used to creating the file and opening the file in
write mode always. When we open NEW FILE in ‘w’ mode then new
file will be opened in write mode and data written from beginning of
the file always. When we open EXISTING FILE in ‘w’ mode then
existing data of the existing file OVERLAPPED with NEW DATA.
3. a mode: This mode is used to creating the file and opening the file in
write mode always. When we open NEW FILE in ‘a’ mode then new
file will be opened in write mode and data written from beginning of
the file always. When we open EXISTING FILE in ‘a’ mode the existing
file APPENEDED with NEW DATA.
4. r+ mode: This mode is also used for opening the file in ‘r’ mode and
perform read operation. After reading the data from file and latter
we can also perform write operation. When we open the file in ‘r+’
mode and if the file doen not exist then we get ‘FileNotFoundError’.
Files in Python
5. w+ mode: This mode is used for opening the file in write mode and
perform write operation always and latter additionally we can
perform read operation also. When we open NEW FILE in ‘w+’ mode
the new file will be opened in write mode and data written from
beginning of the file always and lattes we can read the data also.
When we open EXISTING FILE in ‘w+’ mode then existing data of the
existing file OVERLAPPED with NEW DATA and latter we can read the
data also.
6. a+ mode: This mode is used creating the file and opening the file in
write mode always and perform write operation First and Latter
additionally we can perform read Operation also. When we open
NEW FILE in ‘a+’ mode the new file will be opened in write mode and
data written from the beginning of the file always and later we can
perform read operation. When we open EXISTING FILE in ‘a+’ mode
then existing data of the existing file APPENDED with NEW DATA and
later we can perform read operation.
7. ‘x’ mode: This mode is used for creating the new file and opening
that file in write mode eXclusively. If we open existinf file in ‘x’ mode
then PVM generates ‘FileExistError’.
-----------------------------------------------------------------------------------------------
Files in Python
Pictorial Explanation of read and write operation:
-----------------------------------------------------------------------------------------------
Pictorial Explanation of Persistent and non-persistent Application:
Files in Python
1) By using open():
Explanation:
‘varname’ is an object pointing to the file and it is called File Pointer.
-Here ‘File Name’ represents Name of the File.
-Here ‘File Mode’ represents any File Opening mode ( r, w, a, r+, w+, a+,x)
To write the data to the file, we have one pre-defined function in file
pointer object, They are:
1. write()
1. write(): This function is used for writing any type of data to file in the
form od str. If we have non-str data then convert into str type and
then write in to the file.
Syntax: filepointer.write(str data)
Files in Python
Examples:
To read the data from the file, we have one pre-defined functions
present in file pointer object. They are:
1) read()
1) read() : This function is used for reading entire content of the file in
the form of str.
Syntax: varname = filepointer.read()
Here varname is an object of type <class, str>
------------------------------------------------------------------------------------------
Example: FileReadEx1.py
--------------------------------------------------------------
#write a python program which will read entire data from the
file----read()
#FileReadEx1.py
fname=input("Enter File Name:")
try:
with open(fname) as fp:
filedata=fp.read()
print("-"*40)
print(filedata)
print("-"*40)
except FileNotFoundError:
print("file does not exists")
------------------------------------------------------------------------------------------
Files in Python
except ValueError:
print("Don't enter strs, symbols and alpha-
numerics for stno and marks")
==========================================================
Files in Python
#write a python program which wiil read student records from
the file----Program-B)
#studunpickex.py
import pickle
try:
with open("studinfo.data","rb") as fp:
print("-"*50)
print("Stno\tName\tMarks")
print("-"*50)
while(True):
try:
record=pickle.load(fp)
for val in record:
print("{}".format(val),end="\t")
print()
except EOFError:
print("-"*50)
break
except FileNotFoundError:
print("File does not exist")
==========================================================
OS Module
If the folder name already exist and if we attempt to create again then
we get FileExistsError as an exception. By using mkdir(), we can create
one folder at a time but not possible to create folders hierarchy (if we
do so we get FileNotFoundError)
Exapmles:
#Program for creating a folder
#mkdirex.py
import os
try:
os.mkdir("PYTHON")
print("Folder created successfully-verify")
except FileExistsError:
print("Folder already exist--try with another one")
except FileNotFoundError:
print("with mkdir(), we can't create Folders Hierarchy")
==========================================================
3) Creating folder Hierarchy--- makedirs(): To create folder hierarchy,
we use makedirs() os module.
Examples:
#program for removing a folder
#rmdirex.py
import os
try:
os.rmdir("C:\PYTHON")
print("Folder Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folder is not empty-can't remove")
==========================================================
5) Remove Folders hierarchy --- removedir(): To remove folders
hierarchy represent root folder, sub-folder, sub-sub folder etc.
Examples:
#program for removing a folders hierarchy
#removedirsex.py
import os
try:
os.removedirs("C:\INDIA\TS\AMPT\python")
print("Folders Hiearchy Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folders hierarhcy is not empty-can't remove")
==========================================================
6) List the files of folder--- listdir(): To list the files in a folder, we use
listdir().
Examples:
#Program for listing the files in a folder
#listdirex.py
import os
try:
files=os.listdir("E:\PYTHON\FILES")
print("Number of files =",len(files))
for file in files:
print(file)
except FileNotFoundError:
print("File does not exists")
=========================================================
7) Rename a folder---rename(): To rename a folder, we use rename().
Examples:
#Program for renaming a folder
#renamefolderex.py
import os
try:
os.rename("E:\PYTHON\FILESPROG","E:\PYTHON\FILESUPDATE”)
print("Folder renamed")
except FileNotFoundError:
print("Folder does not exists")
=========================================================
#program for removing a folder
#rmdirex.py
import os
try:
os.rmdir("C:\PYTHON")
print("Folder Removed")
except FileNotFoundError:
print("File does not exists")
except OSError:
print("Folder is not empty-can't remove")
==========================================================
A csv file is one of the simple file format used to store tabular data,
such as a spreadsheet or data (numbers and text) in plain text. Each line
of the csv file is a data record. Each record consists of one or more
fields, separated by commas.
Python provides an in-built module called csv to work with csv files.
There are two classes provided in this module for writing the data to csv
file, they are:
a) writerow() b) writerows()
a) writerow(): This method writes a single row at a time. Field row can
be written using this method.
Syntax: csvwriteobj.writerow(fields rows/data rows)
There are various ways to read a csv file that uses either the csv module
of the pandas library.
The csv module provides classes for reading information from csv file.
1) csv.reader 2) csv.DictReader
Examples:
=========================================================
Files in Python
#Program for reading the data from CSV file by using csv
module----student.csv
#csvreaderex2.py
import csv
try:
with open("univ1.csv","r") as fp:
cr=csv.reader(fp)
for record in cr:
for val in record:
print("{}".format(val),end="\t")
print()
except FileNotFoundError:
print("File does not exist")
-----------------------------------------------------------------------------------------------
Name Branch Year CGPA
Nikhil CSE 2 9
Aditya IT 2 9.3
Sagar SE 1 9.5
Sahil EP 2 9.1
KVR CSE 2 9
=========================================================
#Program for reading the data from CSV file by using csv
module----student.csv
#csvreaderex3.py
import csv
try:
with open("univ2.csv","r") as fp:
dcr=csv.DictReader(fp)
print("-"*40)
for record in dcr:
for k,v in record.items():
print("\t{}-->{}".format(k,v))
print("-"*40)
except FileNotFoundError:
print("File does not exist")
-----------------------------------------------------------------------------------------------
Files in Python
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 without using csv
module----student.csv
#noncsvex.py
try:
with open("student.csv","r") as fp:
csvfiledata=fp.read()
print(csvfiledata)
except FileNotFoundError:
print("File does not exist")
==========================================================
Files in Python
# field names
csvfields = ['name', 'branch', 'year', 'cgpa']
Even we achived the Data Persistency by using Files, Files has the following
Limitations:
1. Files of any language does not contain security because Files are
unable to provide security in the form of User Name and
Password.
2. Files are unable to store large amount of data.
3. File are different from one OS to another OS (Files are OS
dependent)
4. Querying and Processing the data from Files is very Complex
because file data is organised w.r.t Indices and identifying the
indices is very complex.
5. Files does not contain Column Name (Except CSV Files)
Syntax: pip install module name (at any windows command prompt)
==============================X==============================
Files in Python
Explanation:
1. Import cx_Oracle module: if a python program want to perform any
DB operation (insert, delete, update, read records…etc) then we must
import a pre-defined third-party module “cx_Oracle”.
2. Python Program must get the connection from Oracle DB: To do any
DB operations, First python program must get the connection from
Oracle.
4. Python Program must prepare the Query and Execute the Query in
Oracle DB: A Query is a statement or Request or Question to DB
doftware for obtaining data base results.
5. Python Program Prosess the result of the Query: After Executing DML
statements, the result of DML statements is present in cursor object.
Syntax: SQL> create table <table name> (col name1 database data type,
col name2 database data type,….col name-n database data type);
b) alter: This Query is used for alter the table structure such as
modifying (modify) the column sizes and adding (add) new columns.
Syntax1: SQL> alter table <table name> modify (existing col name1
database datatype…. Existing col name-n database data type);
Syntax2: SQL> alter table <table name> add (new col name1 database
datatype….new col name-n database data type);
c) drop: This query is used for remving the table from Database
software.
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#step-4
cur.execute("drop table student")
print("Student Table droped / removed from Oracle
DB sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)
================================================
Files in Python
#TableDropDemo.py
from TableDropEx import tabledrop as td
td()
================================================
#Program for altering the by the means of adding new columns
to Employee Table
#TableAlterAdd.py
import cx_Oracle # 1
def aftercolumnAdd():
try:
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#step-4
aqa="alter table employee add(cname varchar2(10))"
cur.execute(aqa)
print("Employee altered sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)
#main program
aftercolumnAdd()
======================================
#Program for altering the column sizes of Employee Table
#TableAlterModi.py
import cx_Oracle # 1
def aftercolumnsizes():
try:
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe") # 2
cur=con.cursor() # 3
#step-4
aqm="alter table employee modify(eno number(3),sal
number(9,2))"
cur.execute(aqm)
print("Employee altered sucessfully")
except cx_Oracle.DatabaseError as db:
print("Prob in Database:",db)
#main program
aftercolumnsizes()
======================================
2. DML (Data Manipulating Language) Queries:
The purpose of DML operationa is that “To manipulate the table such as
inserting the records, deliting the records and updating the records”.
Syntax: SQL> insert into <table name> values(val1 for col1,val2 for
col2… val-n for col-n)
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;
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
#prepare Query and execute
iq="insert into employee values
(70,'SV',4.5,'HCL') "
cur.execute(iq)
con.commit()
print("{} Employee Record Inserted
Successfully".format ( cur.rowcount) )
#main program
emprecordinsert()
==========================================================
Files in Python
To get the records from cursor object, we have 3 fuctions. They are :
1) Fetchone() 2) fetchmany(no. of records) 3) fetchall()
c) Fectchall(): It is used for obtaining all the records from cursor object.
==========================================================
Examples:
-------------
#Program selecting or reading all the records from employee
table--fetchone()
#selectex1.py
import cx_Oracle
def selectrecords():
try:
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
cur.execute("select * from employee")
print("="*40)
while(True):
record=cur.fetchone()
if(record==None):
break
else:
for val in record:
print("{}".format(val),end="\t")
print()
Files in Python
print("="*40)
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
cur.execute("select * from employee")
records=cur.fetchmany(3)
print("="*40)
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("="*40)
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
#main program
selectrecords()
==========================================================
#Program selecting or reading all the records from employee
table--fetchall()
#selectex3.py
import cx_Oracle
def selectrecords():
try:
con=cx_Oracle.connect("system/ritik@127.0.0.1/xe")
cur=con.cursor()
cur.execute("select * from employee")
records=cur.fetchall()
print("="*40)
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("="*40)
except cx_Oracle.DatabaseError as db:
print("Problem in Database:",db)
#main program
selectrecords()
==========================================================
Files in Python
Explanation:
1. Import mysql.connector module: If a python program want to
perform any DB operations(insert, delete, update record, read
records…etc) then we must import a pre-defined third party module
“myqsl-connector”.
We know that a module is a collection of Variables, Function Name and
Class Name.
Example: import my-conector
2. Python program must get the connection from MySQL DB: To do any
DB Operation, First python program must get the connection from
MySQL. To get the connection from any DB, we use connect()which is
present in mysql.connector module.
4. Python program must Prepare the Query and Excecute the query in
MySQL DB: A Query is a statement or result or Question to database
software for obtaining data base results.
Syntax: cursorobj.execute(“Query”)
c) Fectchall(): It is used for obtaining all the records from cursor object.
==========================================================
Files in Python
Examples:
#Program obtaining connection from MySQL
#TestMySqlcon.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd="root")
print("type of con=",type(con))
print("Python got connection from MySQL")
==========================================================
#Program creating an object of cursor
#TestMySqlCur.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd="root")
cur=con.cursor()
print("type of cur=",type(cur))
print("Python Program created an object of cursor")
==========================================================
#Program creating a data base in mysql on the name of batch6pm
#DatabaseCreate.py
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",
passwd="root")
cur=con.cursor()
#prepare qurey and execute
dcq="create database"
cur.execute(dcq)
print("Database created successfully in MySQL")
==========================================================
Files in Python
#Program creating a table in batch6pm database on the name of
employee
#TableCreate.py
import mysql.connector
try:
con=mysql.connector.connect(host="localhost",
user="root",
passwd="root",
database="batch6pm" )
cur=con.cursor()
#prepare query and execute
tq="create table student (sno int primary key, sname
varchar(10) not null, marks float not null, cname varchar(10)
not null ) "
cur.execute(tq)
print("Table created in MySQL--Verify")
except mysql.connector.DatabaseError as db:
print("Problem in Database:",db)
==========================================================
Object Oriented Principle or features or concepts
in Python
1. Classes:
Even program in OOPs must starts with class concept, without classes
we can’t develop single program.
Definition of Class:
A class is a collection of Data members and methods. When we define a
class, memory spase is not created for Data Members and methods but
whose memory space created when we create an object w.r.t Class.
class <clsname>:
class level data members
def instancemethod(self, list of formal parms if any):
---------------------------------------------------------------------
---------------------------------------------------------------------
Specify instance data members and perform specific oprations
---------------------------------------------------------------------
---------------------------------------------------------------------
@classmethod
def classmethod(cls,list of formal params if any):
--------------------------------------------------------------------
--------------------------------------------------------------------
Specify class level data members and perform common operations
--------------------------------------------------------------------
--------------------------------------------------------------------
@staticmethod
def staticmethod(list of formal params if any):
-------------------------------------------------------------------
-------------------------------------------------------------------
Perform utility / Universal Operations
-------------------------------------------------------------------
-------------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python
Objects in Python
Definition of Object:
Objects:
1) Instance of a class is called Object.
2) When we created an object, we get the memory space for Data
members and methods of Class.
3) W.r.t One class definition, we can create multiple objects.
4) We can create an object after loading the class definition otherwise
we get NameError.
Instance Data Members are always used for storing Specific Values.
Class Level Data Member are those, whose memory space is created
only once irrespective of number of object are created.
Class Level Data Member are used for storing common values.
Class Level Data Member can be accessed either w.r.t class name or
Object name or self or cls.
#main program
s1=Student()
s2=Student()
#Add the Instance data members to s1 (Through an Object)
s1.sno=10
s1.sname="RS"
s1.marks=22.22
#Add the Instance data members to s2(Through an Object)
s2.stno=20
s2.name="TR"
s2.marks=33.22
s2.cname="OUCET"
#display content of s1
print("-------------------------------------")
print("Content of s1 object:")
print("-------------------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("-------------------------------------")
#display content of s2
print("Content of s2 object:")
print("-------------------------------------")
print("Student Number:{}".format(s2.stno))
print("Student Name:{}".format(s2.name))
print("Student Marks:{}".format(s2.marks))
print("Student College:{}".format(s2.cname))
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#program for storing student number,name and marks
#studex3.py
class Student:pass # Here Student is called Programmer-
defined Data Type.
#main program
s1=Student()
s2=Student()
print("-----------------------------------------")
#Add the Instance data members to s1 (Through an Object)
print("Enter First Student details:")
print("-----------------------------------------")
s1.sno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
#Add the Instance data members to s2(Through an Object)
print("Enter Second Student details:")
print("-----------------------------------------")
s2.sno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
print("Content of s1 object:")
print("-------------------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("-------------------------------------")
#display content of s2
print("Content of s2 object:")
print("-------------------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#program for storing student number,name and marks
#studex4.py
class Student: # Here Student is called Programmer-defined
Data Type.
crs="PYTHON" # here crs is called Class Level Data
Member
#main program
s1=Student()
s2=Student()
print("-----------------------------------------")
#Add the Instance data members to s1 (Through an Object)
print("Enter First Student details:")
print("-----------------------------------------")
s1.sno=int(input("Enter Student Number:"))
s1.sname=input("Enter Student Name:")
s1.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
#Add the Instance data members to s2(Through an Object)
print("Enter Second Student details:")
print("-----------------------------------------")
s2.sno=int(input("Enter Student Number:"))
s2.sname=input("Enter Student Name:")
s2.marks=float(input("Enter Student Marks:"))
print("-----------------------------------------")
print("Content of s1 object:")
print("-------------------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("Student Course:{}".format(s1.crs) ) # OR s1.crs
print("-------------------------------------")
#display content of s2
print("Content of s2 object:")
print("-------------------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("Student Course:{}".format(s2.crs) ) # OR s2.crs
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#CircleAreaPeri.py
class Circle:
PI=3.14
#main program
c=Circle()
c.r=float(input("Enter Radious:"))
c.ar=Circle.PI*c.r**2
c.pr=2*Circle.PI*c.r
print("----------------------------------")
print("Radious={}".format(c.r))
print("Area of Circle={}".format(c.ar))
print("Perimeter of Circle={}".format(c.pr))
print("----------------------------------")
==========================================================
1. Instance method:
Objectname.instancemethodname()
Or
Self.instancemethodname()
What is self:
Self is one of the implicit object used as a first formal parameter in the
definition of instance method.
Class level Methos are used for performing class level operations such
as specifying class level data members and perform operations on them
(if required).
Class level methods always takes “cls” as first positional parameters for
obtaining current class name.
Syntax: @classmethod
def classlevelmethodname(cls, list of formal params)
----------------------------------------------------------------
--------common operation-------------------------------
----------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python
Every class level method can be accessed w.r.t class name or cls or
object name or self.
Classname.class level method name()
Or
Cls.class level method name()
Or
Objectname.class level method name()
Or
Self.class level method name()
What is cls:
Cls is one of the implicit object used as a first formal parameter in the
definition of class level method.
Cls is applicable for class level data member and class level methods only.
3. Static method:
Static method are those which are used for performing utility operation
or Universal Operation.
Static methods definition neither takes “self” nor takes “cls” but it takes
an object as parameter (if req) which belongs other classes.
Syntax: @staticmethod
Def staticmethodname (list of formal params if any):
---------------------------------------------------------------------
----------------Ulitity or Universal Operations-------------
---------------------------------------------------------------------
Object Oriented Principle or features or concepts
in Python
Statics Methods must be accessed w.r.t class name or object name.
Classname.staticmethodname()
Or
Objectname.staticmethodname()
Examples:
-------------
#Program for reading student details from KBD and dispay by
using Classes and Objects
#InstMethodEx1.py--file name and acts module name
class Student:
def readstudvalues(self ):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstudvalues(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))
#main program
s1=Student()
s2=Student()
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
=========================================================
Object Oriented Principle or features or concepts
in Python
#Program for reading two numerical values and find sum by
using Classes and Objects
#InstMethodEx2.py--file name and acts module name
class Sum:
def readvalues(self):
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
def sumop(self):
self.c=self.a+self.b
def dispvalues(self):
return self.a,self.b,self.c
#main program
s=Sum()
s.readvalues()
s.sumop()
res=s.dispvalues()
print("sum({},{})={}".format(res[0],res[1],res[2]))
========================================================
#Program for reading two numerical values and find sum by
using Classes and Objects
#InstMethodEx3.py--file name and acts module name
class Sum:
def readvalues(self): # Instance Method
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))
self.sumop() # calling sumop() from readvalues()
print("sum({},{})={}".format(self.a,self.b,self.c))
#main program
s=Sum()
s.readvalues()
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx1.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"
#main program
Student.getcourse1() # calling Class Level Method
Student.getcourse2() # calling Class Level Method
s1=Student()
s2=Student()
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx2.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"
#main program
s1=Student()
s2=Student()
s1.getcourse1() # calling Class Level Method
s2.getcourse2() # calling Class Level Method
#read the values for s1
print("Enter First Student details:")
print("-----------------------------------------")
s1.readstudvalues()
print("-----------------------------------------")
#read the values for s2
print("Enter Second Student details:")
print("-----------------------------------------")
s2.readstudvalues()
print("-----------------------------------------")
#Display the content of s1
print("Content of First Student object:")
print("-------------------------------------")
s1.dispstudvalues()
print("-------------------------------------")
print("Content of Second Student object:")
print("-------------------------------------")
s2.dispstudvalues()
print("-------------------------------------")
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program accepting student details(Instance Method)along with
common value(Class Level Method)
#ClassMethodEx3.py
class Student:
@classmethod
def getcourse1(cls): # Class Level Method
cls.crs1="PYTHON"
cls.getcourse2() # One class level can call
another class level method
@classmethod
def getcourse2(cls): # Class Level Method
Student.crs2="Data Sci"
class Hyd:
@staticmethod
def dispobjvalues(kvr):
print("="*40)
for k in kvr.__dict__:
print("\t{}--->{}".format(k,
kvr.__dict__.get(k)))
print("="*40)
#main program
e=Employee() # create an object of Employee
s=Student() # create an object of Student
t=Teacher() # # create an object of Teacher
#Read the values for employee object
e.readempvalues()
#Read the values for Student object
s.readstudvalues()
#Read the values for teacher object
t.readteachervalues()
#Today i want to define single method, which will print / display any
type of object values--called static method
print("Employee Information")
Hyd.dispobjvalues(e)
print("Student Information")
Hyd.dispobjvalues(s)
print("Teacher Information")
Hyd.dispobjvalues(t)
==========================================================
Object Oriented Principle or features or concepts
in Python
#staticmethodex2.py
class Employee:
def readempvalues(self):
print("-"*50)
self.eno=int(input("\nEnter Employee Number:"))
self.ename=input("Enter Employee Name:")
self.sal=float(input("Enter Employee Salary:"))
print("-"*50)
class Student:
def readstudvalues(self):
print("-"*50)
self.sno=int(input("\nEnter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
self.cname=input("Enter Student College:")
print("-"*50)
class Teacher:
def readteachervalues(self):
print("-"*50)
self.tno=int(input("\nEnter Teacher Number:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
print("-"*50)
class Hyd:
@staticmethod
def dispobjvalues(kvr):
print("="*40)
for k in kvr.__dict__:
print("\t{}--->{}".format(k,
kvr.__dict__.get(k)))
print("="*40)
#main program
e=Employee() # create an object of Employee
s=Student() # create an object of Student
t=Teacher() # # create an object of Teacher
#Read the values for employee object
e.readempvalues()
#Read the values for Student object
s.readstudvalues()
#Read the values for teacher object
t.readteachervalues()
#Today i want to define single method, which will print /
display any type of object values--called static method
h=Hyd() # Object creation
print("Employee Information")
h.dispobjvalues(e)
print("Student Information")
h.dispobjvalues(s)
print("Teacher Information")
h.dispobjvalues(t)
==========================================================
Object Oriented Principle or features or concepts
in Python
Constructors in Python
#main program
t1=Test()
t2=Test()
t3=Test()
==========================================================
Object Oriented Principle or features or concepts
in Python
2. Parameterized Constructor:
A Constructor is said to be parameterised iff it always takes any
argument(s) or Formal param(s). The purpose of parameterised
constructor is that “To initialised multiple object of same class with
Different values”.
#main progra m
t1=Test(10,20)
t2=Test(100,200)
t3=Test("RS","PYTHON")
==========================================================
Note:
In class of python, we can’t defined both default and parameterised
constructors because PVM can remember only latest constructor (due
to it’s interpretation process). We defined single constructor with
default parameter mechanism.
Object Oriented Principle or features or concepts
in Python
Example:
------------
#DefultParamConstEx1.py
class Test:
def __init__(self,a=1,b=2):
print("i am from Default /Parameterized
Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))
#main progra m
t1=Test() # Object Creation calls Default Constructor
t2=Test(100,200) # Object Creation calls Parameterized
Constructor
==========================================================
#ConstEx1.py
class Student:
def getstudvalues(self):
self.sno=10
self.sname="RS"
#main program
s=Student() # Object Creation---- i want place my own data
without leaving an object empty.
print(s.__dict__)
s.getstudvalues()
print(s.__dict__)
==========================================================
#ConstEx2.py
class Student:
def __init__(self):
print("I am from default constructor")
self.sno=10
self.sname="RS"
#main program
s=Student() # Object Creation---- i want place my own data
without leaving an object empty.
print(s.__dict__)
==========================================================
Object Oriented Principle or features or concepts
in Python
#ConstEx3.py
class Student:
def __init__(self,sno,sname):
print("I am from Parameterfized constructor")
self.sno=sno
self.sname=sname
#main program
s1=Student(10,"DR") # Object Creation---- i want place my own
data without leaving an object empty.
print(s1.__dict__)
s2=Student(20,"TR") # Object Creation---- i want place my own
data without leaving an object empty.
print(s2.__dict__)
==========================================================
#DefConstEx1.py
class Test:
def __init__(self):
print("i am from Default Constructor:")
self.a=10
self.b=20
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))
#main progra m
t1=Test()
t2=Test()
t3=Test()
==========================================================
#DefultParamConstEx1.py
class Test:
def __init__(self,a=1,b=2):
print("i am from Default /Parameterized
Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))
#main progra m
t1=Test() # Object Creation calls Default Constructor
t2=Test(100,200) # Object Creation calls Parameterized
Constructor
==========================================================
Object Oriented Principle or features or concepts
in Python
#Program for can Factorial of agiven Number by using Classes
and Objects
#Fact.py
import sys
class Fact:
def __init__(self):
try:
self.n=int(input("Enter Value of n:"))
except ValueError:
print("Don't enter Strs, symbols and alpha-
numric")
sys.exit()
def calfact(self):
if(self.n<0):
print("{} is invalid
input:".format(self.n))
else:
f=1
for i in range(1,self.n+1):
f=f*i
else:
print("Factorial({})={}".format(self.n,f))
#main program
fo=Fact() # Object Creation---calls default constructor
fo.calfact()
==========================================================
#Program for can Factorial of agiven Number by using Classes
and Objects
#Fact1.py
class Fact:
def __init__(self):
self.n=int(input("Enter Value of n:"))
def calfact(self):
if(self.n<0):
print("{} is invalid
input:".format(self.n))
else:
f=1
for i in range(1,self.n+1):
f=f*i
else:
print("Factorial({})={}".format(self.n,f))
#main program
try:
fo=Fact() # Object Creation---calls default constructor
fo.calfact()
except ValueError:
print("Don't enter Strs, symbols and alpha-numric")
==========================================================
Object Oriented Principle or features or concepts
in Python
#ParamConstEx1.py
class Test:
def __init__(self,a,b):
print("i am from Parameterized Constructor:")
self.a=a
self.b=b
print("Value of a:{}".format(self.a))
print("Value of b:{}".format(self.b))
#main progra m
t1=Test(10,20)
t2=Test(100,200)
t3=Test("RS","PYTHON")
==========================================================
Garbage Collection:
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=Student(20,"Umesh")
print("Program Execution Ended:")
time.sleep(5)
#Here GC calls destructor automatically when the program
execution completed---This is called automatic Garbage
Collection.
=========================================================
Object Oriented Principle or features or concepts
in Python
#destex3.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
s1=None
time.sleep(5)
s2=Student(20,"Umesh")
s3=Student(30,"Rossum")
s4=Student(40,"Ritche")
print("Program Execution Ended:")
time.sleep(5)
#Here GC calls destructor automatically when the program
execution completed---This is called automatic Garbage
Collection.
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex4.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
s1=None # Forcefully calling GC
time.sleep(5)
s2=Student(20,"Umesh")
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
s2=None # Forcefully calling GC
time.sleep(5)
s3=Student(30,"Rossum")
print("No Longer Interested to maintain s3 object:")
time.sleep(5)
s3=None # Forcefully calling GC
time.sleep(5)
s4=Student(40,"Ritche")
print("No Longer Interested to maintain s4 object:")
time.sleep(5)
s4=None # Forcefully calling GC
time.sleep(5)
print("Program Execution Ended:")
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex5.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
del s1 # Forcefully calling GC
time.sleep(5)
s2=Student(20,"Umesh")
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
del s2 # Forcefully calling GC
time.sleep(5)
s3=Student(30,"Rossum")
s4=Student(40,"Ritche")
print("No Longer Interested to maintain s3 object and s4
object:")
time.sleep(5)
del s3 # Forcefully calling GC
del s4 # Forcefully calling GC
time.sleep(5)
print("Program Execution Ended:")
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex6.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print(id(s1),id(s2),id(s3))
print("Program Execution Ended:")
# Even we create three objects with Deep Copy Process, There
exist simgle memory space and all three objects points same
memory space. At the end of the program GC calls only once
destructor Function.
==========================================================
#destex7.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
del s1 # Forcefully calling GC
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
del s2 # Forcefully calling GC
print("Program Execution Ended:")
==========================================================
Object Oriented Principle or features or concepts
in Python
#destex8.py
import time
class Student:
def __init__(self,sno,sname): # Constructor called by
PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating
Memory space:")
#main program
print("Program Execution Started:")
s1=Student(10,"Litun")
s2=s1 # Deep Copy
s3=s1 # Deep Copy
print("No Longer Interested to maintain s1 object:")
time.sleep(5)
del s1 # Forcefully calling GC
print("No Longer Interested to maintain s2 object:")
time.sleep(5)
del s2 # Forcefully calling GC
print("No Longer Interested to maintain s3 object:")
time.sleep(5)
s3=None # Forcefully calling GC
print("Program Execution Ended:")
==========================================================
#gcex1.py
import gc
print("Line--3: Is is GC Running=", gc.isenabled()) # True
print("This is Python Class")
print("Python developed by RS")
gc.disable()
print("Line No:7-->Is is GC Running=", gc.isenabled()) # False
print("Python is an oop lang")
gc.enable()
print("Line--10: Is is GC Running=", gc.isenabled()) # True
print("Python is Fun lang")
==========================================================
Object Oriented Principle or features or concepts
in Python
#gcex2.py
import time,gc
class Student:
def __init__(self,sno,sname): # Constructor called by PVM
self.sno=sno
self.sname=sname
print("\t{}\t{}".format(self.sno,self.sname))
def __del__(self): # Destructor called by GC
print("GC calls __del__(self)-for de-allocating Memory
space:")
#main program
print("Program Execution Started:")
print("Line--13: Is is GC Running=", gc.isenabled()) # True
s1=Student(10,"Litun")
s2=Student(20,"Umesh")
gc.disable()
print("Line--17: Is is GC Running=", gc.isenabled()) # False
print("Program Execution Ended:")
time.sleep(5)
#Here GC calls destructor automatically when the program execution
completed---This is called automatic Garbage Collection.
==========================================================
Inheritance
Types of Inheritences:
1. Single Inheritence
2. Multi Level Inheritence
Object Oriented Principle or features or concepts
in Python
To Inherit the features of Base Class into Derived Class, we use the
following Syntax:
Class <clsname-1>:
-------------------------------
-------------------------------
Class <clsname-2>:
-------------------------------
-------------------------------
---------------------------------------
Class <clsname-n>:
-----------------------------
-----------------------------
Class <clsname-n+1>(clsname-1,clsname-2,…clsname-n) :
-----------------------------
-----------------------------
Explanation:
Here clsname-1,clsname-2,…..clsname-n are called Base or Super Classes.
<clsname-n=1> is called Derived or Sub-class.
For every clss in python, there exist a predefined implicite base class called
“object” because it provides Garbage Collection to all it’s sub classes.
Object Oriented Principle or features or concepts
in Python
Examples:
---------------
#InhProg1.py
class BC:
def getN(self):
self.n=float(input("Enter a number:"))
class DC(BC):
def square(self):
self.sq=self.n**2
def disp(self):
print("square({})={}".format(self.n,self.sq))
#main program
do1=DC()
do1.getN()
do1.square()
do1.disp()
===========================================================
#InhProg2.py
class BC:
def getN(self):
self.n=float(input("Enter a number:"))
class DC(BC):
def square(self):
self.sq=self.n**2
def disp(self):
self.getN() # Calling Base Class Instance Method
Name
self.square() # Calling Current Class Instance
Method Name
print("square({})={}".format(self.n,self.sq))
#main program
do1=DC()
do1.disp()
===========================================================
Object Oriented Principle or features or concepts
in Python
Examples:
---------------
#methodoverex1.py
class Circle:
def draw(self): # original Method
print("Drawing Circle")
class Rect(Circle):
def draw(self): # overridden Method
print("Drawing Rect:")
super().draw()
class Square(Rect):
def draw(self): # overridden Method
print("Drawing Square:")
super().draw()
#main program
so=Square()
so.draw()
=============================================================
Object Oriented Principle or features or concepts
in Python
#teacher.py
class Teacher:
def readsub(self):
print("Teacher advises to read 2 hours")
class LazyStudent(Teacher):
def readsub(self):
print("LazyStudent never read at all")
class PerfectStudent(Teacher):
def readsub(self):
print(" Perfect Student 2hrs reading and
practicing")
ls=LazyStudent()
ls.readsub()
ps=PerfectStudent()
ps.readsub()
============================================================
Polymorphism in Python
Def. of Polymorphism:
The process of representating “One Form in multiple Form” is called
polymorphism”.
With super() we are able to call only one immediate base class method but
unable to call specified method of base class. To do this we must use clss
name approach.
2. By using class name: By using class name approach, we can call any base
class method/ constructor name from the context of derived class
method / constructor names.
class Rect(Circle):
def __init__(self): ## Overridden Constructor (Multiple
Forms)
print("Drawing--Rect--DC")
class Square(Rect):
def __init__(self): # Overridden Constructor (Multiple
Forms)
print("Drawing--Square--DC")
#main program
s=Square()
=============================================================
#MethodOverEx1.py
class Circle:
def draw(self): # Original Method (One Form )
print("Drawing--Circle")
class Rect(Circle):
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Rect")
class Square(Rect):
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Square:")
#main program
print("w.r.t Square")
s=Square()
s.draw()
=============================================================
Object Oriented Principle or features or concepts
in Python
#NonMethodOver.py
class Circle:
def draw1(self):
print("Drawing--Circle")
class Rect(Circle):
def draw2(self):
print("Drawing---Rect")
#main program
r=Rect()
r.draw1()
r.draw2()
===========================================================
#PolyEx1.py
class Circle:
def draw(self): # Original Method (One Form )
print("Drawing--Circle")
class Rect:
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Rect")
class Square(Circle,Rect):
def draw(self): # Overriddent Method (Multiple Forms)
print("Drawing Square")
super().draw()
Rect.draw(self)
#main program
s=Square()
s.draw()
============================================================
#PolyEx2.py
class Circle:
def __init__(self): # Original Constructor (One Form )
print("Drawing--Circle")
class Rect:
def __init__(self): # Overridden Constructor (Multiple
Forms)
print("Drawing--Rect--DC")
class Square(Circle,Rect):
def __init__(self): # Overridden Constructor (Multiple
Forms)
print("Drawing--Square--DC")
Rect.__init__(self)
super().__init__()
#main program
s=Square()
=============================================================
Object Oriented Principle or features or concepts
in Python
#write a python program which will calculate area of different
figures by using polymorphism
#PolyEx3.py
class Circle:
def area(self,r):
print("-"*50)
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
print("-"*50)
class Square(Circle):
def area(self,s):
print("-"*50)
self.sa=s**2
print("Area of Square:{}".format(self.sa))
print("-"*50)
class Rect(Square):
def area(self,l,b=0):
print("-"*50)
self.ar=l*b
print("Area of Rect:{}".format(self.ar))
print("-"*50)
Circle.area(self,float(input("Enter Radious:")))
super().area(float(input("Enter Side:")))
#main program
r=Rect()
r.area(float(input("Enter Length:")),float(input("Enter
breadth:")) )
============================================================
Object Oriented Principle or features or concepts
in Python
#write a python program which will calculate area of different
figures by using polymorphism
#PolyEx4.py
class Circle:
def __init__(self,r):
print("-"*50)
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
print("-"*50)
class Square:
def __init__(self,s):
print("-"*50)
self.sa=s**2
print("Area of Square:{}".format(self.sa))
print("-"*50)
class Rect(Square,Circle):
def __init__(self,l,b=0):
print("-"*50)
self.ar=l*b
print("Area of Rect:{}".format(self.ar))
print("-"*50)
super().__init__(float(input("Enter Side:")))
Circle.__init__(self,float(input("Enter
Radious:")))
#main program
r=Rect(float(input("Enter Length:")),float(input("Enter
breadth:")))
============================================================
Regular Expressions in Python
Index
2) Group (): This function is used obtaining matched value by the finditer().
This function present in match class of “re” Module.
If the search pattern not found in given data then it returns None which
is type <class, “Nonetype”> and it indicates search is unsuccessful.
Examples:
---------------
#RegExpr1.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="Python"
lst=re.findall(sp,gd)
print("'{}' is found {} Times:".format(sp,len(lst)))
==========================================================
#RegExpr2.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="python"
matobj=re.search(sp,gd) # here matobj is an object of
<class , re.match>
if(matobj!=None):
print("\nSearch is Sucessful")
print("Start Index:{} End Index:{}
Value:{}".format(matobj.start(),matobj.end(),matobj.group()) )
else:
print("\nSearch is Not Successful")
==========================================================
#RegExpr3.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="ant"
obj=re.finditer(sp,gd) # Here obj is an object of <class
'callable_iterator'>
for m in obj:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(),m.group()))
==========================================================
Regular Expressions in Python
Examples:
--------------
#RegExpr1.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="Python"
lst=re.findall(sp,gd)
print("'{}' is found {} Times:".format(sp,len(lst)))
===========================================================
#RegExpr2.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="python"
matobj=re.search(sp,gd) # here matobj is an object of
<class , re.match>
if(matobj!=None):
print("\nSearch is Sucessful")
print("Start Index:{} End Index:{}
Value:{}".format(matobj.start(),matobj.end(),matobj.group()) )
else:
print("\nSearch is Not Successful")
===========================================================
#RegExpr3.py
import re
gd="Python is an oop lang. Python is also Fun prog lang"
sp="ant"
obj=re.finditer(sp,gd) # Here obj is an object of <class
'callable_iterator'>
for m in obj:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(),m.group()))
===========================================================
#RegExpr4.py
#Searching for either 'a' or 'b' or 'c' only
import re
mat=re.finditer("[abc]","cAKL5&@9HpaTbU*#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)
"""--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:b
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
#RegExpr5.py
#Searching for all except a' or 'b' or 'c'
import re
mat=re.finditer("[^abc]","cAKL5&@9HpaTbU*#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)
"""
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:K
Start Index:3 End Index:4 Value:L
Start Index:4 End Index:5 Value:5
Start Index:5 End Index:6 Value:&
Start Index:6 End Index:7 Value:@
Start Index:7 End Index:8 Value:9
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:11 End Index:12 Value:T
Start Index:13 End Index:14 Value:U
Start Index:14 End Index:15 Value:*
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
-----------------------------------------"""
==============================================================
#RegExpr6.py
#Searches for Upper Case Alphabets only
import re
mat=re.finditer("[A-Z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)
"""--------------------------------------------------
Start Index:1 End Index:2 Value:A
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:H
Start Index:10 End Index:11 Value:T
Start Index:12 End Index:13 Value:U
Start Index:14 End Index:15 Value:L
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
#RegExpr7.py
#Searches for all except Upper Case Alphabets
import re
mat=re.finditer("[^A-Z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for m in mat:
print("Start Index:{} End Index:{}
Value:{}".format(m.start(),m.end(), m.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:6 End Index:7 Value:9
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:11 End Index:12 Value:b
Start Index:13 End Index:14 Value:*
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
Start Index:19 End Index:20 Value:e
--------------------------------------------------
"""
==========================================================
#RegExpr8.py
#Searches for all lower Case Alphabets only
import re
mat=re.finditer("[a-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:11 End Index:12 Value:b
Start Index:19 End Index:20 Value:e
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr9.py
#Searches for all except lower Case Alphabets.
import re
mat=re.finditer("[^a-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:5 End Index:6 Value:K
Start Index:6 End Index:7 Value:9
Start Index:7 End Index:8 Value:H
Start Index:10 End Index:11 Value:T
Start Index:12 End Index:13 Value:U
Start Index:13 End Index:14 Value:*
Start Index:14 End Index:15 Value:L
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
--------------------------------------------------
"""
=========================================================
#RegExpr10.py
#Searches for all digits
import re
mat=re.finditer("[0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:2 End Index:3 Value:5
Start Index:6 End Index:7 Value:9
Start Index:16 End Index:17 Value:4
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr11.py
#Searches for all except digits
import re
mat=re.finditer("[^0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:H
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:10 End Index:11 Value:T
Start Index:11 End Index:12 Value:b
Start Index:12 End Index:13 Value:U
Start Index:13 End Index:14 Value:*
Start Index:14 End Index:15 Value:L
Start Index:15 End Index:16 Value:#
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr12.py
#Searches for all alphabets
import re
mat=re.finditer("[A-Za-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:5 End Index:6 Value:K
Start Index:7 End Index:8 Value:H
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:10 End Index:11 Value:T
Start Index:11 End Index:12 Value:b
Start Index:12 End Index:13 Value:U
Start Index:14 End Index:15 Value:L
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
--------------------------------------------------"""
==========================================================
#RegExpr13.py
#Searches for all except alphabets
import re
mat=re.finditer("[^A-Za-z]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:6 End Index:7 Value:9
Start Index:13 End Index:14 Value:*
Start Index:15 End Index:16 Value:#
Start Index:16 End Index:17 Value:4
--------------------------------------------------"""
=========================================================
Regular Expressions in Python
#RegExpr14.py
#Searches for all alphabets and Digits only(Except Special
Symbols)
import re
mat=re.finditer("[A-Za-z0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:5 End Index:6 Value:K
Start Index:6 End Index:7 Value:9
Start Index:7 End Index:8 Value:H
Start Index:8 End Index:9 Value:p
Start Index:9 End Index:10 Value:a
Start Index:10 End Index:11 Value:T
Start Index:11 End Index:12 Value:b
Start Index:12 End Index:13 Value:U
Start Index:14 End Index:15 Value:L
Start Index:16 End Index:17 Value:4
Start Index:17 End Index:18 Value:Q
Start Index:18 End Index:19 Value:L
Start Index:19 End Index:20 Value:e
--------------------------------------------------"""
==========================================================
#RegExpr15.py
#Searches for all special symbols except alphabets
import re
mat=re.finditer("[^A-Za-z0-9]","cA5&@K9HpaTbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:@
Start Index:13 End Index:14 Value:*
Start Index:15 End Index:16 Value:#
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr16.py
#Searches for Space Character
import re
mat=re.finditer("\s","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:4 End Index:5 Value:
Start Index:11 End Index:12 Value:
--------------------------------------------------"""
==========================================================
#RegExpr17.py
#Searches for all except Space Character
import re
mat=re.finditer("\S","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:3 End Index:4 Value:&
Start Index:5 End Index:6 Value:@
Start Index:6 End Index:7 Value:K
Start Index:7 End Index:8 Value:9
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:b
Start Index:14 End Index:15 Value:U
Start Index:15 End Index:16 Value:*
Start Index:16 End Index:17 Value:L
Start Index:17 End Index:18 Value:#
Start Index:18 End Index:19 Value:4
Start Index:19 End Index:20 Value:Q
Start Index:20 End Index:21 Value:L
Start Index:21 End Index:22 Value:e
--------------------------------------------------
"""
==========================================================
Regular Expressions in Python
#RegExpr18.py
#Searches for all digits
import re
mat=re.finditer("\d","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:2 End Index:3 Value:5
Start Index:7 End Index:8 Value:9
Start Index:18 End Index:19 Value:4
--------------------------------------------------"""
==========================================================
#RegExpr19.py
#Searches for all except except digits
import re
mat=re.finditer("\D","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:
Start Index:5 End Index:6 Value:@
Start Index:6 End Index:7 Value:K
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:10 End Index:11 Value:a
Start Index:11 End Index:12 Value:
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:b
Start Index:14 End Index:15 Value:U
Start Index:15 End Index:16 Value:*
Start Index:16 End Index:17 Value:L
Start Index:17 End Index:18 Value:#
Start Index:19 End Index:20 Value:Q
Start Index:20 End Index:21 Value:L
Start Index:21 End Index:22 Value:e
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
#RegExpr20.py
#Searches for all except except digits
import re
mat=re.finditer("\w","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:c
Start Index:1 End Index:2 Value:A
Start Index:2 End Index:3 Value:5
Start Index:6 End Index:7 Value:K
Start Index:7 End Index:8 Value:9
Start Index:8 End Index:9 Value:H
Start Index:9 End Index:10 Value:p
Start Index:10 End Index:11 Value:a
Start Index:12 End Index:13 Value:T
Start Index:13 End Index:14 Value:b
Start Index:14 End Index:15 Value:U
Start Index:16 End Index:17 Value:L
Start Index:18 End Index:19 Value:4
Start Index:19 End Index:20 Value:Q
Start Index:20 End Index:21 Value:L
Start Index:21 End Index:22 Value:e
--------------------------------------------------"""
==========================================================
Regular Expressions in Python
Note:
\ddd or \d{3} : Searches for 3 Digits.
\dd.\dd : Searches for 2 integer values and 2 decimal values.
\d{2,4} : Searches for nin 2 Digit number and max 4 digit number.
[A-Za-z]+ : Searches one alphabet or mere alphabets.
\w+
[0-9]+ OR \d+
Examples:
--------------
#RegExpr21.py
#Searches for all special symbols
import re
mat=re.finditer("\W","cA5& @K9Hpa TbU*L#4QLe")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:3 End Index:4 Value:&
Start Index:4 End Index:5 Value:
Start Index:5 End Index:6 Value:@
Start Index:11 End Index:12 Value:
Start Index:15 End Index:16 Value:*
Start Index:17 End Index:18 Value:#
--------------------------------------------------
"""
==========================================================
#RegExpr22.py
#Searches for only 'k'
import re
mat=re.finditer("k","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
Regular Expressions in Python
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:2 End Index:3 Value:k
Start Index:3 End Index:4 Value:k
Start Index:5 End Index:6 Value:k
Start Index:6 End Index:7 Value:k
Start Index:7 End Index:8 Value:k
Start Index:9 End Index:10 Value:k
--------------------------------------------------
"""
==========================================================
#RegExpr23.py
#Searches for either one 'k' or more k's
import re
mat=re.finditer("k+","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:2 End Index:4 Value:kk
Start Index:5 End Index:8 Value:kkk
Start Index:9 End Index:10 Value:k
--------------------------------------------------
"""
==========================================================
#RegExpr24.py
#Searches for either zero k or one 'k' or more k's
import re
mat=re.finditer("k*","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
Regular Expressions in Python
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:1 End Index:1 Value:
Start Index:2 End Index:4 Value:kk
Start Index:4 End Index:4 Value:
Start Index:5 End Index:8 Value:kkk
Start Index:8 End Index:8 Value:
Start Index:9 End Index:10 Value:k
Start Index:10 End Index:10 Value:
Start Index:11 End Index:11 Value:
--------------------------------------------------"""
==========================================================
#RegExpr25.py
#Searches for all
import re
mat=re.finditer(".","kvkkvkkkvkv")
print("-"*50)
for k in mat:
print("Start Index:{} End Index:{}
Value:{}".format(k.start(),k.end(), k.group()))
print("-"*50)
"""
--------------------------------------------------
Start Index:0 End Index:1 Value:k
Start Index:1 End Index:2 Value:v
Start Index:2 End Index:3 Value:k
Start Index:3 End Index:4 Value:k
Start Index:4 End Index:5 Value:v
Start Index:5 End Index:6 Value:k
Start Index:6 End Index:7 Value:k
Start Index:7 End Index:8 Value:k
Start Index:8 End Index:9 Value:v
Start Index:9 End Index:10 Value:k
Start Index:10 End Index:11 Value:v
--------------------------------------------------
"""
==========================================================
Multi Threading in Python
Index:
-----------
Purpose of Multi Threading
Types of Applications
a) Process Based Applications
b) Thread Based Applications
Programming Examples
---------------------------------------------------------------------------------------
Synchronization in Threading (OR) Dead Concept in Threading
Implementation of Synchronization in Threading (OR) Dead Concept in
Threading
Lock class
a) acquire()
b) release()
Programming Examples
=======================================================
Multi Threading in Python
Multi-Threading in Python
========================================
Examples: C,CPP...etc
--------------------------------------------------------------------------------------------
b) Thread Based Applications.
-------------------------------------------------------------------------------------------
Thread Based Applications are those whose execution environment
contains Single Thread (by deafult) and allows us create Multiple
Threads programatically.
Multi Threading in Python
Thread Based Applications provides Sequential Execution (by default)
also provides Concurrent Execution programatically.
=========================================
Introduction to Thread Based Applications
=========================================
The purpose of multi-threading is that "To provide Concurrent /
Simultaneous execution / Paralllel Execution".
Demo2.py
-------------------
import threading
def hello():
print("\nLine-3--> am from hello()--executed
by",threading.current_thread().name)
def hi():
print("\nI am from hi()--executed by
",threading.current_thread().name)
def greet():
print("\nI am from greet()--executed by
",threading.current_thread().name)
#main program
print("\nLine-10-->Default Name of thread in main
program=",threading.current_thread().name)
hello()
print("\nLine-12-->Default Name of thread in main
program=",threading.current_thread().name)
hi()
print("\nLine-15-->Default Name of thread in main
program=",threading.current_thread().name)
greet()
print("\nLine-17-->Default Name of thread in main
program=",threading.current_thread().name)
------------------------------------------------------------
Multi Threading in Python
non-threadex1.py
---------------------
import time,threading
def squares(lst):
for i in lst:
print("{} executed by
square({})={}".format(threading.current_thread().name,i,i**2))
time.sleep(1)
def cubes(lst):
for i in lst:
print("{} executed by
cubes({})={}".format(threading.current_thread().name,i,i**3))
time.sleep(1)
#main program
bt=time.time()
print("\nDefault Name of thread in main
program=",threading.current_thread().name)
lst=[2,5,12,6,13,19,4,16]
squares(lst)
cubes(lst)
print("\nProgram execution Completed:")
et=time.time()
print("Exec Time by Non-Threading application:{}".format(et-bt))
----------------------------------------------------------------
#threadex1.py
----------------
import time,threading
def squares(lst):
for i in lst:
print("{} executed by
square({})={}".format(threading.current_thread().name,i,i**2))
time.sleep(1)
def cubes(lst):
for i in lst:
print("{} executed by
cubes({})={}".format(threading.current_thread().name,i,i**3))
time.sleep(1)
#main program
bt=time.time()
print("\nDefault Name of thread in main
program=",threading.current_thread().name)
lst=[2,5,12,6,13,19,4,16]
#create sub threads
t1=threading.Thread(target=squares,args=(lst,) ) # Thread-1
t2=threading.Thread(target=cubes,args=(lst,) ) # Thread-2
t1.start()
t2.start()
t1.join()
t2.join()
print("\nProgram execution Completed:")
et=time.time()
print("Exec Time by Threading Application:{}".format(et-bt))
----------------------------------------------------------------
Multi Threading in Python
threading module
===================================================
1) current_thread()
--------------------------
It is used for obtaining name of th thread
Syntax: threading.current thread().name
2) active count():
------------------------
This function is used for counting number of active threads
Syntax:- threading.active_count()
========================================================
threading contains two classes--- 1. Thread 2.Lock
======================================================
1. Thread class
---------------------------
1) Thread(target,args): This constructor is used for creating sub thread
and initlizing with which Function to exdcute(target) by the sub thread
and whgich parameters(args) to pass(if required)
Syntax:-
varname=threading.Thread(target=Functionname,args=(Val1,val2....Val-n))
Here varname is called an object of sub thread
2) start():
---------------
=>This function is used for dispatching the sub thread for executing
targeted Function .
=>Syntax:- subthreadobj.start()
3) join():
-------------
=>This function is used for making the sub threads to join with main
thread after sub threads completion.
Syntax: subthreadobj1.join()
subthreadobj2.join()
--------------------------
Multi Threading in Python
subthreadobj-n.join()
4) setName():
-----------------------
=>This function is used for setting the user-friendly name to the sub
thread.
=>This Function is deprecated on the name of "name" attribute
=>Syntax:- subthread.setName("str")
(OR)
subthread.name=str data Here str data represent sub thread name
5) getName():
----------------------
This function is used forobtaining the thread name
This Function is deprecated on the name of "name" attribute
Syntax:- subthreadname=subthreadobj.getName()
(OR)
str data=subthread.name
# Here str data represent sub thread name
Example: tname=t1.getName()
(OR)
tname=t1.name
6) is_alive():
-----------------
This function returns true provded sub thread is under execution
otherwise it return False.
Syntax: subthreadname.is_alive()
Example: t1.is_alive()
8) run(self):
------------------
Multi Threading in Python
This function is used for defining the logic of Python program, which is
executed sub thread
Examples:
-----------------
#Program generating 1 to n number after each very second by using
threads
#approachEx1.py
import time
import threading # step-1
Multi Threading in Python
def generate(): #step-2
n=int(input("Enter how many numbers u want to generate:"))
if(n<=0):
print("{} is invalid".format(n))
else:
print("-"*50)
print("Numbers within :{}".format(n))
print("-"*50)
for i in range(1,n+1):
print("Val of i=",i)
time.sleep(1)
print("-"*50)
#main program
t1=threading.Thread(target=generate) # step-3
t1.start()
-----------------------------------------------------------------------
2. By using Object Oriented Approach without Inheritance
-----------------------------------------------------------------------
Step-1: import-threading module
Step-2 Define Programmer-defined class
Step-3: defined Instance Method in Programmer-defined class
Step-4: create an object of Programmer-defined class
Step-5: create sub thread
Step-6: Dispatch the sub threads.
Examples:
-------------------
#Program generating 1 to n number after each very second by using
threads
#approachEx2.py
import time
import threading #Step-1
class Numbers: #Step-2
def generate(self,n): #Step-3
self.n=n
if(self.n<=0):
print("{} is invalid".format(self.n))
else:
print("-"*50)
print("Numbers within :{}".format(self.n))
print("-"*50)
for i in range(1,self.n+1):
print("Val of i=",i)
time.sleep(1)
print("-"*50)
#main program
n=Numbers() #Step-4
t1=threading.Thread(target=n.generate,args=(int(input("Enter a
number:")),)) #Step-5
t1.start() #Step-6
========================================================
Multi Threading in Python
3. By using Object Oriented Approach with Inheritance
--------------------------------------------------------------------------------------------
Step-1: import therading module
Step-2: Choose and defined Programmer-Defined Class
Step-3: The Programmer-Defined class must inherit from Thread class
of threading module
Step-4: The Programmer-Defined class must override run(self) of
Thread class
Step-5 : Create an object of The Programmer-Defined class, which is
the sub class of Thread class
Step-6: Dispatch the sub thread
Examples:
----------------
#Program generating 1 to n number after each very second by using
threads
#approachEx3.py
import threading ,time # Step-1
# Step-2 Step-3
class Numbers(threading.Thread):
def setvalue(self,n):
self.n=n
def run(self): # Step-4--->Overriding the run() of Thread class
of threading module
self.setvalue(int(input("Enter Value of n:")))
if(self.n<=0):
print("{} is invalid".format(self.n))
else:
print("-"*50)
print("Numbers within :{}".format(self.n))
print("-"*50)
for i in range(1,self.n+1):
print("Val of i=",i)
time.sleep(1)
print("-"*50)
#main program
n=Numbers() #Step-5----Sub thread creation only
print("Execution status of sub thread before =",n.is_alive())
n.start() # Step-6----dispatching sub thread
print("Execution status of sub thread after start=",n.is_alive())
=======================================================================
#write a python program which will print even numbers seprated by one
thread and odd no. seprated by one thread and voiwels in given line.
#EvenOddVowels.py
import threading,time
def evennumbers(n): # Functional Approach
if(n<=0):
print("{} is invalid".format(n))
else:
for i in range(2,n+1,2):
Multi Threading in Python
print("{}-->Generates Even
Number:{}".format(threading.current_thread().name,i))
time.sleep(0.75)
class Odd:
def oddnumbers(self,n): # Object Oriented Approach without using
Inheritance
if(n<=0):
print("{} is invalid".format(n))
else:
for i in range(1,n+1,2):
print("{}-->Generates Odd
Number:{}".format(threading.current_thread().name,i))
time.sleep(0.75)
class Vowels(threading.Thread):
def settext(self,line):
self.line=line
def run(self): # Object Oriented Approach without using
Inheritance
if (self.line.isspace() or len(self.line)==0):
print("Given String is empty:")
else:
for i in [ j for j in self.line if j.lower() in
['a','e','i','o','u'] ]:
print("{}-->Generates
Vowel:{}".format(threading.current_thread().name,i))
time.sleep(0.75)
#main program
v=Vowels() # Object Oriented Approach with Inheritance
line=input("Enter a line of text:")
v.settext(line)
n=int(input("Enter a Number:"))
et=threading.Thread(target=evennumbers,args=(n,)) # Functional
Approach
ot=threading.Thread(target=Odd().oddnumbers,args=(n,)) # Object
Oriented Approach without using Inheritance
et.start()
ot.start()
v.start()
=======================================================================
#Write a Python Program which will accept a line of text and display each
and every character after one second using thread
#CharGenApproachEx1.py----Functional Approach
------------------------------------------
import threading,time
def chargeneration(line):
if (line.isspace() or len(line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",line)
print("-"*50)
for ch in line.split():
print("\t\t{}".format(ch))
time.sleep(0.5)
print("-"*50)
#main program
Multi Threading in Python
t=threading.Thread(target=chargeneration,args=(input("Enter a line:"),))
t.start()
=======================================================================
#Write a Python Program which will accept a line of text and display
each and every character after one second using thread
----------------------------------------------------------------------
#CharGenApproachEx2.py----Object Oriented Approach without Inheritance
-------------------------------------------------
import threading,time
class CharGen:
def chargeneration(self,line):
self.line=line
if (self.line.isspace() or len(self.line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",self.line)
print("-"*50)
for ch in self.line.split():
print("\t\t{}".format(ch))
time.sleep(0.5)
print("-"*50)
#main program
t=threading.Thread(target=CharGen().chargeneration,args=(input("Enter a
line:"),))
t.start()
=======================================================================
#Write a Python Program which will accept a line of text and display
each and every character after one second using thread
---------------------------------------------------------------
#CharGenApproachEx3.py----Object Oriented Approach with Inheritance
-------------------------------------------------------------------
import threading,time
class CharGen(threading.Thread):
def run(self):
self.line=input("Enter a line of Text:")
if (self.line.isspace() or len(self.line)==0):
print("Given String is empty:")
else:
print("-"*50)
print("Given Line:",self.line)
print("-"*50)
for ch in self.line:
print("\t\t{}".format(ch))
time.sleep(0.5)
print("-"*50)
#main program
cg=CharGen() # here cg is an object of CharGen Class and it is sub
thread
cg.start() # start() automatically calls run(), which as already
overridden in CharGen Class.
=======================================================================
Multi Threading in Python
--------------------------------------------------------------------------------------
Multi Threading in Python
Steps for implementing Synchronization Concept:
(OR)
Steps for avoiding dead lock
--------------------------------------------------------------------------------------
1) obtain / create an object of Lock class, which is present in threading
module.
Syntax:- lockobj=threading.Lock()
Once current object acquire the lock, other thread objects are made
wait until curent thread object releases the lock.
Syntax: lockobj.release()
Once current object releases the lock, other objects are permitted
into shrable resource. This process of aquiring and releasing the lock
will be continued until all the objects completed their execution.
========================================================
#nonlock-FunEx.py
-------------------
import threading,time
def table(n):
if(n<=0):
print("{} in valid input:".format(n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,n))
print("-"*50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
time.sleep(0.5)
print("-"*50)
#main program
t1=threading.Thread(target=table,args=(4,))
t2=threading.Thread(target=table,args=(14,))
t3=threading.Thread(target=table,args=(-9,))
t4=threading.Thread(target=table,args=(19,))
Multi Threading in Python
t1.start()
t2.start()
t3.start()
t4.start()
========================================================
#lock-FunEx.py
-------------------
import threading,time
def table(n):
L.acquire() # Get the lock
if(n<=0):
print("{} in valid input:".format(n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,n))
print("-"*50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
time.sleep(0.5)
print("-"*50)
L.release() # release the lock
#main program
#Create an object Lock class
L=threading.Lock() # Here L is an object of Lock class and it is
global variable
t1=threading.Thread(target=table,args=(4,))
t2=threading.Thread(target=table,args=(14,))
t3=threading.Thread(target=table,args=(-9,))
t4=threading.Thread(target=table,args=(19,))
t1.start()
t2.start()
t3.start()
t4.start()
=======================================================
#lock-OopExOnlyEx1.py (Without Inheritance)
----------------------------------------------
import threading,time
class Multable:
def table(self,n):
K.acquire() # Get the lock
self.n=n
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
K.release() # release the lock
Multi Threading in Python
#main program
#Create an object Lock class
K=threading.Lock() # Here K is an object of Lock class and it is
global variable
t1=threading.Thread(target=Multable().table,args=(4,))
t2=threading.Thread(target=Multable().table,args=(14,))
t3=threading.Thread(target=Multable().table,args=(-9,))
t4=threading.Thread(target=Multable().table,args=(19,))
t1.start()
t2.start()
t3.start()
t4.start()
====================================================================
#lock-OopExOnlyEx2.py (Without Inheritance)
----------------------------------------------
import threading,time
class Multable:
@classmethod
def getlock(cls):
cls.K=threading.Lock() # Here K is an object of Lock
class and it is Class Level Variable
def table(self,n):
self.K.acquire() # Get the lock
self.n=n
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
Multable.K.release() # release the lock
#main program
Multable.getlock()
t1=threading.Thread(target=Multable().table,args=(14,))
t2=threading.Thread(target=Multable().table,args=(8,))
t3=threading.Thread(target=Multable().table,args=(-16,))
t4=threading.Thread(target=Multable().table,args=(23,))
t1.start()
t2.start()
t3.start()
t4.start()
-----------------------------------------------------------------------
#nonlock-OopEx1.py (Without Inheritance)
--------------------------------------------
import threading,time
class Multable:
def table(self,n):
self.n=n
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
Multi Threading in Python
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
#main program
t1=threading.Thread(target=Multable().table,args=(4,))
t2=threading.Thread(target=Multable().table,args=(14,))
t3=threading.Thread(target=Multable().table,args=(-9,))
t4=threading.Thread(target=Multable().table,args=(19,))
t1.start()
t2.start()
t3.start()
t4.start()
=======================================================================
#lock-OopExInhEx1.py (With Inheritance)
-------------------------------------------
import threading,time
class MulTable(threading.Thread):
K=threading.Lock() # Here K is an object of Lock class and it
is Class Level Variable
def setval(self,n):
self.n=n
def run(self):
MulTable.K.acquire()
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thre Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
MulTable.K.release()
#main program
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
t1.setval(4)
t2.setval(14)
t3.setval(-9)
t4.setval(19)
t1.start()
t2.start()
t3.start()
t4.start()
=======================================================================
Multi Threading in Python
#nonlock-OopEx2.py (With Inheritance)
---------------------------------------
import threading,time
class MulTable(threading.Thread):
def setval(self,n):
self.n=n
def run(self):
if(self.n<=0):
print("{} in valid input:".format(self.n))
else:
print("-"*50)
print("Thread Name:{} Mul Table for
:{}".format(threading.current_thread().name,self.n))
print("-"*50)
for i in range(1,11):
print("\t{} x
{}={}".format(self.n,i,self.n*i))
time.sleep(0.5)
print("-"*50)
#main program
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
t1.setval(4)
t2.setval(14)
t3.setval(-9)
t4.setval(19)
t1.start()
t2.start()
t3.start()
t4.start()
======================================================================
Numpy Module in Python
Index
• Purpose of Numpy
• How to use Numpy in Python
• Differences Traditional Python list and ndarray.
• What is ndarray
• Types of arraya: 1) 1-D 2) 2-D 3) N-D
• Number of Approaches to create an object of ndarray.
• Arithmetic Operations on ndarray in numpy.
• Statistical Operations on ndarray in numpy.
• Basic indexing & Slicing Operations on ndarray in numpy.
• Advanced Indexing Advanced Slicing Operations on ndarray in numpy.
• Copy and View on ndarray object in numpy.
• Selecting Elements or Filtering Elements from ndarray in numpy.
• Sorting and Searching Oprtations on ndarray.
Numpy Module in Python
Numpy
Introduction of Numpy:
History of Numpy:
The Numeric Library was not able to solve complex maths calculations.
Need of Numpy:
With the revolution of data science, date analysis librarys like Numpy,
SciPy, Scikit, Pandas, etc. have seen a lot of grouth. With a much easier
syntax than other programming languages, Python is the first choice
language for the data scientist.
1) With Numpy Programming, we can deal with array such 1-D, 2-D & N-D.
2) Numpy maintains minimum memory for large sets of data.
3) Numpy provides Fast in performing operation because internally it’s data
is available at same address.
4) Numpy performs array-oriented computing.
5) It efficiently implements the multidimentional arrays.
6) It perform scientific computations.
7) It is capable of performing reshaping the data stored in multidimentional
array.
8) Numpy provides many in-built functions for various complex
mathematical operations such as statistical, financial, trigonometric
operations etc.
Numpy Module in Python
The objects of ndarray and list are mutable (changes can takes place).
In large smpling of data, list based applications takes more memory space
whereas ndarray object takes less memory space.
List based application are not efficient because list object values takes
more time to extract or retrieve (they are available a different address)
where as Numpy based applications are efficient because of ndarray
object values takes less time to extract or retrieve (they are avalibale ar
same Address).
1) array(): This function is used for converting traditional Python object into
ndarray object.
Dtype represents any numpy data type such as int8, int16, int32, float16,
float 32, float64, U64, U5….etc.
Examples:
--------------
>>> import numpy as np
>>> l1=[10,20,30,40,50,60]
>>> print(l1,type(l1))-----------------[10, 20, 30, 40, 50, 60] <class
'list'>
>>> a=np.array(l1)
>>> print(a,type(a))----------------[10 20 30 40 50 60] <class
'numpy.ndarray'>
>>> t=(10,20,30,40,50,60,70)
>>> print(t,type(t))--------------(10, 20, 30, 40, 50, 60, 70) <class
'tuple'>
>>> a=np.array(t)
>>> print(a,type(a))--------------[10 20 30 40 50 60 70] <class
'numpy.ndarray'>
>>> d1={10:1.2,20:4.5,30:6.7}
>>> a=np.array(d1)
>>> a----array({10: 1.2, 20: 4.5, 30: 6.7}, dtype=object)
-----------------------------------------------------------------------
Numpy Module in Python
>>> t=(10,20,30,40,50,60)
>>> a=np.array(t)
>>> a--------------array([10, 20, 30, 40, 50, 60])
>>> a.ndim------------1
>>> a.dtype----------dtype('int32')
>>> a.shape-------------(6,)
>>> b=a.reshape(3,2)
>>> c=a.reshape(2,3)
>>> b--------------
array([[10, 20],
[30, 40],
[50, 60]])
>>> c
array([[10, 20, 30],
[40, 50, 60]])
>>> print(b,type(b))
[[10 20]
[30 40]
[50 60]] <class 'numpy.ndarray'>
>>> print(c,type(c))
[[10 20 30]
[40 50 60]] <class 'numpy.ndarray'>
>>> b.ndim-------------2
>>> c.ndim------------2
>>> b.shape---------------(3, 2)
>>> c.shape-------------(2, 3)
>>> d=a.reshape(3,3)-------ValueError: cannot reshape array of size 6
into shape (3,3)
-----------------------------------------------------------------------
>>> t1=((10,20),(30,40))
>>> print(t1,type(t1))--------------((10, 20), (30, 40)) <class
'tuple'>
>>> a=np.array(t1)
>>> a
array([[10, 20],
[30, 40]])
>>> a.ndim----------2
>>> a.shape----------(2, 2)
-----------------------------------------------------------------------
>>> t1=( ((10,20,15),(30,40,25)),( (50,60,18),(70,80,35) ))
>>> print(t1,type(t1))
(((10, 20, 15), (30, 40, 25)), ((50, 60, 18), (70, 80, 35))) <class
'tuple'>
>>> a=np.array(t1)
>>> a
array([[[10, 20, 15],
[30, 40, 25]],
[[50 60 18]
[70 80 35]]]
Numpy Module in Python
>>> a.ndim
3
>>> a.shape
(2, 2, 3)
>>> b=a.reshape(4,3)
>>> b
array([[10, 20, 15],
[30, 40, 25],
[50, 60, 18],
[70, 80, 35]])
>>> c=a.reshape(3,4)
>>> c
array([[10, 20, 15, 30],
[40, 25, 50, 60],
[18, 70, 80, 35]])
>>> d=a.reshape(3,2,2)
>>> d
array([[[10, 20],
[15, 30]],
[[40, 25],
[50, 60]],
[[18, 70],
[80, 35]]])
>>> d[0]
array([[10, 20],
[15, 30]])
>>> d[1]
array([[40, 25],
[50, 60]])
>>> d[2]
array([[18, 70],
[80, 35]])
=============================================================
2) arange(): arrange() always create an object of ndarray in 1-D array only
but not possible to create directly 2-D and multi-dimentional arrays.
Examples:
-------------
>>> import numpy as np
>>> a=np.arange(10)
>>> a-----------array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.ndim--------1
>>> a=np.arange(50,62)
>>> print(a,type(a))---[50 51 52 53 54 55 56 57 58 59 60 61] <class
'numpy.ndarray'>
>>> a.ndim------1
>>> a=np.arange(10,23,2)
>>> a-----array([10, 12, 14, 16, 18, 20, 22])
>>> a=np.arange(10,22,2)
>>> a--------array([10, 12, 14, 16, 18, 20])
>>> b=a.reshape(2,3)
>>> c=a.reshape(3,2)
>>> b-----
array([[10, 12, 14],
[16, 18, 20]])
>>> c
array([[10, 12],
[14, 16],
[18, 20]])
>>> b.ndim------ 2
>>> c.ndim------- 2
>>> b.shape-----(2, 3)
>>> c.shape-----(3, 2)
>>> l1=[ [[10,20],[30,40]], [[15,25],[35,45]] ]
>>> l1----------[[[10, 20], [30, 40]], [[15, 25], [35, 45]]]
>>> a=np.arange(l1)----------TypeError: unsupported operand type(s) for
-: 'list' and 'int'
=============================================================
3) zeros(): This function is used for buildind zero matrix either with 1-D or
2-D or N-D.
Examples:
-------------
>>> import numpy as np
>>> a=np.zeros(12)
>>> a-----------array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> a=np.zeros(12,dtype=int)
>>> a------------array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> a.reshape(3,4)
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
>>> a.reshape(4,3)
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a.reshape(6,2)
array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]])
>>> a.reshape(2,6)
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]]])
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]]])
Numpy Module in Python
>>> a.reshape(2,2,3)
array([[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]]])
-----------------------------------------------------------------------
>>> import numpy as np
>>> a=np.zeros((3,3),dtype=int)
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((2,3))
>>> a
array([[0., 0., 0.],
[0., 0., 0.]])
>>> a=np.zeros((2,3),int)
>>> a
array([[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((3,2,3),dtype=int)
>>> a
array([[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]]])
>>> print(a,type(a))
[[[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]]] <class 'numpy.ndarray'>
=============================================================
4) ones(): This function is used for building ONEs matrix either with 1-D or
2-D or N-D.
Examples:
-------------
>>> import numpy as np
>>> a=np.ones(10)
>>> print(a,type(a))----------[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] <class
'numpy.ndarray'>
>>> a=np.ones(10,dtype=int)
>>> print(a,type(a))-------------[1 1 1 1 1 1 1 1 1 1] <class
'numpy.ndarray'>
>>> a.shape-----------(10,)
>>> a.shape=(5,2)
>>> a
array([[1, 1],
[1, 1],
[1, 1],
[1, 1],
[1, 1]])
>>> a.ndim-------------- 2
>>> a.shape------------ (5, 2)
>>> a.shape=(2,5)
>>> a
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
>>> a.shape----------------------(2, 5)
>>>
>>> a=np.ones((3,4),dtype=int)
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> a=np.ones((4,3),dtype=int)
>>> print(a,type(a))
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]] <class 'numpy.ndarray'>
>>> a.shape----------(4, 3)
>>> a.shape=(3,2,2)
>>> a
array([[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]])
Numpy Module in Python
>>> a=np.ones((4,3,3),dtype=int)
>>> a
array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]])
>>> a[0][0][0]-----------1
>>> a[0,0,0]-----------1
>>> a[0][0,0]------------1
=============================================================
5) full(): This is function is used building a matrix by specifying fill value
either 1-D or 2-D or N-D.
Examples:
--------------
>>> a=np.full(3,1)
>>> a---------array([1, 1, 1])
>>>print(type(a))--------<class,numpy.ndarray>
>>> a=np.full(3,9)
>>> a------------array([9, 9, 9])
>>> a=np.full(6,8)
>>> a-------------array([8, 8, 8, 8, 8, 8])
>>> a.shape=(3,2)
>>> a
array([[8, 8],
[8, 8],
[8, 8]])
>>> a=np.full(6,9)
>>> a----------array([9, 9, 9, 9, 9, 9])
>>> a.reshape(2,3)
array([[9, 9, 9],
[9, 9, 9]])
Numpy Module in Python
>>> a=np.full((3,3),9)
>>> a
array([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])
>>> a=np.full((2,3),6)
>>> a
array([[6, 6, 6],
[6, 6, 6]])
>>> a.reshape(3,2)
array([[6, 6],
[6, 6],
[6, 6]])
>>> a=np.full((3,3,3),7)
>>> a
array([[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],
[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],
[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]]])
=============================================================
6) eye(): This function is used for building identity matrix or unit matrix.
Examples:
--------------
>>> import numpy as np
>>> #varname=numpy.eye(N,M=None,K=0,dtype
>>> a=np.eye(3)
>>> print(a,type(a))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] <class 'numpy.ndarray'>
>>> a=np.eye(3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(4,3,dtype=int)
>>> print(a,type(a))
[[1 0 0]
[0 1 0]
[0 0 1]
[0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,dtype=int)
>>> print(a,type(a))
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]] <class 'numpy.ndarray'>
>>> a=np.eye(3,4,k=-1,dtype=int)
>>> print(a,type(a))
[[0 0 0 0]
[1 0 0 0]
[0 1 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-1,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-2,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]
[0 0 1 0 0 0]] <class 'numpy.ndarray'>
Numpy Module in Python
>>> a=np.eye(5,6,k=-3,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]
[0 1 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=-4,dtype=int)
>>> print(a,type(a))
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[1 0 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=1,dtype=int)
>>> print(a,type(a))
[[0 1 0 0 0 0]
[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=2,dtype=int)
>>> print(a,type(a))
[[0 0 1 0 0 0]
[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]
[0 0 0 0 0 0]] <class 'numpy.ndarray'>
>>> a=np.eye(5,6,k=3,dtype=int)
>>> print(a,type(a))
[[0 0 0 1 0 0]
[0 0 0 0 1 0]
[0 0 0 0 0 1]
[0 0 0 0 0 0]
[0 0 0 0 0 0]] <class 'numpy.ndarray'>
=============================================================
7) identity(): This function always build Identity or unit matrix.
Here N represents either we can take Rows or Columns and PVM takes as
NXN Matrix (Square Matrix – Unit or Identity)
Numpy Module in Python
Examples:
--------------
>>> import numpy as np
>>> a=np.identity(3,dtype=int)
>>> print(a,type(a))-------------
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.identity(5,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]] <class 'numpy.ndarray'>
=============================================================
All the arithmetic functions can also be perform w.r.t arithmetic Operators.
Examples:
-------------
>>> l1=[ [10,20],[30,40] ]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.add(a,b)
>>> c
array([[11, 22],
[33, 44]])
-----------------------------------------------------------------------
>>> x=np.array([[1,2,3],[4,5,6]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> y=np.array([4,4,4])
>>> y
array([4, 4, 4])
>>> z=x+y
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> z=np.add(x,y)
>>> z
array([[ 5, 6, 7],
[ 8, 9, 10]])
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> k=np.array([[2,3],[4,5]])
>>> k
array([[2, 3],
[4, 5]])
>>> kvr=np.add(x,k)----ValueError: operands could not be broadcast
together with shapes (2,3)
(2,2)
-----------------------------------------------------------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=a+b # we used operator + instead of add()
>>> c
array([[11, 22],
[33, 44]])
Numpy Module in Python
=============================================================
b) subtract(): This function is used to subtracting elements of ndarrayobj1,
ndarrayobj2 and result can be displayed.
Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.subtract(a,b)
>>> c
array([[ 9, 18],
[27, 36]])
-----------------------------------
>>> d=a-b # we used operator - instead of subtract()
>>> d
array([[ 9, 18],
[27, 36]])
============================================================
c) multiply(): This function is used for performing element-wise
multiplicaton of ndarrayobj1, ndarrayobj2 and result can be displayed.
Examples:
--------------
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
Numpy Module in Python
>>> c=np.multiply(a,b)
>>> c
array([[ 5, 12],
[12, 12]])
-----------------------------------------------
>>> e=a*b # we used operator * instead of multiply()
>>> e
array([[ 5, 12],
[12, 12]])
=============================================================
d) dot() or matmul(): This function is used for performing actual matrix
multiplication of ndarrayobj1, ndarrayobj2 and result can be displayed.
Examples:
-------------
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> d=np.dot(a,b)
>>> d
array([[13, 12],
[31, 30]])
(OR)
>>> d=np.matmul(a,b)
>>> d
array([[13, 12],
[31, 30]])
=============================================================
Numpy Module in Python
Examples:
--------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.divide(a,b)
>>> c
array([[10., 10.],
[10., 10.]])
---------------------------------------------------------------
>>> d=a/b # we used operator / instead of divide()
>>> d
array([[10., 10.],
[10., 10.]])
=============================================================
f) floor_divide(): This function is used for performing element-wise floor
division of ndarrayobj1, ndarrayobj2 and result can be displayed.
Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.floor_divide(a,b)
>>> c
array([[10, 10],
[10, 10]])
---------------------------------------------------------------
Numpy Module in Python
>>> d=a//b # we used operator // instead of floor_divide()
>>> d
array([[10, 10],
[10, 10]])
============================================================
g) mod(): This function is used for performing element-wise modulo
division of ndarrayobj1, ndarrayobj2 and result can be displayed.
Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.mod(a,b)
>>> c
array([[0., 0.],
[0., 0.]])
-----------------------------------------------------------------------
=>We can also do with operator %
>>> e=a%b
>>> e
array([[0, 0],
[0, 0]], dtype=int32)
============================================================
Numpy Module in Python
Examples:
-------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>>c=np.power(a,b)
>>>print(c)
array([[ 10, 400],
[ 27000, 2560000]],
--------------------------------------------
>>> f=a**b # Instead of using power() we can use ** operator
>>> f
array([[ 10, 400],
[ 27000, 2560000]], dtype=int32)
=============================================================
These Operations we can perform on the entire matrix and we can also
perform on column-wise(axis=0) ans row-wise(axis=1).
Numpy Module in Python
Examples:
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> max=np.amax(A)
>>> cmax=np.amax(A,axis=0)
>>> rmax=np.amax(A,axis=1)
>>> print("Max element=",max)-----------Max eleemnt= 4
>>> print("Column Max eleemnts=",cmax)---Column Max eleemnts= [4 4 3]
>>> print("Row Max eleemnts=",rmax)---Row Max eleemnts= [3 4 4]
============================================================
b) amin(): This function obtains minimum element of the entire matrix.
c) mean(): This function used for calculate mean of the total matrix elements.
The formula for mean = (sum of all elements of matrix)/ total number of
elements.
Median as nothing but sorting the given data in ascending order and select
middle element.
If the number sorted elements are odd then center or middle element
become median.
If the number sorted elements are even then center or middle element of
two elements, add them and divide by 2 and that result becomes median.
Numpy Module in Python
Examples:
--------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)----Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556
0.88888889
0.66666667]
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556
0.66666667]
============================================================
f) std(): standard deviation = sqrt(var)
>>> sd=np.std(A)
>>> csd=np.std(A,axis=0)
>>> rsd=np.std(A,axis=1)
>>> print("std=",sd)---std= 1.0657403385139377
>>> print(" column std=",csd)--- column std= [1.24721913 0.94280904
0.81649658]
>>> print("Row std=",rsd)--Row std= [0.81649658 1.24721913 0.81649658]
=================================X=====================================
NOTE:
----------
>>> import statistics
>>> l=[10,20,10,30,40,10,50,10]
>>> statistics.mode(l)
10
>>> l=[10,20,10,30,40,10,50,10,20,20,20]
>>> statistics.mode(l)
10
>>> l=[20,10,10,30,40,10,50,10,20,20,20]
>>> statistics.mode(l)
20
>>> statistics.multimode(l)
[20, 10]
>>> l=[20,10,10,30,40,10,50,10,20,20,20,10]
>>> statistics.multimode(l)
[10]
>>>
=============================================================
If we want to access single element of 1-D, 2-D and N-D arrays we must use
the concept of Basic Indexing.
Examples:
>>> a=np.array([10,20,30,40,50,60])
>>> a
array([10, 20, 30, 40, 50, 60])
>>> a[0]
10
>>> a[3]
40
============================================================
Accessing single Element of 2-D:
Examples:
>>>import numpy as np
>>> a=np.array([10,20,30,40,50,60])
>>> b=a.reshape(2,3)
>>> b
array([[10, 20, 30],
[40, 50, 60]])
>>> b[0,0]
10
>>> b[0,1]
20
>>> b[1,2]
60
=============================================================
Accessing single Element of 3-D:
Examples:
>>> a=np.array([10,20,30,40,50,60,70,80])
>>> b=a.reshape(2,2,2)
>>> b
array([[[10, 20],
[30, 40]],
[[50, 60],
[70, 80]]])
>>> b[0,0,0]-----------10
>>> b[-1,0,0]---------50
>>> b[-2,1,1]---------40
============================================================
Numpy Module in Python
Numpy (Indexing and Slicing Operations of 1-D, 2-D and 3-D array)
Examples:
-------------
>>> a=np.array([10,20,30,40,50,60,70])
>>> a------------array([10, 20, 30, 40, 50, 60, 70])
>>> a[::-1]-----------array([70, 60, 50, 40, 30, 20, 10])
>>> a[::]-----------array([10, 20, 30, 40, 50, 60, 70])
============================================================
2-D array slicing:
Syntax: ndarrayobj[ i , j ]
Here ‘ i ’ represents row index.
Here ‘ j ’ represents column index.
Syntax: 2darrayobj[row index, column index]
Syntax: 2darrayobj[begin:end:step , begin:end:step]
Examples:
--------------
>>> a=np.array([[10,20,30],[40,50,60]])
>>> a
array([[10, 20, 30],
[40, 50, 60]])
>>> a[0,0]
10
>>> a[0:,0:1]
array([[10],
[40]])
>>> a[0:,1:2]
array([[20],
[50]])
>>> a[1:,:]
array([[40, 50, 60]])
=============================================================
Numpy Module in Python
Syntax: 3dndarrayobj [ i , j , k]
Here ‘ i ’ represents which 2-D matrix (Matrix number---0 1 2 3 …)
Here ‘ j ’ represents which rows in that 2-D matrix.
Here ‘ k ’ represents which column in that 2-D matrix.
OR
3dndarrayobj [ matrix index, row index, column index]
OR
3dndarrayobj [ begin:end:step , begin:end:step , begin:end:step ]
Examples:
-------------
>>> lst=[ [ [1,2,3],[4,5,6],[7,8,9] ],[
[13,14,15],[16,17,18],[19,20,21] ] ]
>>> print(lst)
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[13, 14, 15], [16, 17, 18], [19,
20, 21]]]
>>> arr2=np.array(lst)
>>> print(arr2)
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]
[[13 14 15]
[16 17 18]
[19 20 21]]]
>>> arr2.ndim
3
>>> arr2.shape
(2, 3, 3)
>>> arr2[:,:,0:1]
array([[[ 1],
[ 4],
[ 7]],
[[13],
[16],
[19]]])
>>> arr2[:,:,:1]
array([[[ 1],
[ 4],
[ 7]],
[[13],
[16],
[19]]])
Numpy Module in Python
>>> arr2[: , 0:2, 1:3]
array([[[ 2, 3],
[ 5, 6]],
[[14, 15],
[17, 18]]])
>>> arr2[: , :2, 1:]
array([[[ 2, 3],
[ 5, 6]],
[[14, 15],
[17, 18]]])
=============================================================
Here ‘x’ can be either ndarray or list which represents required indexes of
arbitrary elements.
Examples:
--------------
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
#access 10 30 and 80 elements
# here indexes of 10 30 and 80 are 0 2 7
>>>lst=[0,2,7] here [0,2,7] are indexes of 10 30 and 80
>>> indexes=np.array(lst) # here lst converted into ndarray object
>>> print(indexes)---------[0 2 7]
Numpy Module in Python
>>> print(a[indexes])--------------[10 30 80]
(OR)
>>> ind=[0,2,7] # prepare the list of indexes of arbitray
elements(10,30,80) of ndarray and pass to ndarray
>>> print(a[ind]) -----------[10 30 80]
Examples:
---------------------
Q1-->Access 20 30 80 10 10 30
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
>>> ind=[1,2,7,0,0,2] # [1,2,7,0,0,2] are the indexes of 20 30 80 10 10
30
>>> print(a[ind])----------------[20 30 80 10 10 30]
===========================================================
Accessing Multiple Arbitary Elements (2D):
Examples:
-------------
>>>import numpy as np
>>>mat=np.array([ [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16] ] )
>>> print(mat)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
Examples:
--------------
>>>import numpy as np
>>>l1=[ [ [1,2,3,4],[5,6,7,8],[9,10,11,12] ],[
[13,14,15,16],[17,18,19,20],[21,22,23,24] ] ]
>>>mat3d=np.array(l1)
>>>print(mat3d)
>>> print(mat3d)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
>>> mat3d.ndim
3
>>> mat3d.shape
(2, 3, 4)
----------------------------------------
Q1) Access the elements 1 14 24
Ans:- mat3d[ [0,1,1], [0,0,2], [0,1,3] ]
a=np.array([10,20,30,40,50,60,70,80,15,25,35,45,55,65,75,85])
print(a)
a.shape=(2,2,2,2)
print(a)
[[[[10 20]
[30 40]]
[[50 60]
[70 80]]]
[[[15 25]
[35 45]]
[[55 65]
[75 85]]]]
Prepare Boolean Array (It contains True or False). True represents condition
satisfied and False reperesents Condition not satisfied.
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-1:
In this approach, we directly pass Boolean array values to the ndarray for
getting required elements based on condition.
Examples:
-------------
-----------------------------
Q1) Select the Possitive Elements from ndarray
>>> import numpy as np
>>> l=[10,21,-34,23,-45,30,-40]
>>> print(l)--------------[10, 21, -34, 23, -45, 30, -40]
>>> a=np.array(l)
>>> a------------array([ 10, 21, -34, 23, -45, 30, -40])
>>> b=a>0 # Boolean Array
>>> print(b)----[ True True False True False True False]
>>> a[b]-------array([10, 21, 23, 30])
===================OR=========================
>>> a[ a>0 ]-----------array([10, 21, 23, 30])
-------------------------------------------------------------------
Q2) Select the Negative Elements from ndarray
>>> l=[10,21,-34,23,-45,30,-40]
>>> a=np.array(l)
>>> a---------- array([ 10, 21, -34, 23, -45, 30, -40])
>>> b=a<0 # Boolean Array
>>> b---- array([False, False, True, False, True, False,
True])
>>> a[b]------- array([-34, -45, -40])
=================OR=============
>>> a[a<0]-------------- array([-34, -45, -40])
-----------------------------------------------------------------------
Q3) Select the Even and Odd Elements from ndarray
>>> a=np.array([11,20,33,31,41,47,46,12,13])
>>> a------------------array([11, 20, 33, 31, 41, 47, 46, 12, 13])
>>> a[a%2==0]-----------------array([20, 46, 12])
>>> a[a%2!=0]-----------------array([11, 33, 31, 41, 47, 13])
-----------------------------------------------------------------------
Numpy Module in Python
>>> a=np.array([10,20,30,40,50,60,70,80,90])
>>> b=a.reshape(3,3)
>>> b
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
#Get Multiples of 3
>>> m3=(b%3==0)
>>> m3 #----------------------Boolean array
array([[False, False, True],
[False, False, True],
[False, False, True]])
>>> b[m3]--------------------------array([30, 60, 90])
======================OR===========================
>>> b[b%3==0]-------------------array([30, 60, 90])
============================================================
Examples:
-------------
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr)) # [0 1 2 3]
----------------------------------------------------
import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr)) # ['apple' 'banana' 'cherry']
-----------------------------------------------------
import numpy as np
arr = np.array([True, False, True])
print(np.sort(arr)) # [False True True]
-------------------------------------------------------
Sorting a 2-D Array
--------------------------------------------------------
If you use the sort() method on a 2-D array, both columns and Rows of
nd array will be sorted.
-------------------
Numpy Module in Python
Examples:
-------------------
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
#output
[[2 3 4]
[0 1 5]]
-----------------------------------------------------------------------
a=np.array([110, 20, -30, 40, 50, 160, 7, 8, 90])
print(a)
np.sort(a,axis=0) # ColumnWise
array([[ 7, 8, -30],
[ 40, 20, 90],
[110, 50, 160]])
-----------------------------------------------------------
print(a)
array([[110, 20, -30],
[ 40, 50, 160],
[ 7, 8, 90]])
The main difference between a copy and a view of an array is that the copy
is a new array, and the view is just a view of the original array.
The copy owns the data and any changes made to the copy will not affect
original array, and any changes made to the original array will not affect the
copy. Modification are independent (Like Shallow Copy).
Numpy Module in Python
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.
Copy:
Examples:
--------------
# Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [1 2 3 4 5]
-----------------------------------------------------------------------
NOTE: The copy SHOULD NOT be affected by the changes made to the
original array.
-----------------------------------------------------------------------
VIEW:
Example
-------------
#Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [42 2 3 4 5]
-----------------------------------------------------------------------
NOTE : The view SHOULD be affected by the changes made to the original
array.
-----------------------------------------------------------------------
Numpy Module in Python
# Make Changes in the VIEW:
------------------
Example
------------------
# Make a view, change the view, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr) # [31 2 3 4 5]
print(x) # [31 2 3 4 5]
-----------------------------------------------------------------------
=>In the case append() , view() does not reflect the changes
=============================================================
Pandas Module in Python
Series
Creating a Series:
A Series object can be created by using the following Syntax:
Explanation:
Here varname is an object of <class, pandas.core.series.Series>
‘object’ can either int, float, complex, bool, str, bytes, byesarray, range, list,
ndarray, dict,… etc…(but not set data type because they are un-orderd).
‘index’ represents the positional values of present Series object. The default
value of index starts from 0 to n-1, here ‘n’ represents total values in Series
object. Programatically we can give our own Index Value.
----------------------------------------------------------------------
>>> import pandas as pd
>>> import numpy as np
>>> lst=[10,20,30,40,50,60]
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 20
2 30
3 40
4 50
5 60
dtype: int64 <class 'pandas.core.series.Series'>
----------------------------
>>> lst=[10,20,30,40,50,60]
>>> s=pd.Series(lst,dtype=float)
>>> print(s,type(s))
0 10.0
1 20.0
2 30.0
3 40.0
4 50.0
5 60.0
dtype: float64 <class 'pandas.core.series.Series'>
------------------------------------------------------------------
>>> lst=["Rossum","Gosling","Travis","MCKinney"]
>>> a=np.array(lst)
>>> a ------array(['Rossum', 'Gosling', 'Travis', 'MCKinney'],
dtype='<U8')
>>> print(a, type(a))--['Rossum' 'Gosling' 'Travis' 'MCKinney'] <class
'numpy.ndarray'>
>>> s=pd.Series(a)
>>> print(s,type(s))
0 Rossum
1 Gosling
2 Travis
3 MCKinney
dtype: object <class 'pandas.core.series.Series'>
----------------------------------------------------------------------
>>>lst=[10,"Rossum",34.56,"Author"]
>>> s=pd.Series(lst)
>>> print(s,type(s))
0 10
1 Rossum
2 34.56
3 Author
dtype: object <class 'pandas.core.series.Series'>
-----------------------------------------------------------------------
Examples:
-------------
>>> import pandas as pd
>>> d1={"sub1":"Python","sub2":"Java","sub3":"Data
Science","sub4":"ML"}
>>> print(d1)--{'sub1': 'Python', 'sub2': 'Java', 'sub3': 'Data
Science', 'sub4': 'ML'}
>>> s=pd.Series(d1)
>>> print(s)
sub1 Python
sub2 Java
sub3 Data Science
sub4 ML
dtype: object
>>> d2={"RS":2.3,"JG":1.2,"MCK":4.5,"TOLI":2.4}
>>> print(d2)---{'RS': 2.3, 'JG': 1.2, 'MCK': 4.5, 'TOLI': 2.4}
>>> s=pd.Series(d2)
>>> print(s)
RS 2.3
JG 1.2
MCK 4.5
TOLI 2.4
dtype: float64
=============================================================
Pandas Module in Python
DataFrame in Pandas
a) by using list/tuple.
b) By using dict.
c) By using Series.
d) By using ndarray of numpy.
e) By using CSV Files (comma separated Values).
Explanation:
‘index’ represents Row index and whose default indexing starts from
0, 1, n-1 where n is number of columns.
Rno Name
1 10 RS
2 20 JG
3 30 MCK
4 40 TRA
-------------------------------------------
tpl=( ("Rossum",75), ("Gosling",85), ("Travis",65),
("Ritche",95),("MCKinney",60) )
df=pd.DataFrame(tpl, index=[1,2,3,4,5],columns=['Name','Age'])
print(df)
Name Age
1 Rossum 75
2 Gosling 85
3 Travis 65
4 Ritche 95
5 MCKinney 60
Pandas Module in Python
-----------------------------------------------------------------------
b) Creating an object DataFrame by Using dict object
--------------------------------------------------------------------
When we create an object of DataFrame by using Dict , all the keys
are taken as Column Names and Values of Value are taken as Data.
-----------------
Examples:
-----------------
>>> import pandas as pd
>>>
dictdata={"Names":["Rossum","Gosling","Ritche","McKinney"],"Subjects":[
"Python","Java","C","Pandas"],"Ages":[65,80,85,55] }
>>> df=pd.DataFrame(dictdata)
>>> print(df)
Names Subjects Ages
0 Rossum Python 65
1 Gosling Java 80
2 Ritche C 85
3 McKinney Pandas 55
>>> df=pd.DataFrame(dictdata,index=[1,2,3,4])
>>> print(df)
Names Subjects Ages
1 Rossum Python 65
2 Gosling Java 80
3 Ritche C 85
4 McKinney Pandas 55
----------------------------------------------------------------------
c) Creating an object DataFrame by Using Series object
----------------------------------------------------------------------
>>> import pandas as pd
>>> sdata=pd.Series([10,20,30,40])
>>> df=pd.DataFrame(sdata)
>>> print(df)
0
0 10
1 20
2 30
3 40
>>>
sdata=pd.Series({"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]})
>>> print(sdata)
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
dtype: object
>>> df=pd.DataFrame(sdata)
>>> print(df)
0
IntMarks [10, 20, 30, 40]
ExtMarks [80, 75, 65, 50]
Pandas Module in Python
>>> ddata={"IntMarks":[10,20,30,40],"ExtMarks":[80,75,65,50]}
>>> df=pd.DataFrame(ddata)
>>> print(df)
IntMarks ExtMarks
0 10 80
1 20 75
2 30 65
3 40 50
-----------------------------------------------------------------------
d) Creating an object DataFrame by Using ndarray object
----------------------------------------------------------------------
>>> import numpy as np
>>> l1=[[10,60],[20,70],[40,50]]
>>> a=np.array(l1)
>>> df=pd.DataFrame(a)
>>> print(df)
0 1
0 10 60
1 20 70
2 40 50
>>> df=pd.DataFrame(a,columns=["IntMarks","ExtMarks"])
>>> print(df)
IntMarks ExtMarks
0 10 60
1 20 70
2 40 50
-----------------------------------------------------------------------
e) By using CSV File(Comma Separated Values)
-----------------------------------------------------------------
import pandas as pd1
df=pd1.read_csv("C:\rtkdemo\stud.csv")
print("type of df=",type(df)) #type of df= <class
'pandas.core.frame.DataFrame'>
print(df)
--------------------- OUTPUT--------------------
stno name marks
0 10 Rossum 45.67
1 20 Gosling 55.55
2 30 Ritche 66.66
3 40 Travis 77.77
4 50 KVR 11.11
===========================================================
Python DateTime Module
==========================
Python Dates:
--------------------------------
A date in Python is not a data type of its own, but we can import a module named datetime to work with d
ates as date objects.
========================================================
Creating Date Objects:
--------------------------------------------------
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
=====================================================
The strftime() Method:
------------------------------------------------------
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned stri
ng:
=========================================================
Ex1.py
-------
import datetime
x = datetime.datetime.now()
print(x)
--------------------------------------------------------------------
Ex2.py
---------
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
--------------------------------------------------------------------------------------------------------------------------------------
Ex3.py
------------
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
---------------------------------------------------------------------
Ex4.py
--------------
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
---------------------------------------------------------------------
Ex5.py Weekday, short version
-------------------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%a"))
---------------------------------------------------------------
Ex6.py Weekday, full version
--------------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%A"))
-------------------------------------
Ex7.py Weekday as a number 0-6, 0 is Sunday
-------------------------------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%w"))
--------------------------------------------------------
Ex8.py Day of month 01-31
------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%d"))
---------------------------------------
Ex9.py Month Name Short Version
------------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%b"))
------------------------------
Ex10.py Month Name Full Version
----------------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%B"))
-------------------------------------------
Ex11.py Month as Number 01-12
-----------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%m"))
----------------------------------------------
Ex12.py Year short version
----------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%y"))
--------------------------------------
Ex13.py Year Full Version
--------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%Y"))
-------------------------------------------
Ex14.py AM/PM
------------------------
import datetime
x = datetime.datetime.now()
print(x.strftime("%p"))
------------------------------------------
Ex15.py To disp a calendar for the month
----------------------------------------------------
# Python program to display calendar of
# given month of the year
# import module
import calendar
yy = 2023
mm = 10
Examples:
---------------------
# Python program to convert JSON to Python
import json
# JSON string
employee = ’ {"id":"09", "name": "Rossum", "department":"IT"} ’
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict)
--------------------------------------------------------------------------------------------------------------------------
Python--- read JSON file
--------------------------------------------------------------------------------------------------------------------------
=>json.load() method can read a file which contains a JSON object.
Consider a file named
employee.json which contains a JSON object.
Syntax:
json.load(file_object)
------------------------------------------------------------------------------------------------------
Ex1:
-----
import json
# JSON string
employee = ’{"id":"09", "name": "Rossum", "department":"IT"}’
print(employee,type(employee))
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict,type(employee_dict))
------------------------------------------------------------------------
Ex2:
------
import json
# JSON string
employee = ’ {"id":"09", "name": "Rossum", "department":"IT"} ’
print("Json String data=",employee)
# Convert string to Python dict
employee_dict = json.loads(employee)
print("Dict Data=",employee_dict)
for k,v in employee_dict.items():
print("{}-->{}".format(k,v))
---------------------------------------------------------------------------------
Ex3:
----------
# Python program to write JSON to a file
#JsonWrite.py
import json
# Data to be written
dictionary ={
"name" : "Rossum",
"rollno" : 56,
"cgpa" : 8.6,
}
with open("C:\\Users\\ritik\\OneDrive\\Desktop\\jsonfile.json","w") as fp:
json.dump(dictionary, fp)
print("Data written to file--verify")
------------------------------------------------------------------------------------------
Ex4:
------------
# Python program to read json file
#JsonRead.py
import json
# Opening JSON file
try:
fp = open("C:\\Users\\ritik\\OneDrive\\Desktop\\jsonfile.json")
# returns JSON object as a dictionary
data = json.load(fp)
# Iterating through the json list
for i,j in data.items():
print("{}--->{}".format(i,j))
except FileNotFoundError:
print("Json File does not exist")
------------------------------------------------------------------------------------