Professional Documents
Culture Documents
Python by Sathish Sir
Python by Sathish Sir
Duration : 50 sessions
rambabu
: 9866545966
support@nareshit.com
pythonbygupta@gmail.com
mon-sat ==>
Q: What is python?
Q: Features Python
Q: Applications of python
Demo-1:
Q: What is python?
==> language is a software which provide set of instructions to develop softwares or applications.
language.
1
==> python is a high level programming language. all high level language are simple english. all high level
languages are portable language. portability allows to develop and run python programs on different
platforms.
==> python is a multiparadigm programming language. A programming paradigm define set of rules and
regulations to write programs.
1. Monolithic Porgramming
Q: What is python?
1. Programming Language
2. General Purpose
4. Multiparadigm
programming alngauge.
Demo-2:
Python Features
=============
1. Easy
a. easy to understand
b. easy to code
==> python is easy to understand becoz it is high level language and high level language are english like.
2
3. Free and OpenSource
==> python source code is open to public. which allows to develop new technologies using python.
Demo-3:
=======
applications.
1. Cpython
2. Jython
3. IronPython
4. Pypy
C ==> Turboc
3
Demo-4:
6. Interpreted
=============
Q: What is Translator?
Translator is a software which translates the instructions written in one language to another
language.(Source Language==>Translator==>Dest Language)
1. Interpreter
2. Compiler
Q: What is interpreter?
==> interpreter is a translator, which translates and execute execute instructions line by line.
Q: What is compiler?
==> compiler is a translator, which translate complete program and start execution.
Q: What is bytecode?
PVM.
Q: What is PVM?
Applications of Python
==================
python.
4
Guideo Van Rossum in the year 1980.
==> Python name is derived/taken from comedy series which is telecasted in BBC in 1980. "Monty
python flying Circus'
Python Versions
=============
int,long int
raw_input input
xrange range
www.python.org
Python Software
==============
1. Windows
2. Linux
3. Solaries
4. MacOS
5
Python Software Consist of,
2. Lib
3. development tools(pip)
4. Python compiler
5. Python Interprter(PVM)
1. Interactive mode
Python IDE's(Editors)
==================
1. PyCharm
2. Jupiter
3. Spyder
===================
6
UNICODE support alphabets in all languages,digits(0-9) and special characters.
Tokens
======
1. keywords
2. identifiers
3. datatypes
4. operators
5. literals
keywords
========
and,or,not,del,in,as,is
True,False,None
if,else,elif,for,while,break,continue,return
def,global,nonlocal,lambda,yield,pass
import,from,with
7
6. keywords belongs execption handling
try,except,finally,raise,assert
class
async,await
Identifiers
=========
1. variables
2. functions
3. classes
4. modules
5. packages
Identifier rules
=============
Quiz:
A. True
B. False
8
C. true
D. false
Ans: C,D
A. $amt
B. amt$
C. student_name
D. amt_
A. int
B. float
C. class
D. False
35
Datatypes
=========
1. Standard Datatypes
2. Sequences
3. Collections
9
==> python is an object oriented programming language.
Q: What is object?
eg: car,mobile,keyboard,monitor,customer,account,employee,product,...
Q: What is class?
SBI of an object?
SBI stands,
S ==> State
B ==> Behaviour
I ==> Identity
Q: What is variable?
10
int
==
pythonbrains
26/5/2020
=========
id(object)
eg:
>>> a=10
>>> b=20
>>> id(a)
1720186944
>>> id(b)
1720187104
>>> c=10
>>> id(c)
1720186944
11
==> whenever we modify value, it will create new int object.
QUIZ:
a=100
b=200
c=300
d=400
Ans: 4 objects
Ans: 4 variable
a=100
b=200
c=100
d=200
Ans: 2 objects
4 variables
a=5
b=5
c=10
d=a+b
Ans: 2 objects
4 variables
a=10
b=20
c=a+b
Ans: 3 objects
12
5. How many objects are garbage collected?
a=100
b=200
c=100
a=300
Ans: 0
==================================
x=257
y=257
print(id(x))
print(id(y))
========================================
27/5/2020
=========
1. decimal format
2. octal format
4. binary format
decimal number: an number value with base 10 is called decimal number. this number
consist of digits from 0-9. this number is prefix with + or -. the defualt number system
is decimal. it allows one special character _. _ character is used in numbers for grouping digits. this _
cannot used as prefix or sufix.decimal number should not start with 0.
binary number : an numeric value with base 2 is called binary number. this number of consist of two
digits 0,1. this number is prefix with 0b or 0B.
eg:
>>> y=0b10101
13
>>>x
>>>y
10
hexa decimal format : a numeric value with base 16 is called hexa decimal numer. this number consist of
digits from 0-9 and a-f/A-F. this number is prefix 0x or 0X. this number is system is used to represent
larger values(address,colors,...)
eg:
>>>x=0xa
>>>y=0xb
>>>x
10
>>>y
11
octal number : a numeric value with base 8 is called octal number. this number consist of digits from 0-
7. this number is prefix with 0o or 0O.
>>>x=0o12
>>>y=0o13
>>>x
10
>>>y
11
python : a=0
c : int a;
type(variable-name/value):
>>>a=10
14
>>>type(a)
<class 'int'>
float
====
==> float datatype reserve memory for real numbers or floating point numbers or
1. fixed
2. expo
28/5/2020
=========
float
====
==> float datatype reserve memory for real numbers or floating point numbers or
1. fixed
2. expo
15
==> whenever there is a change it will create new object.
double == 8bytes
eg:
x=1.5
y=1.5e0
print(id(x))
print(id(y))
print(x)
print(y)
print(type(x))
print(type(y))
QUIZ:
Q: Find output?
x=1.0
y=1.
print(x)
print(y)
output: 1.0
1.0
Q: Find output?
x=123e-2
print(x)
Output:
1.23
16
Q: Find Output?
x=123e2
print(x)
Output: 12300.0
x=0.5
y=0.5
Ans: 1
complex
=======
1. real 2. img
syntax:
real+imagj
eg:
>>> comp1=1+2j
>>> comp1
(1+2j)
>>> comp1.real
1.0
>>> comp1.imag
2.0
>>> type(comp1)
<class 'complex'>
>>> type(comp1.real)
<class 'float'>
>>> type(comp1.imag)
17
<class 'float'>
==> complex number is immutable, after creating complex number we cannot modify
>>> comp1.real=1.2
comp1.real=1.2
>>> comp1.imag=2.0
comp1.imag=2.0
comp1=1+2j
comp2=1+2j
print(comp1)
print(comp2)
print(type(comp1))
print(type(comp2))
print(id(comp1))
print(id(comp2))
print(comp1.real)
print(comp1.imag)
print(comp2.real)
print(comp2.imag)
18
QUIZ:
comp1=1+2j
comp2=2j
comp3=1
comp1=1+2j
comp2=2j
bool
====
keywords.
1. True
2. False
>>> a=True
>>> b=False
>>> a
True
>>> b
False
>>> type(a)
<class 'bool'>
19
>>> type(b)
<class 'bool'>
name=
age=90
seats=5
seatsreserved=True
string
=====
==> string is a collection of characters and these characters can be alphabets,digits or special characters.
==> the string which contain only alphabets is called alphabetic string.
==> the string which contain alphabets,digits and special characters is called alphanumeric string.
3. within three single quotes ''' ''' or three double quotes """ """
eg:
>>> name='naresh'
>>> name
'naresh'
>>> type(name)
<class 'str'>
>>>
>>> name1="suresh"
>>> name2='''ramesh'''
>>> name3="""rajesh"""
>>> type(name1)
<class 'str'>
20
>>> type(name2)
<class 'str'>
>>> type(name3)
<class 'str'>
>>> name
'naresh'
>>> name1
'suresh'
>>> name2
'ramesh'
>>> name3
'rajesh'
>>>
29/5/2020
=========
==> using three signle quotes or double quotes we can represent multiline string.
21
print("python is a 'General Purpose' programming language")
print('python\njava\noracle')
escape sequences
================
\n ==> newline
\b ==> backspace
\\ ==> backslash
==> single and double quotes are used to represent singleline string
====================================================================
22
eg:
name="naresh"
address='''Ameerpet,
Hyderabad'''
print(name)
print(address)
===================================================================
eg:
s1="java"
s2="java"
s3="python"
s4="python"
print(id(s1))
print(id(s2))
print(id(s3))
print(id(s4))
print(s1)
print(s2)
print(s3)
print(s4)
==================================================================
Indent
=====
23
==> if working with ide's indent is set automatically.
comments in python
=================
================================================================
eg:
print(num1)
print(num2)
print(num3)
==================================================================
eg:
r=1.5
area=3.147*r*r
print(area)
===================================================================
24
print()
=====
C: python
==>python lib is called module(a module is python program). these modules are
syntax:
print(value,...,sep=' ',end='\n',file=sys.stdout,flush=False)
eg:
print()
print("Hello World")
print(100,200,300)
print("python",3.8,"lanauge")
QUIZ:
Find output?
print("Python")
print("Python",3.8)
print("Python",3.8,sep='$')
Output:
Python
Python 3.8
25
Python,3.8
Find output?
print(10,20,30,40,50)
print(10,20,30,40,50,sep='$')
10 20 30 40 50
10$20$30$30$50
Find output?
print(10,20,30,40,50,sep='\n')
10
20
30
40
50
CRT@4.00PM
by
Demo Link:
www.zoom.us/j/98394372651
NareshIT
9000994007 / 08
Rambabu
9866545966
1/06/2020
=========
eg:
print("Hello")
26
print(10,20,30,40,50)
print(10,20,30,40,50,sep=':')
print(10,20,30,40,50,sep=',')
print(10)
print(20,end=' ')
print(30)
print(40)
output:
Hello
10 20 30 40 50
10:20:30:40:50
10,20,30,40,50
10
20 30
40
input()
======
==> input() function read the value and return that value as string.
syntax:
input([prompt])
eg:
a=input()
b=input()
print(a)
print(b)
x=input("X Value")
27
y=input("Y Value")
print(x)
print(y)
eg:
rollno=input("Enter Rollno")
name=input("Enter name")
print(rollno)
print(name)
output:
Enter Rollno101
Enter namenaresh
101
naresh
===============================================================
n3=n1+n2
print(n1,n2,n3)
print(type(n1))
print(type(n2))
print(type(n3))
print(n4)
print(type(n4))
28
=====================================================================
Conversion functions
==> python provide the following conversion functions to convert one tye of object to
another type.
1. int() function
this function is used to create integer object using different types of values.
int(float value) ==> create integer object using float value/float to int
int(string value,base=10) ==> create integer object using string value/string to int
eg:
z=int(1.5) # creating integer object using float value or converting float to int
print(x,y,z)
print(n1,n2,n3,n4,n5)
QUIZ:
Find Error:
x=int("abc") # ValueError
print(x)
Find output?
29
print(x)
Find output?
x=int("-10")
print(x)
Find output?
x=int(1.5)
print(x) ==> 1
Find output?
x=int("0o189",base=8) # error
print(x)
Find output?
x=int(0x123) # no error
print(x)
Find output?
x=int("0x123",base=16)
print(x)
n1=int(x)
n2=int(y)
n3=n1+n2
print("sum of ",n1,n2,"is",n3)
z=x+y
float()
30
=====
==> it allows to creating float object using float,int and string value.
z=float(15) # creating float object using integer value ==> int to float
p=float("15") # creatinf float object using string value ==> str rep int to float
eg:
n1=float("1.5")
n2=float(1.5)
n3=float(10)
n4=float("10")
n5=float("1.5e2")
print(n1,n2,n3,n4,n5)
eg:
area=0.5*base*height
output:
H.W:
31
2. write a program to find simple intrest
complex()
========
eg:
>>> c1=complex(1.5,2.5)
>>> c1
(1.5+2.5j)
>>> c2=complex(real=1.2)
>>> c2
(1.2+0j)
>>> c3=complex(imag=2.5)
>>> c3
2.5j
>>> c4=complex(1+2j)
>>> c4
(1+2j)
>>> c5=complex("1+2j")
>>> c5
(1+2j)
32
02-06-2020
2/06/2020
=========
complex()
========
eg:
>>> c1=complex(1.5,2.5)
>>> c1
(1.5+2.5j)
>>> c2=complex(real=1.2)
>>> c2
(1.2+0j)
>>> c3=complex(imag=2.5)
>>> c3
2.5j
>>> c4=complex(1+2j)
>>> c4
(1+2j)
>>> c5=complex("1+2j")
>>> c5
(1+2j)
33
comp3=comp1+comp2
print(comp1,comp2,comp3)
bool()
=====
b1=bool(True)
b2=bool(False)
b3=bool("True")
b4=bool("False")
print(b1,b2)
print(b3,b4)
print(type(b1),type(b2),type(b3),type(b4))
rollno=int(input("Enter rollno"))
name=input("Enter name")
fee=float(input("Enter Fee"))
feepaid=bool(input("Enter FeePaid"))
print(rollno)
print(name)
print(fee)
print(feepaid)
output:
Enter rollno101
Enter namenaresh
Enter Fee4000
Enter FeePaidTrue
101
naresh
4000.0
34
True
formatting output
===============
2. format function
===================================
==> in this style of formatting a string is defined with replacement fields. these
conversion characters:
%b ==>binary integer
%s ==> string
%% ==>% character
35
eg:
a=65
b=0o12
c=0xab
print(a,b,c)
print("a=%d,b=%o,c=%x"%(a,b,c))
r=float(input("Enter r"))
area=3.147*r*r
eg:
a=1.234567
print("%f"%a)
print("%.3f"%a)
print("%.2f"%a)
eg:
a=1.0
print("%.2f"%a)
print("%.1f"%a)
eg:
a=12e1
print(a)
print("%e"%a)
eg:
x='A'
y='Python'
print("x=%s,y=%s"%(x,y))
36
n1=65
eg:
rollno=int(input("Enter rollno"))
name=input("Enter name")
sub1=int(input("Enter sub1"))
sub2=int(input("Enter sub2"))
sub3=int(input("Enter sub3"))
total=sub1+sub2+sub3
avg=total/3
print("Rollno %d"%rollno)
print("Name %s"%name)
print("Sub1=%d,Sub2=%d,Sub3=%d"%(sub1,sub2,sub3))
print("Total %d"%total)
print("Avg %.2f"%avg)
=======================================
04-06-2020
4/06/2020
=======================================
37
==> in python3 formatting is done by calling format function.
syntax:
are represented using {}. these fields are identified with its position or name.
eg:
a=10
b=20
c=a+b
output:
sum of 10 and 20 is 30
n1=10
n2=20
n1=10
n2=20
eg:
# find output
print("{}{}{}{}{}{}".format(10,20,30,40,50,60))
print("{3}{0}{1}{2}".format(10,20,30,40))
print("{a}{b}{c}".format(b=100,a=200,c=300))
38
dim1=float(input("Enter dim1"))
dim2=float(input("Enter dim2"))
area=dim1*dim2
(dim1=dim1,dim2=dim2,area=area))
eg:
n=65
print("{:d},{:o},{:x},{:b}".format(n,n,n,n))
a=65
b=0o45
c=0xab
d=0b101
print("{:d},{:o},{:x},{:b}".format(a,b,c,d))
print("{1:d},{0:o},{2:b},{3:x}".format(b,a,d,c))
print("{p:d},{q:o},{r:x},{s:b}".format(p=a,q=b,r=c,s=d))
'''
d => decimal
o => octal
b => binary
'''
# f=(c*9/5)+32
39
f=(c*9/5)+32
x=1.5
y=1.5e-1
print("{}{}".format(x,y))
print("{:f},{:e}".format(x,y))
print("{:e},{:f}".format(x,y))
n1=10
n2=100
n3=1000
n4=10000
n5=100000
print(n1)
print(n2)
print(n3)
print(n4)
print(n5)
print("{:6d}".format(n2))
print("{:6d}".format(n3))
print("{:6d}".format(n4))
print("{:6d}".format(n5))
print("{:06d}".format(n2))
print("{:06d}".format(n3))
40
print("{:06d}".format(n4))
print("{:06d}".format(n5))
==============================================
name1="Anshu"
name2="Prakash"
name3="Dell Inspiron"
name4="Nilesh"
print("{:12s}".format(name1))
print("{:12s}".format(name2))
print("{:12s}".format(name3))
print("{:12s}".format(name4))
print("{:>12s}".format(name1))
print("{:>12s}".format(name2))
print("{:>12s}".format(name3))
print("{:>12s}".format(name4))
print("{:^20s}".format(name1))
print("{:^20s}".format(name2))
print("{:^20s}".format(name3))
print("{:^20s}".format(name4))
====================================================================
41
==> write a program to input to angles of triangle and find third angle
05-06-2020
5/06/2020
=========
========================
print('python')
print(f'python')
eg:
a=100
b=200
print(f'{a},{b}')
x=1.5
y=2.5
print(f'{x},{y},{x+y}')
eg:
base=float(input("enter base"))
height=float(input("enter height"))
area=0.5*base*height
print(f'base={base},height={height},area={area}')
eg:
42
# f-string with type characters
a=65
b=0o16
c=0xab
d=0b1010
print(f'{a},{b},{c},{d}')
print(f'{a:d},{b:o},{c:x},{d:b}')
#---------------------------------------------------------------------
n1=1.5
n2=1.5e0
print(f'{n1},{n2}')
print(f'{n1:f},{n2:e}')
print(f'{n1:.2f},{n2:.2e}')
#----------------------------------------------------------------------
c1=1+2j
c2=3+4j
print(f'{c1},{c2}')
print(f'{c1.real},{c1.imag},{c2.real},{c2.imag}')
#-----------------------------------------------------------------------
s1="python"
s2="java"
print(f'{s1},{s2}')
print(f'{s1:10s}{s2:10s}')
#------------------------------------------------------------------------
a=40
b=450
c=5600
d=65000
print(f'{a:>10d}\n{b:>10d}\n{c:>10d}\n{d:>10d}')
43
#--------------------------------------------------------------------------
Operators
========
Q: What is operator?
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Identity Operators
7. Membership Operators
8. Conditional Operators
Arithmetic Operators
=================
==> arithmetic operators are binary operators, which required two operands.
% ==>binary modulas
=============================================================
44
r1=10+20
r2=1.5+1.2
r3=(1+2j)+(1+3j)
r4="python"+"language"
r6=False+False
r7=True+False
r8=False+True
print(r1,r2,r3,r4,r5,r6,r7,r8)
# int,float,complex
# complex>float>int
r9=10+1.5
r10=5+(2+4j)
print(r9,r10)
r11=1+2.5+(1+2j)
print(r11)
r12=int(10+1.5)
print(r12)
r13=float(10+20)
print(r13)
r14=int(1+2j) # error
print(r14)
=====================================================================
# Find Output
x=10+"python" # error
45
print(x)
===========================================================
x=str(10)+"python"
print(x)
=============================================================
r1=20-10
r2=1.5-0.05
r3=(3+2j)-(2+1j)
print(r1,r2,r3)
''' s1="java"
s2="python"
=============================================================
r1=5*2
r2=1.5*2.5
r3=(1+2j)*(2+3j)
print(r1,r2,r3)
s1="python"*2
print(s1)
line="*"*50
print(line)
06-06-2020
6/6/2020
========
46
python provide 3 division operators:
% ==>binary modulas
eg:
r1=10/2
r2=5/2
print(r1,r2)
print(type(r1),type(r2))
r3=10.0/2.0
r4=5.0/2.0
print(r3,r4)
'''
'''
===============================================================
47
num1=int(input("Enter numerator"))
num2=int(input("Enter denominator"))
rem=num1%num2
print(f'num1={num1},num2={num2},rem={rem}')
===================================================================
start=int(input("start reading"))
end=int(input("end reading"))
units=end-start
day=units//30
print(start,end,units,day)
'''
5//2 ==> 2
'''
===============================================================
r1=10//2
r2=5//2
print(r1,r2)
48
print(type(r1),type(r2))
r3=10.0//2 # return result into integer type, convert that integer result into float
r4=5//2.0
print(r3,r4)
print(type(r3),type(r4))
r5=10.0//2.0
print(r5)
r6=5.0//2.0
print(r6)
====================================================================
res=10**2
print(res)
n=int(input("enter n value"))
p=int(input("enter p value"))
print(f'{n},{p},{n**p}')
==================================================================
Relational Operators
==> Relational operators are used to find relationship between to operands or values.
49
>= ==> greaterthan or equal
================================================================
str1="a" #97
str2="A" #65
b1=str1>str2 # True
print(b1)
str3="ab" # 97 98
str4="ba" # 98
b2=str3>str4
print(b2)
str5="abc" # 97 98 99
str6="abd" # 97 98 100
b3=str5>str6
print(b3)
str7="ab" # 97 98
str8="abc" # 97 98 100
b4=str7>str8
print(b4)
str9="ab"
str10="ab"
b5=str9==str10
print(b5)
str11="abc" # 97 98 99
str12="ab" # 97 98
50
b6=str11>str12
print(b6)
=====================================================================
r1=100>50 # True
r2=50>100 # False
r3=100<50 # False
r4=50<100 # True
print(r1,r2,r3,r4)
r5=100>=50 # True
r6=50>=50 # True
r7=50>50 # False
r8=49<=50 # True
r9=49<50 # True
print(r5,r6,r7,r8,r9)
r10=10==10
print(r10) # True
r11=10==11 # False
print(r11)
r12=10!=10 # False
print(r12)
r13=10!=11 # True
print(r13)
====================================================================
Logical operators
===============
1. and
2. or
51
3. not
======================
====================
=====================
True False
False True
08-06-2020
08/06/2020
==========
eg:
52
print(res1,res2,res3,res4)
res5=True or True
res6=True or False
res7=False or True
res8=False or False
print(res5,res6,res7,res8)
print(res9)
print(res10)
====================================
>>=
<<=
assignment.
num1=5
num1+=10
print(num1)
num2=15
num2-=5
print(num2)
53
num3=20
num3*=2
print(num3)
num4=30
num4/=3
print(num4)
num5=40
num5//=4
print(num4)
num6=5
num6**=2
print(num6)
=========================================================
# find output
n1=5
n2=6
n1+=n2 # n1=n1+n2
print(n1) # 11
print(n2) #
#======================================
x=5
y=3
x**=y
print(x)
print(y)
#========================================
bitwise operators
==============
==> bitwise operators are used to perform operations in the form of bits.
54
1. >> : Rightshift operator
4. | : Bitwise or operator
value>>n
n1=10
n1=n1+2 ==> 12
x=20
x=x-5 ==> 15
0010 ==> 2
eg:
n=20
print(n)
n=n>>2
print(bin(n))
print(n)
x=456
print(x)
print(bin(x))
x=x>>3
55
print(x)
print(bin(x))
'''
value=20
'''
=================
==>This operator allow to add bits. By adding bits the value get incremented.
value<<n
eg:
value=10 # 1010
print(value)
value=value<<2 # 101000
print(value)
===============
0 1 0
1 0 0
1 1 1
0 0 0
Bitwise | operators
==================
56
==> truth table of bitwise | operator
0 1 1
1 0 1
1 1 1
0 0 0
Bitwise ^ operator
===============
0 0 0
0 1 1
1 0 1
1 1 0
num1=100
num2=200
num3=num1
num1=num2
num2=num3
print(num1,num2)
x=100
y=200
x,y=y,x
print(x,y)
m=100
57
n=200
m=m+n
n=m-n
m=m-n
print(m,n)
a=100
b=200
a=a^b
b=a^b
a=a^b
print(a,b)
conditional operator
=================
print(n1,n2,n3)
vowel")
58
print("vowel") if ch in "aeiouAEIOU" else print("not vowel")
==============================================================
# login application
user=input("****UserName :")
or password")
============================================================
membership operators
===================
==> membership operators are used to to compare one value with group of values.
1.in
2.not in
Identity operators
===============
==> identity operators are used to compare identity/id, which is called address
is
is not
a=100
b=100
c=a is b
09-06-2020
09/06/2020
59
=========
Operator precedence:
==================
Operators in the same box have the same precedence. Unless the syntax is explicitly
given, operators are binary. Operators in the same box group left to right (except for
or Boolean OR
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests
| Bitwise OR
^ Bitwise XOR
division, remainder
** Exponentiation
60
Binding or tuple display, list display, dictionary display,
set display.
control structures
===============
==> control structures are used to control the flow of execution of program.
1. conditional statements
condtional statement
=================
1. simple if
2. if..else
4. nested if
simple if
=======
syntax:
if <condition>:
statement-1
statement-2
statement-3
61
eg:
if True:
eg:
if True:
print("Java")
print("Python")
eg:
if False:
print("Hello")
print("Bye")
if..else
======
syntax:
if <condition>:
statement-1
statement-2
else:
statement-3
statement-4
statement-5
62
r=num%2
if r==0:
print(f'{num} is even')
else:
print(f'{num} is odd')
name=input("Enter name")
print(f'Name is {name}')
print("Fail")
else:
print("Pass")
year=int(input("enter year"))
if year%4==0 or year%400==0:
print(f'{year} is leap')
else:
if ch in "aeiouAEIOU":
print(f'{ch} is vowel')
else:
if..elif..else (if..else..ladder)
=======================
63
==> This syntax allows check multiple conditions.
if <condition1>:
statement-1
elif <condition2>:
statement-2
elif <condition3>:
statement-3
..
else:
statement-4
statement-5
10-06-2020
10/06/2020
===========
if..elif..else (if..else..ladder)
=======================
if <condition1>:
statement-1
elif <condition2>:
statement-2
elif <condition3>:
statement-3
..
else:
statement-4
statement-5
64
==> if condition1 is False and condition2 True, it execute statement-2 and statement-5
and statement-5.
statement-5.
print(f'{n1} is max')
print(f'{n2} is max')
print(f'{n3} is max')
else:
========================================================
character
print(f'{ch} is alphabet')
print(f'{ch} is digit')
else:
===================================================================
ord
65
===
ord(c, /)
ord('A') ==> 65
ord('B') ==> 66
ord('a') ==> 97
value=ord(ch)
print(f'{ch}={value}')
=================================================================
chr
===
chr(i, /)
chr(65) ==> A
chr(66) ==> B
chr(97) ==> a
ch=chr(value)
print(f'{value}={ch}')
=================================================================
value=ord(ch)
value=value+32
66
ch=chr(value)
print(f'{ch}')
value=ord(ch)
value=value-32
ch=chr(value)
print(f'{ch}')
else:
================================================================
if num>0:
print(f'{num} is +ve')
elif num<0:
print(f'{num} is -ve')
else:
print("zero")
===============================================================
nested if
=======
syntax:
if condition1:
if condition2:
statement-1
else:
statement-2
else:
67
statement-3
statement-4
=====================================================================
# login program
user=input("UserName :")
pwd=input("Password :")
if user=='nit':
if pwd=='nit123':
print("Welcome to My Application")
else:
print("Invalid password")
else:
print("Invalid username")
====================================================================
# banking logic/transactions
accno=int(input("enter accno"))
balance=float(input("enter balance"))
if ttype=='d':
amt=float(input("enter amount"))
balance=balance+amt
print("Deposit done")
elif ttype=='w':
amt=float(input("enter amount"))
if amt>balance:
68
print("Insuff balance")
else:
balance=balance-amt
print("Withdraw done")
else:
print(f'AccountNo {accno}')
print(f'CustomerName {cname}')
print(f'Balance {balance}')
====================================================================
saleamount>5000<10000 == > 5%
salesamount<=5000 ==> 2%
=====================================
==> iterative statements or looping statements are used repeate one or more than one
1. while
2. for
11-06-2020
11/06/2020
69
==========
=====================================
==> iterative statements or looping statements are used repeat one or more than one
1. while
2. for
while loop
====
==> it allows to repeat one or more than one statement number of times or until given
condition.
syntax-1:
while <condition>:
statement-1
statement-2
syntax-2:
while <condition>:
statement-1
statement-2
else:
statement-3
statement-4
70
==> statement-1 and statement-2 is repeated until condition is True, if condition is
1. init statement
2. condition
3. updating
==> condition, it is a boolean expression which define how many times loop has to
executed.
*************************************************************************************
****
i=1
while i<=5:
print("naresh")
i=i+1
*************************************************************************************
****
while False:
print("NIT")
# no output
*************************************************************************************
***
while True:
print("NARESH")
print("PYTHON")
=================================================================
print("PYTHON")
==================================================================
71
# write a program/script to print alphabets from A-Z,a-z
n=65
while n<=90:
print(chr(n),end=' ')
n=n+1
print()
n=97
while n<=122:
print(chr(n),end=' ')
n=n+1
=================================================================
ch='A'
while ch<='Z':
print(ord(ch),end=' ')
n=ord(ch)+1
ch=chr(n)
==============================================================
i=1
while i<=10:
print(f'{num}x{i}={num*i}')
i=i+1
=====================================================================
i=1
c=0
72
while i<=num:
r=num%i
if r==0:
c=c+1
i=i+1
if c==2:
print(f'{num} is prime')
else:
====================================================================
c=0
if num==0:
c=1
else:
num=abs(num)
while num!=0:
num=num//10
c=c+1
print("count of digits",c)
==============================================================
1+2+3+4+.......+n
1**2+2**2+3**2+..... +n**2
73
12-06-2020
12/6/2020
=========================================================
num=1
n=int(input("enter n value"))
while num<=n:
print(num)
num+=1
===========================================================
num=1
while num<=n:
print(num) # 2 4
num+=1 # 2 3 4 5 6
=======================================================
num=1
while num<=n:
print(num) # 1 3 5
num+=1 # 2 3 4 5 6
===========================================================
# 1+2+3+4+.......+n
74
num=1
n=int(input("enter n value"))
s=0
while num<=n:
s=s+num
num=num+1
========================================================
#5.
num=1
n=int(input("enter n value"))
s=0
while num<=n:
s=s+(num**2)
num=num+1
=============================================================
% ==> modulas
476%10=6==>
476//10=>47
47%10 ==> 7
47//10 ==> 4
4%10 ==> 4
4//10 ==> 0
75
sum=0
while num!=0:
r=num%10
sum=sum+r
num=num//10
==============================================================
//
rev=0
r=123%10=3
rev=(rev*10)+r==> 3
123//10 ==> 12
r=12%10 ==> 2
rev=(rev*10)+r ==> 32
12//10 ==> 1
r=1%10 ==> 1
rev=(rev*10)+r ==>321
rev=0
while num!=0:
r=num%10
rev=(rev*10)+r
num=num//10
print(rev)
==================================================================
76
121 ==> 121 ==> pal
num1=num
rev=0
while num!=0:
r=num%10
rev=(rev*10)+r
num=num//10
if rev==num1:
print(f'{num1} is pal')
else:
=================================================================
for loop
=======
==> The for statement in Python differs a bit from what you may be used to in C or
Pascal.
==> Rather than always iterating over an arithmetic progression of numbers (like in
Pascal), or giving the user the ability to define both the iteration step and halting
condition (as C), Python’s for statement iterates over the items of any sequence (a list
syntax-1:
statement-1
statement-2
==> it repeate this until all the objects read from collection/sequence.
77
syntax-2:
statement-1
statement-2
else:
statement-3
statement-4
===================================================================
for ch in str1:
print(ch)
=====================================================================
count=0
for ch in str1:
if ch in "aeiouAEIOU":
count+=1
==============================================================
str2=''
for ch in str1:
o=ord(ch)-32
str2=str2+chr(o)
else:
str2=str2+ch
78
print(str1)
print(str2)
================================================================
# write a program to find how many alphabets,digits and special characters exists
abc123 ==> 3 3
ab123* ==> 2 3 1
acount=0
dcount=0
scount=0
for ch in str1:
acount+=1
dcount+=1
else:
scount+=1
====================================================================
# write a program to count a given character is repeated how many times in given string
79
13-06-2020
13/06/2020
===========
i=1
while i<=5:
print("Prakash")
i+=1
range()
======
==> The range type represents an immutable sequence of numbers and is commonly
1. range(stop)
2. range(start,stop,step)
print(r)
for value in r: # 0 1 2 3 4
print(value)
==========================
# find output
r=range(-5)
for value in r:
print(value)
# No output
80
# if step is +ve, the start value must be less than stop value
# if step is -ve, the start value must be greater than stop value
# default step +1
=============================================
print(value)
print("*******************")
print(value)
print("*******************")
print(value)
print("*******************")
print(value)
================================================
print(value,end=" ")
print()
print(value,end=" ")
print()
===================================================
81
for value in range(65,91):
print(value,"=",chr(value))
print(value,"=",chr(value))
===============================================
c=0
for i in range(1,num+1):
if num%i==0:
c+=1
if c==2:
print(f'{num} is prime')
else:
================================================
fact=1
fact=fact*value
print("Factorial is ",fact)
=================================================
15-06-2020
15/06/2020
82
----------
nested loops
==========
1.nested for
2.nested while
============
syntax:
statement-1
statement-2
statement-3
=====================================================
for x in range(5):
for y in range(1,6): # 1 2 3 4 5
print(y,end=' ')
print()
=====================================================
for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
print(f'{num}*{i}={num*i}')
======================================================
83
for num in range(1,n+1): # 5 6
count=0
for i in range(1,num+1): # 1 2 3 4 5 6
if num%i==0:
count+=1
if count==2:
print(num,end=' ')
=========================================================
for i in range(1,6): #1 2 3 4 5
for j in range(1,6):
print(i,end=' ')
print()
=========================================================
for i in range(1,6): # 1 2 3 4 5
for j in range(1,i+1):
print(i,end=' ')
print()
=========================================================
for i in range(5,0,-1): #5 4 3 2 1
for j in range(1,6):
print(i,end=' ')
print()
==========================================================
for i in range(5,0,-1): #5 4 3 2 1
for j in range(1,i+1):
print(i,end=' ')
print()
=========================================================
for i in range(5,0,-1):
84
for j in range(1,i+1):
print(j,end=' ')
print()
==========================================================
for i in range(1,6):
for j in range(1,i+1):
print(j,end=' ')
print()
==========================================================
for i in range(1,6):
for j in range(5,0,-1):
if i>=j:
print(j,end=' ')
else:
print()
=====================================================
16-06-2020
16/06/2020
=========
======================================================
for i in range(1,6):
for j in range(1,6):
if i<=j:
print(j,end=' ')
else:
print()
85
===========================================================
for i in range(1,6):
for j in range(1,6):
if i<=j:
print(j,end=' ')
else:
print()
=========================================================
for i in range(5,0,-1):
for j in range(5,0,-1):
if i>=j:
print(j,end=' ')
else:
print()
=========================================================
for i in range(5,0,-1):
for j in range(1,6):
if i<=j:
print(j,end=' ')
else:
print()
============================================================
k=1
for i in range(1,6):
for j in range(1,6):
if j<=i:
86
print(k,end=' ')
k+=1
print()
=============================================================
if ((col==0 or col==4) and row!=0) or (row==0 or row==3) and (col<4 and col>0):
print("*",end=' ')
else:
print()
==================================================================
print("*",end=' ')
else:
print()
==================================================================
nested while
===========
syntax:
statement-1
statement-2
87
statement-3
statement-4
17-06-2020
17/06/2020
==========
nested while
===========
syntax:
statement-1
statement-2
statement-3
statement-4
=================================================================
num=1
while num<=10:
i=1
while i<=10:
print(f'{num*i:4d}',end='')
i+=1
print()
num+=1
=================================================================
88
# 145
# 1!+4!+5!=145
org=num #12
sum_fact=0
while num!=0:
fact=1
while d>0:
d=d-1
sum_fact=sum_fact+fact # 2+1=3
if sum_fact==org:
print("Strong Number")
else:
==================================================================
break statement
==============
pass statement
=============
==> inorder to write a block without doing any operation we include pass statement.
89
eg:
i=1
while i>10:
print(i)
eg:
i=1
while i<=10:
pass
eg:
i=1
while i<=10:
break
===========================================================
# find output
i=1
while i<=10:
pass
print("Hello")
i=i+1
=========================================================
#8
i=1
c=0
while i<=num:
if num%i==0:
90
c+=1
if c>2:
break
i+=1
if c>2:
else:
print(f'{num} is prime')
===============================================================
while True:
print("1. Python")
print("2. Java")
print("3. C")
print("4. C++")
print("5. Exit")
if opt==1:
elif opt==2:
elif opt==3:
elif opt==4:
elif opt==5:
break
==================================================================
continue
=======
91
==> continue is a passes control statement.
==> the statement moves to begining of the loop (OR) continue current loop
19-06-2020
18&19/06/2020
=============
continue
=======
==> the statement moves to begining of the loop (OR) continue current loop.
==============================================================
===================
Q: what is bug?
==> Go : Press this option advace execution to the next break point.
==> Step : press this option to execute the current line and goto nextline
==> Over : If the current line is having function call, then press this option to step over
==> Out: I thr current line having function call continue execution of this function until
Break point
=========
92
==> when break point is set, the interpreter pause on this line
==> to set the breakpoint click right mouse button select breakpoint.
=====================================================================
if num%2==0:
continue
print(num) # 1 3 5 7 9
num=1
while num<=10:
if num%2!=0:
num+=1
continue
print(num)
num+=1
==================================================================
=================================
==> collections are container which contain more than one value.
==> collection it self is an object which is grouping with more than one object.
==> data sturucture define set of rules and reg for organizing data.
1. Sequence types
2. NonSequence types
93
==> sequence types are : list,tuple,str,range,bytes,byte_array
==> iterables which allows to iterate/read more than one value or item.
sequence type
============
Q: What is sequence?
==> index based allows to read and write in seq or random order.
list
===
1. without type.
94
[] ==> empty list
2. with type
eg:
===
l1=[]
l2=list()
print(type(l1))
print(type(l2))
eg:
===
l1=[10,20,30,40,50] # homogenious
l2=[10,1.5,1+2j,True,'python'] # hetrogenious
print(l1)
print(l2)
l3=[]
l4=list()
print(l3)
print(l4)
==> this index can be +ve or -ve. +ve index start 0 and -ve index start at -1.
==> this index is used to read data from left to right or right to left.
20-06-2020
20/06/2020
95
==========
1. using index
2. iterator
3. for loop
4. slicing
Using index
==========
Q: What is index?
==> index is an integer value which is used to identify each value or location within list.
syntax:
list-name[index]
eg :
# index==> 0 1 2 3
student_info=[101,'naresh','python',5000.0]
# index=> -4 -3 -2 -1
print(student_info[0])
print(student_info[1])
print(student_info[2])
print(student_info[3])
print(student_info[-1])
96
print(student_info[-2])
print(student_info[-3])
print(student_info[-4])
Eg:
# 0 1 2 3 45 6 7 8 9
list1=[10,20,30,40,50,60,70,80,90,100]
# -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(list1[index],end=' ')
print()
print(list1[index],end=' ')
print()
print(list1[index],end=' ')
print()
print(list1[index],end=' ')
======================================================================
product_list=['keyboard','mouse','monitor','disk']
print(product_list)
if index<4:
if index==0:
97
print("Keyboard price 1000")
elif index==1:
elif index==2:
elif index==3:
else:
print("invalid index")
===================================================================
course_list=['python','java','oracle','c']
price_list=[3000,2000,1000,500]
print(course_list)
index=int(input("enter index"))
print(course_list[index],price_list[index])
else:
print("invalid index")
============================================================
iterator
======
syntax:
iter(iterable)
next()
====
98
==> it is a predefined function, which is used read value return by iterator.
syntax:
next(iterator)
list1=[10,20,30,40,50,60,70,80,90,100]
it=iter(list1)
value1=next(it)
value2=next(it)
value3=next(it)
print(value1,value2,value3)
print(value,end=' ')
=================================================================
for loop
======
syntax:
statement-1
statement-2
list1=[10,20,30,40,50,60]
print(value,end=' ')
total=0
total=total+value
print()
print("Total is ",total)
print("Avg is ",total/len(list1))
99
22-06-2020
22/6/2020
=========
slicing
=====
1. slice operator
2. slice type
slice operator:
syntax:
list-name[startindex:endindex:step]
list-name[startindex::]
list-name[:endindex:]
list-name[::step]
list-name[::]
list-name[:]
eg:
list1=[10,20,30,40,50,60,70,80,90,100]
print(list1)
print(list2)
print(list3)
print(list4)
100
list5=list1[:] # startindex=0 endinex=endoflist step=1
print(list5)
print(list6)
print(list7)
print(list8)
eg:
list1=[10,20,30,40,50,60,70,80,90,100]
print(list1)
list3=list1[::1]
print(list3)
eg:
list1=[10,20,30,40,50,60,70,80,90,100]
print(list1)
print(list2)
print(list3)
print(list4)
eg:
# find output
list1=[10,20,30,40,50,60,70,80,90,100]
print(list1)
list2=list1[::-1]
101
print(list2) # 100 90 80 ...10
list3=list1[::1] # 10...100
print(list3)
list4=list1[-1::-1]
print(list4) # 100 to 10
list5=list1[5:]
print(list5) # 60 to 100
list6=list1[5::-1]
print(list6) # 60 to 10
list7=list1[9:5] # step=1
list8=list1[-5:-1] # step= 1
print(list8)
list9=list1[-5:-1:-1] # step=-1
print(list9) # emptylist
eg:
sales_2019=
[4000,7000,8000,9000,10000,12000,30000,6000,10000,56000,12000,40000]
q_sales=sales_2019[0:3]
h_sales=sales_2019[0:6]
print(sales_2019)
print(q_sales)
print(h_sales)
l3_sales=sales_2019[9:]
print(l3_sales)
l6_sales=sales_2019[6:]
print(l6_sales)
eg:
sales_2019=
102
[4000,7000,8000,9000,10000,12000,30000,6000,10000,56000,12000,40000]
q_sales=sales_2019[-len(sales_2019):-(len(sales_2019)-3)]
h_sales=sales_2019[-len(sales_2019):-(len(sales_2019)-6)]
print(sales_2019)
print(q_sales)
print(h_sales)
l3_sales=sales_2019[-1:-4:-1]
print(l3_sales)
l6_sales=sales_2019[-1:-7:-1]
print(l6_sales)
slice() type
=========
==> this object can be applied to more than one sequence or list.
syntax:
l1=[1,2,3,4,5]
l2=['a','b','c','d','e']
l3=[1+2j,1+3j,4+5j,2+3j,3+1j]
l4=[1.5,2.5,3.5,5.5,6.5]
s=slice(0,2)
print(l1)
print(l2)
print(l3)
print(l4)
l5=l1[s]
103
l6=l2[s]
l7=l3[s]
l8=l4[s]
print(l5)
print(l6)
print(l7)
print(l8)
23/06/2020
==========
======================
eg:
list1=[10,20,30]
print(list1)
list1.append(40)
list1.append(50)
list1.append(60)
print(list1)
eg:
list1=list()
list1.append(10)
list1.append(20)
list1.append(30)
print(list1)
eg:
# write a program to read the scores of n plyers and calculate total score
104
scores_list=[]
for i in range(n): # 0 1 2
score=int(input("enter score")) # 50 60 70
total=0 # 180
total+=score
print(scores_list)
print(total)
eg:
name=input("Enter name")
marks_list=[]
for i in range(n):
sub=int(input("enter marks"))
marks_list.append(sub)
total=sum(marks_list)
avg=total/n
min_marks=min(marks_list)
max_marks=max(marks_list)
print(f'Name {name}')
print(f'Marks {marks_list}')
print(f'Total {total}')
print(f'Avg {avg}')
if avg>=90:
105
print("Grade A")
print("Grade B")
print("Grade C")
elif avg<60:
print("Grade D")
syntax: extend(iterable)
eg:
list1=[10,20,30,40,50]
print(list1)
list2=[60,70,80]
print(list2)
list1.extend(list2)
print(list1)
print(list1)
list1=[10,20,30,40,50]
print(list1)
list1.insert(0,60) # [60,10,20,30,40,50]
print(list1)
list1.insert(3,100)
print(list1)
list1.insert(-1,200)
print(list1) # [60,10,20,100,30,40,200,50]
106
print(list1)
list-name[len(list-name):len(list-name)]=[list of values]
list1=[10,20,30,40,50]
list1[len(list1):len(list1)]=[60,70,80]
print(list1) # [10,20,30,40,50,60,70,80]
list-name[startindex:endindex]=[list-of values]
list1=[10,20,30,40,50]
list1[0:0]=[60,70,80]
list1[1:1]=[100,200]
eg:
list1=list(range(10,110,10))
print(list1)
list1[len(list1):len(list1)]=[110,120,130]
print(list1)
list1[0:0]=[1,2]
print(list1)
print(list1)
replacing value:
eg:
list1=[10,20,30,40,50]
print(list1)
list1[0]=100
print(list1)
107
list1[1:4]=[200,300,400]
print(list1)
eg:
list1=list(range(1,21))
print(list1)
list1[1:len(list1)+1:2]=[0,0,0,0,0,0,0,0,0,0]
print(list1)
Q: How to add more than one value into list? ==> extend,slicing
Q: How to insert more than one value into list? ==> slicing
===================
3. remove(value)
4. pop()
5. clear()
list1=[10,20,30,40,50]
list1=[10,20,30,40,50]
print(list1)
print(list1) # [10,30,40,50]
del list1[-2]
print(list1) # [10,30,50]
list2=list(range(10,110,10))
108
print(list2)
del list2[0:2]
print(list2)
del list2[0:5]
print(list2)
del list2[:]
print(list2)
list3=list(range(10,110,10))
print(list3)
del list3[0::2]
print(list3)
list4=list(range(10,110,10))
print(list4)
del list4[-1:-4:-1]
print(list4)
remove method
=============
remove(value)
list_strings=['java','python','oracle','ML','DS']
print(list_strings)
list_strings.remove('java')
print(list_strings)
list_strings.remove('oracle')
print(list_strings)
109
24/06/2020
using list as a stack
================
==> stack is data structure, which follows LIFO (Last In First Out), the element which is
applications of stack:
1. evaluation of expressions
3. compiler designing
4. memory management
Ex:
Stack Operations
1. Push
2. Pop
3. Display
4. Exit
stack=[]
while True:
print("****Stack Operations****")
print("1. Push")
print("2. Pop")
print("3. Display")
110
print("4. Exit")
if opt==1:
stack.append(ele)
elif opt==2:
if len(stack)==0:
print("Stack Empty")
else:
ele=stack.pop()
elif opt==3:
if len(stack)==0:
print("stack is empty")
else:
print(stack)
elif opt==4:
break
==================
==> Queue data structure followed FIFO (First in First Out). The element or item
Application of Queue:
1. CPU Scheduling
1. Adding
111
2. Removing
3. Displaying
4. Exit
queue=list()
while True:
print("****Queue Operations****")
print("1. Adding")
print("2. Removing")
print("3. View")
print("4. Exit")
if opt==1:
ele=int(input("enter element"))
queue.append(ele)
elif opt==2:
if len(queue)==0:
print("Queue is empty")
else:
del queue[0]
elif opt==3:
print(queue)
elif opt==4:
break
list1=[10,20,30,40,50]
print(list1)
112
list1.clear()
print(list1)
list2=[10,20,30,40,50]
print(list2)
list2[:]=[]
print(list2)
==> s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and
before index j)
1. shallow copy
2. deep copy
list1=[[10,20,30]]
list2=list1.copy()
print(list1)
print(list2)
list1[0][0]=100
print(list1)
print(list2)
list2[0][0]=200
print(list1)
print(list2)
113
# ************* Deep Copy *************
list3=[[10,20,30]]
list4=copy.deepcopy(list3)
print(list3)
print(list4)
list3[0][0]=100
print(list3)
print(list4)
26&27/06/2020
=============
Searching element
================
1. in
2. not in
eg:
list1=[10,20,30,40,50,60,70,80,90,100]
b=20 in list1
b=200 in list1:
eg:
114
# write a program to read n names and search given name exists or not
names_list=[]
for i in range(n):
name=input("enter name")
names_list.append(name)
print(names_list)
b=name in names_list
if b==True:
print(name,"exists")
else:
print(name,"not exists")
eg:
list1=list(range(10,110,10))
print(list1)
max_value=max(list1)
min_value=min(list1)
total_value=len(list1)
print("max value",max_value)
print("min value",min_value)
print("total values",total_value)
list2=[1,1,2,2,3,3,4,5,6,7,8]
print(list2)
c1=list2.count(1)
c2=list2.count(3)
c3=list2.count(5)
print(c1,c2,c3)
sorting
115
=======
This method sorts the list in place, using only < comparisons between items.
eg:
list1=[5,2,1,6,3,4]
print(list1)
list1.sort()
print(list1)
list1.sort(reverse=True)
print(list1)
list_names=['aaa','bbb','ccc','AAA','BBB','CCC']
print(list_names)
list_names.sort()
print(list_names)
list_names.sort(reverse=True)
print(list_names)
list2=['c','a','b','A','C','B']
print(list2)
list2.sort()
print(list2)
list2.sort(key=str.upper)
print(list2)
list_names=['RAMA','rama','AMAR','amar','vamsee','VAMSEE']
print(list_names)
list_names.sort()
print(list_names)
list_names.sort(key=str.upper)
print(list_names)
list_names.sort(key=str.lower)
116
print(list_names)
================================================================
# [10,20,30,40,50,60,70,80]
# 60,70,80
list1=list()
for i in range(n):
list1.append(num)
print(list1)
list1.sort(reverse=True)
print(list1)
max_list=list1[:n]
print(max_list)
==================================================================
list1=[10,20,30]
list2=[10,20,30]
list3=list1+list2
print(list1)
print(list2)
print(list3)
python_list=['rajesh','suresh','kishore']
java_list=['naresh','ramesh','kiran']
python_java_list=python_list+java_list
print(python_list)
117
print(java_list)
print(python_java_list)
list1=[1,2,3,4,5]
list2=list1*2
print(list1)
print(list2)
list1=[1,2,3,4,5]
list2=[1,2,3,4,5]
list3=[1,2,3,4,6]
b1=list1==list2
b2=list1==list3
print(b1,b2)
list4=[2,1,4,5,3]
b3=list1==list4
print(b3)
==,>,<,>=,<=
list1=[10,20,30,40,50]
list2=[1,2,3,4,5]
b1=list1>list2
print(b1)
b2=list2<list1
print(b2)
b3=list1<list2
print(b3)
b4=list2>list1
118
print(b4)
l1=[10,20,30]
l2=[5,10,40]
b5=l1>l2
print(b5)
l3=[40,10,20]
b6=l1>l3
print(b6)
nested list
=========
==> in nested list the items/elements are accessed using row and column index.
scores=[40,50,60,70,80]
scores=[[10,20,30,40,50],[60,70,80,90,10 ]]
marks=[30,40,50,60,70]
eg:
matrix1=[[10,20,30],[40,50,60]]
# using index
for i in range(0,2): # 0 1
for j in range(0,3): # 0 1 2
print(matrix1[i][j],end=' ')
print()
print(col,end=' ')
print()
119
list1=matrix1[0]
list2=matrix1[1]
print(list1)
print(list2)
print(list1[0],list1[1],list1[2])
print(list2[0],list2[1],list2[2])
======================================================================
matrix1=[]
row1=[10,20,30]
row2=[40,50,60]
matrix1.append(row1)
matrix1.append(row2)
print(matrix1)
print(col,end=' ')
print()
row=[1,2,3]
matrix1.insert(0,row)
print(matrix1)
matrix1.insert(2,row)
print(matrix1)
matrix1[0].append(4)
print(matrix1)
matrix1[0].insert(0,100)
print(matrix1)
del matrix1[0]
print(matrix1)
del matrix1[0][0]
120
print(matrix1)
matrix1[0][0]=50
print(matrix1)
=====================================================================
matrix=[]
for i in range(m):
row=[]
for j in range(n):
value=int(input("enter value"))
row.append(value)
matrix.append(row)
print("Matrix is")
print(value,end=' ')
print()
=================================================================
matrix1=[]
for i in range(2):
row=[]
for j in range(2):
ele=int(input("enter element"))
row.append(ele)
matrix1.append(row)
121
for col in row:
print(col,end=' ')
print()
for i in range(2):
for j in range(2):
print(matrix1[i][j],end=' ')
print()
===================================================================
matrix1=[[1,2],[3,4]]
matrix2=[[3,4],[5,6]]
matrix3=[]
for i in range(2):
row=[]
for j in range(2):
value=matrix1[i][j]+matrix2[i][j]
row.append(value)
matrix3.append(row)
print(matrix1)
print(matrix2)
print(matrix3)
==================================================================
4. write a program to read 3x3 matrix and display upper triangle and lower triangle
122
29/06/2020
============
list comprehension
================
For constructing a list, a set or a dictionary Python provides special syntax called
•they are computed via a set of looping and filtering instructions, called a
comprehension
==> list1=[1**2,2**2,3**2,4**2,5**2,.....10**2]
list1=[]
list1.append(n**2)
1. list comprehension
2. set comprehension
3. dictionary comprehension
4. generator comprehension
list comprehension
================
syntax-2: Filtering
123
[expression for variable in iterable if test]
eg:
print(list1)
print(list2)
print(list3)
print(list4)
print(list5)
===========================================================
import random
list1=[random.randint(1,100)for i in range(100)]
print(list1)
r=random.randrange(1,101,2)
print(r)
=================================================
124
import random
otplist=[str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint
print(otplist)
print(list1)
=====================================================
list1=[1,2,3,4,5,6,7,8,9,10]
print(list1)
print(list2)
list3=[[10,20],[30,40],[50,60]]
print(list3)
print(list4)
============================================================
30/06/2020
==========
syntax-2: Filtering
==> for loop each time it read one value from iterable and test condition, if
condition/test is True it eval expression and return the result of eval expression into
list.
125
list1=[1,2,3,4,5,6,7,8,9,10]
list2=[]
if value%3==0:
list2.append(value)
list1=[1,2,3,4,5,6,7,8,9,10]
===================================================================
print(list1)
print(list2)
str1="python"
print(list3)
list4=['naresh','suresh','rajesh','kishore','amar']
print(list4)
print(list5)
print(list6)
list7=['naresh','NARESH','suresh','SURESH','kishore','KISHORE']
126
list9=[name for name in list7 if name.islower()]
print(list7)
print(list8)
print(list9)
list10=['65','abc','a123','89','xyz']
print(list10)
print(list11)
list12=["ramesh","kishore","rajesh","raja","rama","naresh"]
print(list12)
print(list13)
===================================================================
matrix1=[[1,2],[3,4]]
matrix2=[[4,5],[6,7]]
without comprehension
matrix3=[]
for i in range(2): 0 1
row=[]
for j in range(2): 0 1
row.append(matrix1[i][j]+matrix2[i][j])
matrix3.append(row)
list1=[10,20,30,40,50]
127
print(list1)
print(list2)
print(list3)
list1=['a','b','c']
list2=['x','y','z']
print(list1)
print(list2)
print(list3)
==================================================================
students_list=[[101,'naresh','A'],[102,'ramesh','A'],[103,'kishore','B'],[104,'raja','C']]
print(students_list)
print(students_listA)
print(students_listB)
print(students_listC)
===================================================================
product_list=[[1,'orange','fruits'],[2,'mango','fruits'],[3,'mouse','ele'],
[4,'keyboard','ele']]
print("1. Fruits")
print("2. Electronics")
opt=int(input("Enter option"))
if opt==1:
128
print(fruits_list)
elif opt==2:
print(ele_list)
====================================================================
01-07-2020
1/7/2020
========
eg:
list1=[1,2,3]
list2=[4,5,6]
print(list1)
print(list2)
print(list3)
eg:
list1=[[1,2,3],[4,5,6],[7,8,9]]
print(list1)
list2=[]
129
list2.append(value)
print(list2)
print(list3)
eg:
list1=[[1,2,3],[4,5,6],[7,8,9]]
print(list1)
print(list2)
print(list3)
eg:
students_list=[['naresh','suresh'],['kishore','rajesh'],['amar','rama']]
print(students_list)
print(students)
print(students_length)
print(students_list1)
tuple
====
130
list tuple
after creation.
==> singleton tuple is created using (value,) ==> a tuple which contain one value
x=(10) ==>expression
eg:
t1=(10,20,30,40)
t2=100,200,300
print(t1)
print(t2)
print(type(t1))
print(type(t2))
t3=1000,
print(t3)
t4=(2000,)
print(t4)
print(type(t3))
131
print(type(t4))
eg:
courses=('c','c++','java','python') # packing
print(type(courses))
print(courses)
c1,c2,c3,c4=courses # unpacking
print(c1,c2,c3,c4)
eg:
print(x,y,z)
t1=(10,20,30,40,50)
a,b,c,d,e=t1
a,b,c=100,200,300,400,500 # error
print(a,b,c)
eg:
t1=(10,'java',5000.0,1+2j,True)
print(t1)
t2=(10,20,30,40,50)
print(t2)
eg:
list1=[10,20,30,40,50]
print(list1)
list1[0]=100
132
print(list1)
t1=(10,20,30,40,50)
print(t1)
eg:
list1=[10,20,30]
print(list1)
list1.append(40)
print(list1)
t1=(10,20,30)
print(t1)
print(t1)
eg:
t1=(10,20,30,40,50)
print(t1[0],t1[1],t1[2],t1[3],t1[4])
for i in range(5): # 0 1 2 3 4
print(t1[i])
print(value)
i=iter(t1)
print(next(i))
print(next(i))
print(next(i))
t2=t1[:]
print(t2)
t3=t1[::-1]
print(t3)
133
02&03-07-2020
2&3/07/2020
===========
eg:
list1=[1,2,3]
list2=[4,5,6]
print(list1)
print(list2)
print(list3)
eg:
list1=[[1,2,3],[4,5,6],[7,8,9]]
print(list1)
list2=[]
list2.append(value)
print(list2)
print(list3)
eg:
134
list1=[[1,2,3],[4,5,6],[7,8,9]]
print(list1)
print(list2)
print(list3)
eg:
students_list=[['naresh','suresh'],['kishore','rajesh'],['amar','rama']]
print(students_list)
print(students)
print(students_length)
print(students_list1)
tuple
====
list tuple
after creation.
135
==> tuples are used to create immutable list.
==> singleton tuple is created using (value,) ==> a tuple which contain one value
x=(10) ==>expression
eg:
t1=(10,20,30,40)
t2=100,200,300
print(t1)
print(t2)
print(type(t1))
print(type(t2))
t3=1000,
print(t3)
t4=(2000,)
print(t4)
print(type(t3))
print(type(t4))
eg:
courses=('c','c++','java','python') # packing
print(type(courses))
print(courses)
c1,c2,c3,c4=courses # unpacking
print(c1,c2,c3,c4)
136
eg:
print(x,y,z)
t1=(10,20,30,40,50)
a,b,c,d,e=t1
a,b,c=100,200,300,400,500 # error
print(a,b,c)
eg:
t1=(10,'java',5000.0,1+2j,True)
print(t1)
t2=(10,20,30,40,50)
print(t2)
eg:
list1=[10,20,30,40,50]
print(list1)
list1[0]=100
print(list1)
t1=(10,20,30,40,50)
print(t1)
eg:
list1=[10,20,30]
print(list1)
list1.append(40)
137
print(list1)
t1=(10,20,30)
print(t1)
print(t1)
eg:
t1=(10,20,30,40,50)
print(t1[0],t1[1],t1[2],t1[3],t1[4])
for i in range(5): # 0 1 2 3 4
print(t1[i])
print(value)
i=iter(t1)
print(next(i))
print(next(i))
print(next(i))
t2=t1[:]
print(t2)
t3=t1[::-1]
print(t3)
=============
eg:
list1=[(10,20,30),(30,40,50)]
list1.append((60,70,80))
138
print(list1[1]) ==> (30,40,50)
list1[0].append(90) # error
list1[0][0]=100 # error
t1=(10,20,30,40,50)
list1=[10,20,30,40,50]
set
===
==> hashcode is an integer value which is used in organizing objects in hash based
data structures.
139
==> if two objects are equal according two eqaul operator, those objects hashcode
must be same.
==> the value which is used in comparing, the same is used as hash value.
==> sequences allows indexing and slicing. set is not sequence it does not allows
eg:
set3={1,'xyz',15.5,True}
print(set1)
print(set2)
print(set3)
eg:
integer_set={10,10,10,10,20,20,20,30,30,30,40,40,40}
print(integer_set)
string_set={'java','python','java','python','oracle'}
print(string_set)
bool_set={True,False,0,1}
print(bool_set)
140
bool_set={True,False,100,200,0,1}
print(bool_set)
2. using iterator
set1={10,20,30,40,50}
print(value)
set1={10,20,30,40,50}
i=iter(set1)
value1=next(i)
value2=next(i)
value3=next(i)
print(value1,value2,value3)
eg:
# write a program to count how many times each element exists in the list
list1=[10,10,20,30,40,20,30] # 210220230140
str1=''
set1=set(list1)
c=list1.count(value)
str1=str1+str(c)+str(value)
print(str1)
str2=''
list2=list(set1)
list2.sort()
141
for value in list2:
c=list1.count(value)
str2=str2+str(c)+str(value)
print(str2)
eg:
# abcabcxyz
# 2a2b2c1x1y1z
str1="abcabcxyz"
set1=set(str1)
print(set1)
list1=list(set1)
list1.sort()
str2=""
for ch in list1:
c=str1.count(ch)
str2=str2+str(c)+ch
print(str1)
print(str2)
mutable operations
================
eg:
set1=set()
for i in range(5):
ele=int(input("enter element"))
set1.add(ele)
142
print(ele)
update(*others)
eg:
set1=set()
set1.add(10)
print(set1)
set1.update((20,30))
print(set1)
set1.update([40,50,60])
print(set1)
eg:
set1=set()
set1.update([10,20],[40,50])
print(set1)
list1=[100,200]
list2=[300,400,500,100]
set1.update(list1,list2)
print(set1)
set1.update(range(1,5),range(5,10))
print(set1)
set operations
============
1. union
union(*others)
Return a new set with elements from the set and all others.
eg:
143
set1={10,20,30}
set2={40,50,60}
set3=set1.union(set2)
set4=set1|set2
print(set1)
print(set2)
print(set3)
print(set4)
s1={1,2}
s2={3,4}
s3={5,6}
s4={7,8}
s5=s1|s2|s3|s4
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
s6=(((s1.union(s2)).union(s3)).union(s4))
print(s6)
eg:
set_dept10={'ramesh','suresh','kishore'}
set_dept20={'rajesh','naresh'}
set_dept1020=set_dept10|set_dept20
print(set_dept10)
print(set_dept20)
print(set_dept1020)
intersection(*others)
144
Return a new set with elements common to the set and all others.
eg:
set1={10,20,30,40,50}
set2={10,20,30,60,70}
set3=set1.intersection(set2)
print(set1)
print(set2)
print(set3)
set3=set1&set2
print(set3)
set4={1,2,3}&{3,4,5}&{3,6,7}
print(set4)
set5={'a','b','c'}&{'a','b','d'}&{'x','y','z'}
print(set5)
4-7-2020
========
intersection(*others)
Return a new set with elements common to the set and all others.
eg:
set1={10,20,30,40,50}
set2={10,20,30,60,70}
set3=set1.intersection(set2)
print(set1)
print(set2)
print(set3)
set3=set1&set2
print(set3)
145
set4={1,2,3}&{3,4,5}&{3,6,7}
print(set4)
set5={'a','b','c'}&{'a','b','d'}&{'x','y','z'}
print(set5)
difference(*others)
Return a new set with elements in the set that are not in the others.
eg:
set1={10,20,30,40,50}
set2={10,20,30,60,70}
set3=set1.difference(set2)
print(set1)
print(set2)
print(set3)
s1={'a','b','c','d','e'}
s2={'a','b','c','f','g'}
s3=s1-s2
print(s1)
print(s2)
print(s3)
s4={1,2,3}-{1,2,4}-{5,6}
print(s4)
s5={'ramesh','naresh'}-{'suresh','naresh'}-{'kishore','suresh'}
print(s5)
eg:
java_stud={'naresh','suresh','kishore'}
python_stud={'naresh','kishore','rajesh'}
only_java=java_stud-python_stud
print(java_stud)
146
print(python_stud)
print(only_java)
only_python=python_stud-java_stud
print(only_python)
java_python_stud=java_stud&python_stud
print(java_python_stud)
psymmetric_difference(other)
set ^ other
Return a new set with elements in either the set or other but not both
eg:
set1={10,20,30,40,50}
set2={10,20,30,60,70}
set3=set1.symmetric_difference(set2)
print(set1)
print(set2)
print(set3)
s1={'a','b','c','d','e'}
s2={'a','b','x','y','z'}
s3=s1^s2
print(s1)
print(s2)
print(s3)
s4={1,2,3,4,5}^{1,2,5,6}^{6,7,8,9}
print(s4)
intersection_update(*others)
Update the set, keeping only elements found in it and all others
set1={1,2,3,4,5}
set2={1,2,3,6,7}
147
print(set1)
print(set2)
set1.intersection_update(set2)
print(set1)
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3=s1.intersection(s2)
print(s1)
print(s2)
print(s3)
==> difference_update(*others)
==> symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in both.
set1={1,2,3,4,5}
set2={1,2,3,6,7}
print(set1)
print(set2)
set1.difference_update(set2)
print(set1)
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s1=s1.difference(s2)
isdisjoint(other)
Return True if the set has no elements in common with other. Sets are disjoint if and
set1={1,2,3,4,5}
148
set2={1,2,3,6,7}
b=set1.isdisjoint(set2)
print(set1)
print(set2)
print(b)
s1={1,2,3}
s2={5,6,7}
print(s1)
print(s2)
b=s1.isdisjoint(s2)
print(b)
java_students={'naresh','suresh','kishore'}
python_students={'ramesh','rajesh'}
b=java_students.isdisjoint(python_students)
print(b)
if b==True:
else:
issubset(other)
issuperset(other)
Test whether the set is a proper subset of other, that is, set <= other and set != other.
Test whether the set is a proper superset of other, that is, set >= other and set != other
149
eg:
set1={1,2,3,4,5,6,7}
set2={1,2,3,4,5}
b=set1.issuperset(set2)
print(b)
set3={1,2,3,7,8}
b=set1.issuperset(set3)
print(b)
eg:
set1={'a','b','c','d','e'}
set2={'a','b','c'}
b1=set1<set2
print(b1)
set3={'a','b'}
b2=set3<set2
print(b2)
1. remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.
2. discard(elem)
3. pop()
Remove and return an arbitrary element from the set. Raises KeyError if the set is
empty.
4. clear()
set1={10,20,30,40,50}
set1.remove(10)
print(set1)
150
b=80 in set1
if b==True:
set1.remove(80)
else:
set1={1,2,3,4,5}
set1.discard(2)
print(set1)
set1.discard(10)
set1={10,20,30,40,50}
print(set1)
set1.pop()
print(set1)
set1.pop()
print(set1)
set1={10,20,30,40,50}
set1.clear()
print(set1)
nested sets
==========
6/7/2020
========
frozenset
========
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set
must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not
specified, a new empty set is returned.
frozenset is immutable.
frozenset([iterable])
151
eg:
print(frozenset1)
print(type(frozenset1))
frozenset2=frozenset(range(10,110,10))
print(frozenset2)
frozenset3=frozenset([10,20,30,40,50])
frozenset4=frozenset("PYTHON")
print(frozenset3)
print(frozenset4)
frozenset2.remove(10) # error
set1={frozenset([1,2,3]),frozenset([10,20,30]),frozenset(['a','b','c'])}
print(set1)
for s in set1:
print(s)
for value in s:
print(value)
eg:
emp_set={frozenset({101,'naresh',6000}),frozenset({102,'suresh',7000})}
print(emp_set)
print(emp)
print(value)
dict or dictionary
==============
152
==> in map data is organized as key and value pair.
==> A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is
currently only one standard mapping type, the dictionary.
==> A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values
containing lists, dictionaries or other mutable types may not be used as keys.
eg:
d1={}
print(d1)
print(type(d1))
print(d2)
print(type(d2))
d3={1:100,2:200}
print(d3)
print(type(d3))
print(d4)
print(type(d4))
d5=dict([(1,10),(2,20),(3,30),(4,40),(5,50)])
153
print(type(d5))
print(d5)
zip()
====
zip(*iterables)
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument
sequences or iterables.
z=zip(range(1,5),range(10,50,10))
print(z)
list1=list(z)
print(list1)
z=zip(range(1,5),range(10,50,10),range(50,100,10))
list1=list(z)
print(list1)
eg:
dict1=dict(zip(range(1,5),range(10,50,10)))
print(dict1)
list1=['a','b','c','d']
list2=[10,20,30,40]
dict2=dict(zip(list1,list2))
print(dict2)
list3=['a','b']
list4=[10,20,30,40,50]
dict4=dict(zip(list3,list4))
print(dict4)
list5=['a','b','c','d']
list6=[1,2]
dict5=dict(zip(list5,list6))
154
print(dict5)
eg:
dict1={1:10,2:20,3:30}
print(dict1)
dict1={1:10,1:20,1:30,1:40,1:50}
print(dict1)
dict1={1:[10,20,30],2:[40,50,60],3:[60,70,80]}
print(dict1)
dict2={1:{10,20,30},2:{40,50,60},3:{60,70,80}}
print(dict2)
dict1={(1,2):10}
print(dict1)
print(type(dict1))
dict2={(1,2):[10,20]}
print(dict2)
7/7/2020
How to read content of dictionary?
1. using key
3. using iterator
a. items
b. keys
c. values
using key:
155
syntax: dict-name[key]
eg:
courses={'java':2000,'python':4000,'C':2000}
print(courses)
fee1=courses['java']
fee2=courses['python']
fee3=courses['C']
print(fee1,fee2,fee3)
dict1={1:'one',2:'two',3:'three'}
print(dict1)
b=key in dict1
if b==True:
print(dict1[key])
else:
eg:
student={1:['naresh','MCA'],2:['suresh','BCA'],3:['kishore','BTECH']}
print(student)
rno=int(input("Enter rollno"))
b=rno in student
if b==True:
l=student[rno]
print(rno,l)
else:
156
2. using for loop
dict1={1:'one'}
dict2={'one':1}
dict3={True:1}
print(dict1)
print(dict2)
print(dict3)
dict4={1.5:'base'}
print(dict4)
statements
eg:
dict1={'a':'apple','b':'ball','c':'cat','d':'dog'}
print(key,dict1[key])
sales_dict1={2005:10000,2006:20000,2007:15000}
print(year,sales_dict1[year])
3. using iterator
players_dict={'dhoni':200,'rahul':100,'virat':50}
print(players_dict)
i=iter(players_dict)
p1=next(i)
print(p1,players_dict[p1])
157
p2=next(i)
print(p2,players_dict[p2])
p3=next(i)
print(p3,players_dict[p3])
a. keys()
b. values()
c. items()
Eg:
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
keyview=dict1.keys()
valueview=dict1.values()
itemsview=dict1.items()
print(keyview)
print(valueview)
print(itemsview)
key_list=list(keyview)
value_list=list(valueview)
items_list=list(itemsview)
print(key_list)
print(value_list)
print(items_list)
eg:
dict1={1:10,2:20,3:30,4:40,5:50}
158
print(key,value)
mutable operations:
1. dictionary[key]=value
eg:
dict1={}
dict1[1]=100
dict1[2]=200
dict1[3]=300
dict1[4]=400
dict1[5]=500
print(dict1)
dict1[1]=10
eg:
sales={}
for i in range(n):
sales[name]=amt
print(name,amt)
2. update
159
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys.
dict1={}
dict1.update([(1,10),(2,20),(3,30)])
print(dict1)
dict1.update([(1,100)])
print(dict1)
dict1.update({1:'one',2:'two',3:'three',4:'four',5:'five'})
print(dict1)
dict2={}
dict2.update(zip([1,2,3,4,5],[10,20,30,40,50]))
print(dict2)
del dictionary-name[key]
eg:
cart={}
while True:
print("****Shoping Cart*****")
print("5. Exit")
if opt==1:
pname=input("ProductName :")
qty=int(input("Qty:"))
cart[pname]=qty
print("Product Added..")
160
elif opt==2:
pname=input("ProductName :")
b=pname in cart
if b==True:
qty=int(input("Qty: "))
cart[pname]=qty
print("Product updated...")
else:
print("Invalid ProductName")
elif opt==3:
b=pname in cart
if b==True:
del cart[pname]
print("Product Deleted...")
else:
elif opt==4:
print(pname,qty)
elif opt==5:
break
8&9/7/2020
==========
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
l=list(dict1)
print(l)
161
for key in dict1:
print(key)
===============================================================
stud={101:['naresh','python'],102:['suresh','java']}
print(stud)
c=len(stud)
print(c)
==============================================================
dict1={4:40,2:20,5:50,1:10,3:30}
print(dict1)
l=sorted(dict1) # 1 2 3 4 5
dict2={}
for key in l:
print(key,dict1[key])
print(dict2)
=====================================================================================
======
dict1={1:200,2:100,3:50,4:250,5:90}
list1=list(dict1.items())
for i in range(len(list1)):
for j in range(len(list1)-1):
if list1[j][1]>list1[j+1][1]:
t=list1[j]
list1[j]=list1[j+1]
list1[j+1]=t
dict2=dict(list1)
162
print(dict1)
print(dict2)
=====================================================================================
===========
dict1={1:['abc',4],2:['xyz',2],3:['pqr',5],4:['mno',1]}
list1=list(dict1.items())
for i in range(len(dict1)):
for j in range(len(dict1)-1):
if list1[j][1][1]>list1[j+1][1][1]:
t=list1[j]
list1[j]=list1[j+1]
list1[j+1]=t
dict2=dict(list1)
print(dict1)
print(dict2)
=====================================================================================
============
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
value=dict1.pop(4)
print(value)
print(dict1)
key,value=dict1.popitem()
print(key,value)
print(dict1)
=====================================================================================
=============
list1=['a','b','c','d']
list2=['apple','ball','cat','dog']
163
dict1={key:value for key,value in zip(list1,list2)}
print(dict1)
=====================================================================================
=============
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
print(dict2)
=====================================================================================
============
list(d)
eg:
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
l=list(dict1)
print(l)
print(key)
len(d)
sorted(iterable)
dict1={4:40,2:20,5:50,1:10,3:30}
print(dict1)
l=sorted(dict1) # 1 2 3 4 5
dict2={}
for key in l:
164
print(key,dict1[key])
print(dict2)
dictionary comprhension
====================
eg:
list1=['a','b','c','d']
list2=['apple','ball','cat','dog']
print(dict1)
eg:
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
print(dict2)
eg:
sales={2015:40000,2016:30000,2017:50000,2018:80000,2019:40000}
print(sales)
print(sales1)
print(sales2)
165
print(dict1)
eg:
dict1={1:[1,2,3,4,5],2:[4,5,6,7,8],3:[8,9,3,7]}
dict2={}
l=[]
for n in value:
if n%2==0:
l.append(n)
dict2[key]=l
print(dict1)
print(dict2)
print(dict3)
eg:
print(dict1)
nested dictionaries
================
syntax:
{key:{dictionary},key:{dictionary},key:{dictionary},..}
emp_records={'emp1':{'id':101,'name':'naresh','sal':5000},
'emp2':{'id':102,'name':'suresh','sal':6000}}
sales={2019:{'jan':40000,'feb':50000,'mar':60000},
2020:{'jan':20000,'feb':30000}}
166
print(emp_records)
print(sales)
print(emp_records['emp1'])
for e in emp_records:
print(emp_records[e])
print(sales[year])
print(sales[2019]['jan'])
print(emp_records['emp1']['sal'])
eg:
sales={2019:{'jan':40000,'feb':50000,'mar':60000,'apr':20000},
2020:{'jan':20000,'feb':30000}}
print(sales)
print(sales2)
2. it is index based collection, where reading and writing is done using index.
2. it is key based collection where reading and writing is done using key.
3. it allows slicing.
4. it allows duplicates.
167
4. it does not allows duplicates.
strings
======
==> string is a collection of characters, these characters can be alphabets,digits or special characters.
10/7/2020
=========
strings
======
special characters.
168
''' ''' , """ """
eg:
str1="PYTHON"
str2='PYTHON'
print(str1)
print(str2)
str3="'PYTHON'"
str4='"PYTHON"'
print(str3)
print(str4)
str5='\'PYTHON\''
str6="\"PYTHON\""
print(str5)
print(str6)
str7="""PYTHON
PROGRAMMING
LANGUAGE"""
str8='''PYTHON
PROGRAMMING
LANGUAGE'''
print(str7)
print(str8)
str9='PYTHON\nPROGRAMMING\nLANGUAGE'
str10="PYTHON\nPROGRAMMING\nLANGUAGE"
print(str9)
169
print(str10)
str9='''"PYTHON"
"PROGRAMMING"
"LANGAUGE"'''
print(str9)
str10="""'PYTHON'
'LANGUAGE'
"""
print(str10)
eg:
str1=''
str2=str()
str3=str(100)
str4=str(1.5)
str5=str(1+2j)
str6=str(True)
print(str1,str2,str3,str4,str5,str6)
=====================
==> indexing allows to only one element or value or character from string
==> slicing allows to read more than one character from string.
eg:
c=0
170
for ch in str1: # string is iterable which allows to read one character
print(ch)
c+=1
l=len(str1)
eg:
import random
print(str1[i])
i=1
while i<len(str1):
n=random.randint(0,len(str1))
print(str1[n])
i+=1
eg:
import random
str1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n=random.randint(0,25)
print(str1[n])
eg:
import random
str1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
str2="0123456789"
str3="$*%"
171
password=''
for i in range(4):
n=random.randint(0,25)
password=password+str1[n]
for i in range(2):
n=random.randint(0,9)
password=password+str2[n]
n=random.randint(0,2)
password=password+str3[n]
print(password)
slicing ==> allows to read more than one value or character from string.
1. slice operator
2. slice method
str1="PROGRAMMING"
str2=str1[:]
str3=str1[::]
print(str1)
print(str2)
print(str3)
str4=str1[-1::-1]
print(str4)
str5=str1[len(str1)-1::-1]
print(str5)
str6=str1[::-1]
print(str6)
str7=str1[::2]
print(str7)
methods of string
172
===============
1. isalpha()
2. isdigit()
3. isupper()
4. islower()
5. istitle()
6. isalnum()
eg:
name=input("Enter name")
b=name.isalpha()
if b==True:
print(name,"Hello")
else:
eg:
name=input("Enter Name")
username=input("Enter UserName")
b1=name.isalpha()
b2=username.isalnum()
if b1==True:
if b2==True:
else:
print("Invlid username")
else:
print("invalid name")
eg:
173
n=input("Enter any number")
b=n.isdigit()
print(b)
eg:
str1="abc" # lowercase
str2="ABC" # uppercase
str3="Abc" # titlecase
b1=str1.isupper()
b2=str1.islower()
b3=str1.istitle()
print(b1,b2,b3) # False,True,False
b4=str2.isupper() # True
b5=str2.islower() # False
b6=str2.istitle() # False
print(b4,b5,b6)
b7=str3.isupper() # False
b8=str3.islower() # False
b9=str3.istitle() # True
print(b7,b8,b9)
======================
=> maketranslate()
174
11/7/2020
=========
==========================
=> maketranslate()
eg:
str1="python"
str2="PYTHON"
str3="oracle"
str4=str1.upper()
str5=str2.lower()
str6=str3.title()
print(str1,str2,str3)
print(str4,str5,str6)
list1=['naresh','suresh','rajesh','kishore']
print(list1)
print(list2)
print(list3)
print(list4)
list5=['a','b','c','d','A','B','C','z','D','p','Q']
175
list7=[s for s in list5 if s.islower()]
print(list5)
print(list6)
print(list7)
list8=['ab','bc','dc','12','pq123','p123*']
print(list8)
print(list9)
print(list10)
=======================
"java"
maketranslate:
==============
maketranslate(src,dest)
table=str.marktranslate("aeiou","*+&%$")
str1="java"
str2=str1.translate(table)
eg:
str1="programming"
table=str.maketrans("aeiou","12345")
str2=str1.translate(table)
print(str1)
print(str2)
176
split methods:
=============
1. split
2. rsplit
3. partition
4. rpartition
5. splitlines
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is
given, at most maxsplit splits are done. If maxsplit is not specified or -1, then there is
eg:
str1="a,b,c,d,e,f"
print(str1)
l1=str1.split(",")
print(l1)
l2=str1.split(",",2)
print(l2)
l3=str1.split(",",3)
print(l3)
eg:
str1="ab*cd*de"
l=str1.split("*")
print(l)
str2="ab cd de"
l1=str2.split(" ")
print(l1)
l2=str2.split(" ",1)
print(l2)
177
eg:
names=name.split(" ")
print(name)
print(names)
str.rsplit(sep=None, maxsplit=- 1)
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is
given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or
eg:
s1="1,2,3,4,5,6,7,8,9,10"
print(s1)
l1=s1.split(",")
l2=s1.rsplit(",")
print(l1)
print(l2)
l3=s1.split(",",3)
print(l3)
l4=s1.rsplit(",",3)
print(l4)
s2='a,b,c,d,e,f,g,h,j,k'
l5=s2.split(",")
l6=s2.rsplit(",")
print(l5)
print(l6)
l7=s2.split(',',4)
l8=s2.rsplit(',',4)
print(l7)
print(l8)
178
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not
str1="python\nprogramming\nlangauage"
l1=str1.splitlines()
print(l1)
l2=str1.splitlines(True)
print(l2)
eg:
str1="python\nlanguage\vis\reasy\n"
l1=str1.splitlines()
print(l1)
str2='''python
programming
language'''
print(str2)
l2=str2.splitlines()
print(l2)
str.partition(sep)
Split the string at the first occurrence of sep, and return a 3-tuple containing the part
before the separator, the separator itself, and the part after the separator. If the
separator is not found, return a 3-tuple containing the string itself, followed by two
empty strings.
"a:b,c:d,e".partition(",") ==>('a:b',',','c:d,e')
"abcde".partition("c")==>('ab','c','de')
13/7/2020
==========
179
trimming/strip methods:
=======================
1. str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars argument is a
string specifying the set of characters to be removed. If omitted or None, the chars
argument defaults to removing whitespace. The chars argument is not a prefix; rather,
2. str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars argument is a
string specifying the set of characters to be removed. If omitted or None, the chars
argument defaults to removing whitespace. The chars argument is not a suffix; rather,
3.str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The
or None, the chars argument defaults to removing whitespace. The chars argument is
not a prefix or suffix; rather, all combinations of its values are stripped:
eg:
str1=" nit"
print(len(str1)) # 5
b=str1=="nit"
print(b) # False
str2=str1.lstrip() # "nit"
print(len(str2)) # 3
b=str2=="nit"
print(b)
eg:
str1="***nit"
print(str1)
180
str2=str1.lstrip("*")
print(str2)
str3="ababcabcnit"
print(str3)
str4=str3.lstrip("ab")
print(str4)
eg:
str1="nit "
print(len(str1))
str2=str1.rstrip()
print(len(str2))
print(str1)
print(str2)
eg:
str1="nit***"
str2=str1.rstrip("*")
print(str1)
print(str2)
str3="nit.$&*&*."
str4=str3.rstrip(".*&")
print(str3)
print(str4)
str5="nitabcabcabc"
str6=str5.rstrip("bc")
print(str5)
print(str6)
eg:
str1=input("any string")
print(str1)
181
print(len(str1))
str2=str1.rstrip()
print(str2)
print(len(str2))
eg:
print(str1)
print(len(str1))
str2=str1.strip()
print(str2)
print(len(str2))
str3="***nit****"
print(str3)
print(str3.strip("*"))
str4="ababcnitababc"
str5=str4.strip("abc")
print(str4)
print(str5)
eg:
str1="www.gmail.com"
str2=str1.lstrip("w.")
print(str1)
print(str2)
str3=str2.rstrip(".com")
print(str3)
str4=str1.strip("w.com")
print(str4)
===========================
182
1. str.endswith(suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix
can also be a tuple of suffixes to look for. With optional start, test beginning at that
Return the lowest index in the string where substring sub is found within the slice s
[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return the highest index in the string where substring sub is found, such that sub is
contained within s[start:end]. Optional arguments start and end are interpreted as in
Return True if string starts with the prefix, otherwise return False. prefix can also be a
tuple of prefixes to look for. With optional start, test string beginning at that position.
eg:
names_list=['naresh','kishore','ramesh','suresh','pavan']
print(names_list)
print(names_list1)
print(names_list2)
eg:
str1="programming"
b=str1.endswith('g')
print(b)
b=str1.endswith('m',0,7) # progrmm
print(b)
183
eg:
names_list=['amar','pavan','krishna','naresh','rajesh','om','ramesh','rama']
print(names_list)
print(names_list1)
print(names_list2)
print(names_list3)
eg:
str1="naresh technologies"
index=str1.find("te")
print(index)
index1=str2.find('g')
index2=str2.rfind('g')
print(index1)
print(index2)
Return a copy of the string with all occurrences of substring old replaced by new. If
the optional argument count is given, only the first count occurrences are replaced.
str2=str1.replace("java","python")
print(str1)
print(str2)
str3=str1.replace("java","oracle",1)
print(str3)
str4="aaaabbbbbccccdddd"
str5=str4.replace('a','A')
184
print(str5)
str6=str4.replace('a','A',2)
print(str6)
justification methods:
======================
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the specified
fillchar (default is an ASCII space). The original string is returned if width is less than
or equal to len(s).
str.ljust(width[, fillchar])
Return the string left justified in a string of length width. Padding is done using the
specified fillchar (default is an ASCII space). The original string is returned if width is
str.rjust(width[, fillchar])
Return the string right justified in a string of length width. Padding is done using the
specified fillchar (default is an ASCII space). The original string is returned if width is
eg:
name1="naresh"
name2=name1.center(20)
print(name1)
print(name2)
name3=name1.center(20,'*')
print(name3)
name4=name1.center(30)
print(name4)
eg:
list_names=['naresh','kishore','rama','suresh','kiran']
185
print(name.center(20,'*'))
name1="naresh"
name2=name1.ljust(20)
print(name1)
print(name2)
name3=name1.ljust(20,'*')
print(name3)
name_list=['naresh','suresh','rama','kishore','kiran']
print(name.ljust(20,"*"))
eg:
name1="naresh"
name2=name1.rjust(20)
print(name1)
print(name2)
name3=name1.rjust(20,'*')
print(name3)
list_names=['naresh','suresh','kishore','raja','kiran']
print(name.rjust(20,'*'),name.ljust(20,'*'),name.center(20,'*'))
14&15-7-2020
============
functions
========
paradigm or approches.
1. unstructured programming
186
2. procedural programming
Q: What is a function?
==> a function is self contained block, which contain set of instructions inorder to
1. Modularity
2. Reusability
3. Efficiency
==> Modularity: dividing programming instructions according two operation into small
==> Reusability : functions allows to write code once and use number of time. this
==> Efficiency : function reduce the size of program, which incr efficiency.
Types of functions
===============
1. predefined functions
predefined functions: the existing functions are called predefined functions. the
eg: input(),print(),int(),float(),.....
userdefined functions.
syntax:
def <function-name>([arguments]):
'''document string'''
statement-1
187
statement-2
statement-3
===================
Q: What is PyCharm?
https://www.jetbrains.com/pycharm/download/#section=windows
Creating project?
==> Select Project ==> New ==> File ==> Python File
eg:
def sayHello():
print("Hello")
sayHello() # invoking
sayHello() # invoking
sayHello() # invoking
eg:
188
print("inside fun1")
print("inside fun2")
eg:
def drawLine():
for i in range(40):
print("*",end="")
print()
drawLine()
print("PYTHON")
drawLine()
print("LANGUAGE")
drawLine()
=================
eg:
eg:
189
def fun1():
print("inside fun1")
def fun2():
print("inside fun2")
main()
==> main is userdefined function which include all the operations done by program.
module/program. This module or program by default python assign one name called
__main__.
local variables
============
==> the variables declared inside function are called local variables.
==> the scope these variables within function, these variables cannot accessed
def fun1():
print(a)
def fun2():
print(a) # error
def main():
fun1()
fun2()
main()
==> the memory for local variables allocated when function is called and deallocated
190
eg:
def fun1():
a=10
print(a)
def main():
fun1()
main()
eg:
def add():
print(c)
def sub():
print(c)
def main():
add()
sub()
main()
global variables
==============
==>
16&17-7-2020
=============
191
global variables
==============
==> The variables which are declared outside the function or at the top of the
==>These variables can be used inside more than one function of same program or
another program.
==> global variables are shared by one or more than one function.
eg:
def fun1():
print(a)
print(b)
def fun2():
print(a)
print(b)
def main():
fun1()
fun2()
print(a,b)
main()
eg:
list1=[1,2,3,4,5,6,7,8,9,10]
def sqr():
for n in list1:
print(n**2,end='')
def cube():
for n in list1:
print(n**3,end='')
192
def main():
sqr()
print()
cube()
main()
eg:
def fun1():
print(a)
print(b)
def main():
fun1()
main()
eg:
def fun1():
print(a)
print(b)
def fun2():
print(a)
def main():
fun1()
fun2()
main()
=================================
193
The global statement is a declaration which holds for the entire current code block. It
impossible to assign to a global variable without global, although free variables may
global <variable1>,<variable2>,...
eg:
a=100
def fun1():
global a
a=300
print(a)
def fun2():
print(a)
def main():
fun1()
fun2()
main()
eg:
base=0
height=0
def readData():
global base,height
base=float(input("Enter Base"))
height=float(input("Enter height"))
def findArea():
area=0.5*base*height
def main():
readData()
194
findArea()
main()
eg:
a=100
def fun1():
print(a) # 200
global a
a=400 # error
def main():
fun1()
main()
====================
==> python allows you to write function with arguments and without arguments.
==> arguments are local variables which receive values from another function.
==> if function required input from another function, that function is defined with
arguments.
2. default arguments
4. keyword arguments
pass
fun1(100) # invalid
195
pass
fun2(100)
def add(a,b):
....
.....
required arguments
================
eg:
print(a,b)
def main():
fun1(100,200)
fun1(100) # error
fun1() # error
main()
eg:
for i in range(width):
print(symbol,end='')
print()
def main():
drawLine('*',20)
print("Python Programming")
drawLine('#',30)
print("Scripting Language")
drawLine('%',20)
main()
eg:
196
def findMax(a,b,c):
print(a)
elif b>c:
print(b)
print(c)
else:
print("equal")
def main():
findMax(100,200,300)
findMax(200,300,100)
findMax(300,100,200)
findMax(100,100,100)
main()
eg:
def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def multiply(a,b):
print(a*b)
def division(a,b):
print(a/b)
def main():
while True:
print("Calculator")
197
print("1.Add")
print("2.Sub")
print("3.Multiply")
print("4.Division")
print("5.Exit")
opt=int(input("enter option"))
if opt==1:
add(n1,n2)
if opt==2:
sub(n1,n2)
if opt==3:
multiply(n1,n2)
if opt==4:
division(n1,n2)
if opt==5:
break
main()
variable.
==> in python variables are reference variables, which does not values it hold
address.
eg:
def toUpper(l):
for i in range(len(l)):
l[i]=l[i].upper()
def main():
198
namesList=['naresh','suresh','rajesh','kishore']
print(namesList)
toUpper(namesList)
print(namesList)
main()
eg:
def swap(a,b):
a,b=b,a
def main():
x=100
y=200
print(x,y)
swap(x,y)
print(x,y)
main()
eg:
def fun1(a,b):
print(a,b)
def main():
fun1(b=100,a=200)
fun1(300,400)
fun1(b=1000,a=2000)
fun1(a=3000,b=4000)
main()
return keyword
============
199
==> function receive values and perform operation and return result of that operation
eg:
def average(a,b):
r=(a+b)/2
return r
def main():
c=average(100,200)
print(a,b,c)
main()
eg:
def toUppercase(s):
s1=''
for i in range(len(s)):
ch=chr(ord(s[i])-32)
s1=s1+ch
else:
s1=s1+s[i]
return s1
def main():
str1="naresh"
str2=toUppercase(str1)
print(str1)
print(str2)
main()
200
eg:
def countWords(s):
c=1
c=c+s.count(' ')
return c
def main():
str1='python'
c1=countWords(str1)
c2=countWords(str2)
print(c1)
print(c2)
main()
eg:
def countVowels(s):
c=0
for ch in s:
if ch in "aeiouAEIOU":
c+=1
return c
def countSpecial(s):
c=0
for ch in s:
pass
else:
c+=1
return c
def countDigits(s):
201
c=0
for ch in s:
c+=1
return c
def main():
count1=countVowels("python program")
count2=countDigits("python 3.8")
print(count1)
print(count2)
print(count3)
main()
18-7-2020
==========
================================
==> an argument given value at the time of defining the function is called default
arguemt.
==> this argument does not required value at the time of calling the function.
def function-name(arg1,arg2,arg3,arg4=<value>,..):
statement-1
statement-2
statement-3
==> arg4 is called default argument. it does not required to send value at the time of
calling function.
eg:
202
def fun1(a,b,c): # function with required arguemnts
print(a,b,c)
print(a,b,c)
def main():
fun1(1,2,3)
fun2(10,20)
fun2(100,200,300)
main()
eg:
def drawLine(ch='*',width=30):
for i in range(width):
print(ch,end='')
print()
def main():
drawLine()
print("Python Programming")
drawLine('$')
print("Good Language")
drawLine('%',25)
print("Naresh Technologies")
drawLine(width=40)
main()
eg:
def fun1(a=100,b):
print(a,b)
def main():
fun1(200,300)
main()
203
Expl: the above script or code gives an error becoz
eg:
def simple_intrest(amt,t,rate=1.5):
si=amt*t*rate/100
return si
def main():
res1=simple_intrest(5000,12)
res2=simple_intrest(6000,12,2.0)
print(res1)
print(res2)
main()
eg:
def sortList(l,order='ascending'):
if order=='ascending':
for i in range(len(l)):
for j in range(len(l)-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
elif order=="descending":
for i in range(len(l)):
for j in range(len(l)-1):
if l[j]<l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
def main():
list1=[10,50,20,40,30]
print(list1)
sortList(list1)
print(list1)
204
sortList(list1,'descending')
print(list1)
main()
eg:
def fun1(a,b=100,c):
print(a,b,c)
def main():
fun1(100,200,300)
main()
eg:
def fun1(a,b=10,c=20,d=30):
print(a,b,c,d,)
def main():
fun1(100)
fun1(200,300,)
fun1(400,500,600)
fun1(700,800,900,1000)
fun1(b=1,a=2)
fun1(c=10,b=1,a=3)
fun1(10,d=100,c=300,)
main()
========================================================
==> an argument which receive 0 or more values is called variable length argument.
def <function-name>(req-args,def-args=value,*var-length):
statement-1
statement-2
205
statement-3
20&21-7-2020
=============
=================================================
==> an argument which receive 0 or more values is called variable length argument.
def <function-name>(req-args,def-args=value,*var-length):
statement-1
statement-2
statement-3
eg:
def fun1(*a):
print(a)
print(type(a))
print(a[0],a[1])
def main():
fun1(100,200)
main()
eg:
def maximum(*a):
if len(a)==0:
return None
elif len(a)==1:
return a[0]
else:
206
m=a[0]
for i in range(1,len(a)):
if a[i]>m:
m=a[i]
return m
def main():
res1=maximum()
res2=maximum(100)
res3=maximum(400,200,500,300)
print(res1,res2,res3)
main()
eg:
def fun1(a,*b):
print(a,b)
def main():
fun1(100)
fun1(200,300)
fun1(400,500,600,700)
fun1(1,2,3,4,5,6,7,8,9,10)
main()
eg:
def fun1(*a,*b):
print(a,b)
def main():
fun1(100,200,300)
main()
Expl: the above function display syntax error becoz a function contain only one
eg:
207
def fun1(*a,b):
print(a,b)
def main():
fun1(b=100)
fun1(10,20,30,40,b=50)
fun1(100,200,300,400,500,b=600)
main()
eg:
def vowelCount(*alpha):
c=0
if value in "aeiouAEIOU":
c+=1
return c
def main():
count1=vowelCount('a','b','c')
count2=vowelCount('a','b','c','e','o')
print(count1)
print(count2)
main()
eg:
def addNumber(*n):
s=0
for value in n:
s=s+value
return s
def main():
res1=addNumber()
res2=addNumber(100)
208
res3=addNumber(10,20,30)
print(res1)
print(res2)
print(res3)
main()
def fun1(a,b=10,*c):
print(a)
print(b)
print(c)
def main():
fun1(100)
fun1(100,200)
fun1(100,200,300,400,500)
main()
eg:
def fun1(*a,*b):
print(a,b)
def main():
print(100,200,300,400,500)
main()
Expl: the above function display error becoz a function cannot have multiple variable
length arguments.
keyword arguments
================
syntax:
209
def function-name(**kwargs):
statement-1
statement-2
eg:1
def fun1(**a):
print(a)
print(type(a))
def main():
fun1(x=100,y=200)
main()
eg:2
def drawLine(**kwargs):
keys=kwargs.keys()
listKey=list(keys)
value1=kwargs[listKey[0]]
value2=kwargs[listKey[1]]
for i in range(value2):
print(value1,end='')
print()
def main():
drawLine(char='*',width=30)
drawLine(x='$',y=40)
drawLine(line='%',size=50)
main()
eg:
def fun1(**kwargs):
print(kwargs['a'])
print(kwargs['b'])
def main():
210
fun1(a=100,b=200)
fun1(x=100,y=200) # error
main()
eg:
si=kwargs['amt']*kwargs['time']*kwargs['rate']/100
return si
def main():
res=simpleIntrest(amt=5000,time=12,rate=2.5)
print(res)
res=simpleIntrest(amt=6000,time=24,rate=1.5)
print(res)
main()
eg:
def fun1(**kwargs):
print(kwargs)
def main():
main()
eg:
print(a)
print(b)
print(c)
def main():
fun1(100)
fun1(200,300)
fun1(400,500,600,700)
211
fun1(800,900,x=1000,y=2000)
main()
eg:
def fun1(*a,b):
print(a)
print(b)
def main():
fun1(b=100)
fun1(10,20,30,b=40)
main()
Nested functions
==============
statement-1
statement-2
statement-3
statement-4
==> dividing the functionality of one function into number sub functions.
def fun1():
def main():
fun1()
212
main()
eg:
def calculator(n1,n2,opr):
def add():
return n1+n2
def sub():
return n1-n2
def multiply():
return n1*n2
def division():
return n1/n2
if opr=='+':
r=add()
return r
if opr=='-':
r=sub()
return r
if opr=='*':
r=multiply()
return r
if opr=='/':
r=division()
return r
def main():
o=input("Enter operator")
res=calculator(num1,num2,o)
print(res)
213
main()
22-07-2020
==========
eg: inner function/nested function can access local variables of outer function
def outer():
def inner():
print(x)
inner()
def main():
outer()
main()
def outer():
def inner():
x=200
print(x) # error
def main():
outer()
main()
eg:
def complexOperations(comp1,comp2,opr):
def addComplex():
return comp1+comp2
214
def subComplex():
return comp1-comp2
if opr=='+':
return addComplex()
if opr=='-':
return subComplex()
def main():
res1=complexOperations((1+2j),(2+3j),'+')
res2=complexOperations((2+3j),(1+2j),'-')
print(res1)
print(res2)
main()
eg:
def fun1():
def fun2():
print("global variable",x)
fun2()
def main():
fun1()
main()
eg:
def fun1():
215
x=100
def fun2():
print(x)
fun2()
print(x)
def main():
fun1()
main()
nonlocal
========
The nonlocal statement causes the listed identifiers to refer to previously bound
variables in the nearest enclosing scope excluding globals. This is important because
the default behavior for binding is to search the local namespace first.
nonlocal variable1,variable2,variable3,....
eg:
def fun1():
x=100
def fun2():
nonlocal x
x=300
print(x)
fun2()
print(x)
def main():
fun1()
main()
eg:
def findAreaOfTriangle():
216
base=0.0
height=0.0
def read():
nonlocal base,height
read()
area=0.5*base*height
return area
def main():
a1=findAreaOfTriangle()
print(a1)
main()
eg:
def fun1():
def fun2():
print(x)
print(y)
print(z)
fun2()
def fun3():
print(x)
def main():
print(x)
fun1()
fun3()
217
main()
eg:
def findResult():
rno=None
name=None
sub1,sub2=(0,0)
def read():
nonlocal rno,name,sub1,sub2
rno=int(input("Enter rollno"))
name=input("Enter name")
sub1=int(input("Enter subject1"))
sub2=int(input("Enter subject2"))
read()
print(f"Rollno {rno}")
print(f'Name {name}')
print(f'Subject1 {sub1}')
print(f'Subject2 {sub2}')
global res
if sub1<40 or sub2<40:
res="Fail"
else:
res="Pass"
def main():
findResult()
print(f'Result is {res}')
main()
eg:
n=100
218
def fun1():
def fun2():
global n
n=300
print(n)
fun2()
print(n)
def main():
fun1()
print(n)
main()
eg:
def fun1():
x=100
def fun2():
y=200
def fun3():
nonlocal x
x=400
print(x)
fun3()
fun2()
def main():
fun1()
main()
23/07/2020
Generators:
============
219
==> A generator is special function which does not return a single value, instead it returns iterator object
with sequence of values.
==> yield return value to the calling function, after returning it pause execution of function.
yield 10
yield 20
yield 30
def main():
g=fun1()
r=range(1,100)
value1=next(g)
value2=next(g)
print(value1)
print(value2)
value3=next(g)
print(value3)
main()
eg:
def alphagenerator():
for i in range(65,91):
yield chr(i)
def main():
alpha=alphagenerator()
value1=next(alpha)
value2=next(alpha)
value3=next(alpha)
print(value1,value2,value3)
220
for value in alpha:
print(value,end=' ')
main()
eg:
def prime_generator(start,stop):
c=0
for i in range(1,num+1):
if num%i==0:
c+=1
if c==2:
yield num
def main():
prime=prime_generator(5,10)
print(value)
prime=prime_generator(1,100)
print(value,end=' ')
prime=prime_generator(1,20)
list1=list(prime)
print(list1)
main()
eg:
import random
def otpgenerator():
while True:
221
otp=str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,
9))
yield int(otp)
def main():
otpgen=otpgenerator()
otp1=next(otpgen)
otp2=next(otpgen)
print(otp1)
print(otp2)
for i in range(5):
otp=next(otpgen)
print(otp,end=' ')
main()
==============================
==> A closure is a function that remembers values in enclosing scopes even if they are not present
memory.
def fun1():
x=100
print(x)
return fun2
def main():
f2=fun1()
f2()
==> closure function is useful when outer function receive the value and inner function perform
differenet operations using that value.
24&25-7-2020
Closure Function or Closures
222
=============================
==> A closure is a function that remembers values in enclosing scopes even if they are not present
memory.
def fun1():
x=100
print(x)
return fun2
def main():
f2=fun1()
f2()
eg:
def readNum(num):
def pow(p):
r=num**p
return r
return pow
def main():
c1=readNum(5)
res1=c1(2)
res2=c1(3)
res3=c1(4)
print(res1,res2,res3)
main()
eg:
def draw_line(ch):
def draw(width):
for i in range(width):
print(ch,end='')
223
print()
return draw
def main():
draw1=draw_line('*')
draw1(30)
draw1(20)
draw1(40)
main()
==> closure function is useful when outer function receive the value and inner function perform
differenet operations using that value.
============================
==> decorator function receive input as a function and return new function with additional functionality.
def box(f):
def draw():
print("****************")
f()
print("****************")
return draw
def fun1():
print("Hello")
def fun2():
print("Bye")
def main():
fun1()
224
fun2()
''' nfun1=box(fun1)
nfun2=box(fun2)
nfun1()
nfun2()'''
main()
eg:
def smart_division(fun):
def div(n1,n2):
if n2==0:
return
else:
r=fun(n1,n2)
return r
return div
@smart_division
def division(n1,n2):
n3=n1/n2
return n3
def main():
res1=division(5,2)
print(res1)
res2=division(5,0)
main()
=========================================
225
==> a function decorator is calling another function decorator, which is called decorator chaining.
def draw_stars(f):
def draw():
print("*"*30)
f()
print("*"*30)
return draw
def draw_doller(f):
def draw():
print("$"*30)
f()
print("$"*30)
return draw
@draw_doller
@draw_stars
def fun1():
print("Hello")
def main():
fun1()
main()
eg:
def A(f):
def d():
print("A")
f()
return d
def B(f):
def d():
print("B")
226
f()
return d
@B
@A
def fun1():
print("Hello")
def main():
fun1()
main()
27/7/2020
=========
==================================
==> Lambda functions are used as higher order function, a function which receive a
function as an argument.
syntax:
lambda <arguments>:expression
def main():
a()
a()
main()
def main():
227
a=lambda x,y:x if x>y else y
max1=a(100,200)
max2=a(400,300)
print(max1)
print(max2)
main()
def main():
a=lambda x,y:x+y
res1=a(100,200)
res2=a(300,400)
print(res1)
print(res2)
main()
def calculator(f):
x=100
y=200
r=f(x,y)
return r
def main():
res1=calculator(lambda n1,n2:n1+n2)
res2=calculator(lambda n1,n2:n1-n2)
res3=calculator(lambda n1,n2:n1*n2)
print(res1)
print(res2)
print(res3)
main()
filter()
228
=====
filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true.
If function is None, the identity function is assumed, that is, all elements of iterable
def main():
list1=list(range(1,25))
print(list1)
i=filter(lambda n:n%2==0,list1)
list2=list(i)
print(list2)
i=filter(lambda n:n%2!=0,list1)
list3=list(i)
print(list3)
main()
===================================================================
def main():
listOfNames=['naresh','NARESH','suresh','RAJESH','KISHORE']
i1=filter(lambda x:x.isupper(),listOfNames)
i2=filter(lambda x:x.islower(),listOfNames)
i3=filter(lambda x:x.startswith(('n','s')),listOfNames)
i4=filter(lambda x:x.endswith(('H','E')),listOfNames)
print(list(i1))
print(list(i2))
print(list(i3))
print(list(i4))
main()
229
==================================================================
def main():
list1=[True,False,False,True,False,True]
list2=list(filter(None,list1))
print(list1)
print(list2)
list3=[1,2,3,4,5,True,False,True,False,1.5]
list4=list(filter(None,list3))
print(list3)
print(list4)
list5=['a','b','c','d','e','f','True','False']
list6=list(filter(None,list5))
print(list5)
print(list6)
main()
====================================================================
Return an iterator that applies function to every item of iterable, yielding the results. If additional
iterable arguments are passed, function must take that many arguments and is applied to the items
from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is
exhausted.
60 ====> A
80 ====> A+
50 ====> B
70 ====> A
90 ====> A+
28/7/2020
==========
230
eg:
def main():
list1=[1,2,3,4,5,6,7,8,9,10]
i1=map(lambda x:x*x,list1)
i2=map(lambda x:x**3,list1)
print(list1)
print(list(i1))
print(list(i2))
main()
eg:
def main():
list1=["a","b","c","d","e"]
i=map(list,list1)
print(list1)
print(list(i))
i1=map(str.upper,list1)
print(list(i1))
list2=[1,2,3,4,5,6,7,8,9]
list3=list(map(str,list2))
print(list2)
print(list3)
list4=["123","456","678"]
list5=list(map(int,list4))
print(list4)
print(list5)
main()
eg:
def main():
list1=[1,2,3,4,5]
231
list2=[5,6,7,8,9]
list3=list(map(lambda x,y:x+y,list1,list2))
print(list1)
print(list2)
print(list3)
main()
eg:
def main():
list1=['a','b','c','d']
list2=['m','n','o']
list3=list(map(lambda x,y:x+y,list1,list2))
print(list1)
print(list2)
print(list3)
main()
reduce()
========
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce
the iterable to a single value
eg:
import functools
def main():
list1=[10,20,30,40,50,60,70,80,90,100]
s=functools.reduce(lambda x,y:x+y,list1)
print(s)
print(m)
232
print(n)
main()
eg:
import functools
def main():
list1=['a','b','c','d','e','f']
s=functools.reduce(lambda x,y:x+y,list1)
print(s)
print(list1)
main()
==========================================
eg:
def fun1():
print("inside fun1")
def main():
fun1()
main()
1. init statement
2. condition
3. updation
eg:
233
def printNum(n):
if n>0:
printNum(n-1)
print(n)
def main():
printNum(3)
main()
eg:
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
def main():
res=factorial(num)
print("Factorial is ",res)
main()
29/7/2020
=========
====================
Q: What is module?
==> Any file which is saved with ext .py is called module.
1. predefined modules
234
2. userdefined modules
Q.predefined modules?
==> the modules provided by python are called predefined modules (OR) existing
==> the modules which are created by programmer or user are called userdefined modules.
==> dividing the functions of an application into number of programs and each program is called one
module.
==> the content of one module can be used inside another module, which is called reusability.
1. executable modules
2. reusable modules
==> executable modules consist of executable statements. this module is given a name python
runtime(PVM). the name of that module is __main__.
eg:
def fun1():
print("inside fun1")
def fun2():
print("inside fun2")
def fun3():
print("inside fun3")
print(__name__)
=====================================================
import statement
==============
235
==> import statement allows to use the content of one
import module-name
module1.py
==========
def power(n,p):
return n**p
def maxTwo(n1,n2):
if n1>n2:
return n1
else:
return n2
module2.py
==========
import module1
def main():
res1=module1.power(5,2)
res2=module1.maxTwo(100,200)
print("Result1",res1)
print("Result2",res2)
main()
=================================
==> the module name can be imported with another name with the help of the
following syntax.
eg;
236
import module1 as m1
def main():
res1=m1.power(5,2)
res2=m1.maxTwo(100,200)
print(res1)
print(res2)
main()
==========================
==> we can import the content of module inside current module using the following syntax.
30&31/7/2020
=============
=============================================
import statement
==============
==> import statement allows to use the content of one module inside another module.
import module-name
module1.py
==========
def power(n,p):
return n**p
237
def maxTwo(n1,n2):
if n1>n2:
return n1
else:
return n2
module2.py
==========
import module1
def main():
res1=module1.power(5,2)
res2=module1.maxTwo(100,200)
print("Result1",res1)
print("Result2",res2)
main()
============================
==> the module name can be imported with another name with the help of the following syntax.
eg;
import module1 as m1
def main():
res1=m1.power(5,2)
res2=m1.maxTwo(100,200)
print(res1)
print(res2)
main()
==========================
==> we can import the content of module inside current module using the following syntax.
238
from module-name import <function-name>,<variable-name>,..
============================================
==> we need to check the following condition inorder import executable module as reusable module.
if __name__=='__main__':
main()
module4.py
=========
def fun1():
print("inside function1")
def fun2():
print("inside function2")
def fun3():
print("inside function3")
def main():
fun1()
fun2()
fun3()
if __name__=='__main__':
main()
module5.py
==========
import module4
def fun4():
print("inside function4")
def main():
module4.fun1()
fun4()
239
main()
package
=======
Q: What is package?
==> This file does not contain any code. this file indicates that it
is a package.
pip command
============
==> pip is used to install python packages from the python package index and other.
Q: What PyPI?
Open terminal
============
>pip
240
Q: What is virtual environment?
==> python virtual environment which consist of python software and installed packages(local
repository).
==> python virtual envrironment is used to develop and execute python applications.
==> first step install virtualenv module/tool. which is used to work with virtual environment.
virtualenv <evnrionment-name>
(OR)
2. virtualenv <envrionment-name>
==> on creation virtualenvironment, it include python interpreter and default lib and other tools
3. c:\>c:\myenv\Scripts\activate
c:\>c:\myenv\Scripts\deactivate
1/8/2020
========
==> Object oriented programming is not a language. It is a concept which define set of
Q: What is object?
241
==> Every object is having properties and behaviour.
Q: What is class?
C: Python
1. Encapsulation
2. Polymorphism
3. Inheritance
4. class
5. object
Encapsulation:
=============
==> Encapsulation is a process of grouping data and operations which operate on that
Adv:
Data Hiding : preventing data access from unrelated operations is called data hiding.
242
Adv object oriented programming:
2. Reusability
3. Security
4. Extensibility
5. Efficiency
=================
and functions.
syntax of class
============
class <class-name>:
variables
methods/member function
variables
========
3/8/2020
========
=================================
==> object properties are defined using instance variables/object level variables.
243
==> these variables are created in different ways.
2. setattr() function
3. properties class
__init__(self):
==> this constructor method, this method is called automatically at the time of creating
object.
==> any method which suffix and prefix with __ is called magic method and these
==> using self, we can create or access object level variables/instance variables.
==> __init__(self) contain the operations which has to be performed at the time of
creating.
eg:
class A:
def __init__(self):
print("object created")
def main():
a1=A()
a2=A()
a3=A()
print(a1)
print(a2)
print(a3)
main()
244
Note: in the place of self we can use any other name.
eg:
class Student:
def __init__(self):
self.rno=0
self.name=""
def main():
stud1=Student()
stud2=Student()
stud1.rno=101
stud1.name="naresh"
stud2.rno=102
stud2.name="suresh"
print(stud1.rno,stud1.name)
print(stud2.rno,stud2.name)
main()
eg:
class A:
def __init__(self):
self.x=100
self.y=200
def main():
print(A.x,A.y)
main()
Expl: the above code display syntax error becoz object level variables accessed with
object name not with class name and cannot accessed without creating object.
245
==> by default the variables are public.
eg: class A:
def __init__(self):
self.x=100
self.y=200
class B:
def __init__(self):
self.__x=100
self.__y=200
def main():
obj1=A()
print(obj1.x,obj1.y)
obj2=B()
print(obj2.__x,obj2.__y)
main()
class Student:
def __init__(self):
self.__rno=101
self.__name="naresh"
self.__course="python"
def main():
stud1=Student()
print(stud1.__rno)
246
print(stud1.__name)
print(stud1.__course)
list1=list()
list1.append()
main()
4/8/2020
========
class Student:
def __init__(self):
self.__rno=101
self.__name="naresh"
self.__course="python"
def main():
stud1=Student()
print(stud1.__rno)
print(stud1.__name)
print(stud1.__course)
list1=list()
list1.append()
main()
methods
========
247
==> methods written inside class are 3 types.
3. static methods
================================
==> these methods are used to perform operation on object level variables.
==> any method defined inside class with first argument 'self' is called object level
==> this method access object level variables using 'self' argument inorder to
syntax:
def <method-name>(self,arg1,arg2,arg3,...):
statement-1
statement-2
==> this method is called with object and cannot called without creating object.
ex:
class Student:
def __init__(self):
self.__rno=101
self.__name="naresh"
self.__course="python"
def printStudent(self):
print(self.__rno)
print(self.__name)
print(self.__course)
def main():
stud1=Student()
248
# print(stud1.__rno)
# print(stud1.__name)
# print(stud1.__course)
stud1.printStudent()
main()
eg:
class Triangle:
def __init__(self):
self.__base=0.0
self.__height=0.0
def setBase(self,b):
self.__base=b
def setHeight(self,h):
self.__height=h
def findArea(self):
return self.__base*self.__height*0.5
def main():
t1=Triangle()
t1.setBase(1.5)
t1.setHeight(2.5)
t1_area=t1.findArea()
t2=Triangle()
t2.setBase(2.5)
t2.setHeight(3.5)
t2_area=t2.findArea()
main()
eg:
249
class Matrix:
def __init__(self):
self.__m=[[0,0],[0,0]]
def printMatrix(self):
print(col,end=' ')
print()
def readMatrix(self):
for i in range(2):
for j in range(2):
self.__m[i][j]=int(input("Enter element"))
def main():
m1=Matrix()
m1.printMatrix()
m2=Matrix()
m2.printMatrix()
m1.readMatrix()
m1.printMatrix()
m2.readMatrix()
m2.printMatrix()
main()
eg:
class Stack:
def __init__(self):
self.__s=[]
self.__top=-1
def push(self,value):
self.__s.append(value)
250
print("element pushed")
self.__top=self.__top+1
def pop(self):
if self.__top==-1:
print("Stack is empty")
else:
value=self.__s[self.__top]
del self.__s[self.__top]
self.__top=self.__top-1
return value
def main():
stack1=Stack()
stack1.push(100)
stack1.push(200)
stack1.push(300)
e1=stack1.pop()
e2=stack1.pop()
print(e1)
print(e2)
main()
eg:
class Calculator:
def __init__(self,n1,n2):
self.__num1=n1
self.__num2=n2
def add(self):
return self.__num1+self.__num2
def sub(self):
251
return self.__num1-self.__num2
def multiply(self):
return self.__num1*self.__num2
def main():
calc1=Calculator(100,200)
print(calc1.add())
print(calc1.sub())
print(calc1.multiply())
main()
3. write a class to represent marks details of student and calculate total,avg and result
5/8/2020
=========
class Circle:
def __init__(self):
self.__r=0.0
self.__r=r
def findArea(self):
return 3.147*self.__r*self.__r
def main():
circle1=Circle()
circle1.setR(1.2)
area1=circle1.findArea()
main()
252
1. Write a class to find area rectangle
class Rectangle:
def __init__(self):
self.__l=0.0
self.__b=0.0
def setL(self,l):
self.__l=l
def setB(self,b):
self.__b=b
def findArea(self):
return self.__l*self.__b
def main():
rect1=Rectangle()
rect1.setL(1.5)
rect1.setB(2.5)
area1=rect1.findArea()
main()
3. write a class to represent marks details of student and calculate total,avg and
result
class StudentMarks:
def __init__(self):
self.__rno=0
self.__name=""
self.__sub1=0
self.__sub2=0
def readData(self):
self.__rno=int(input("Enter rollno"))
self.__name=input("Enter name")
253
self.__sub1=int(input("Enter subject1"))
self.__sub2=int(input("Enter subject2"))
def printData(self):
print(f'Rollno {self.__rno}')
print(f'Name {self.__name}')
print(f'Subject1 {self.__sub1}')
print(f'Subject2 {self.__sub2}')
print(f'Total {self.__sub1+self.__sub2}')
print(f'Avg {(self.__sub1+self.__sub2)/2}')
if self.__sub1<40 or self.__sub2<40:
print("Result is Fail")
else:
print("Result is Pass")
def main():
studentList=[]
for i in range(n):
s=StudentMarks()
s.readData()
studentList.append(s)
stud.printData()
main()
class Player:
def __init__(self):
self.__name=""
self.__score=0
def setName(self,n):
254
self.__name=n
def setScore(self,s):
self.__score=s
def getName(self):
return self.__name
def getScore(self):
return self.__score
def main():
playerList=list()
for i in range(n):
p=Player()
n=input("Enter name")
s=int(input("Enter score"))
p.setName(n)
p.setScore(s)
playerList.append(p)
tot=0
for p in playerList:
tot=tot+p.getScore()
print(f'{p.getName()}--->{p.getScore()}')
main()
6&7/8/2020
==========
=====================================
255
=================
==> the variables declared inside the class are called class level
variable.
==> this variable can be accessed with class name without creating
object.
eg:
class Account:
def __init__(self,accno,cname,bal):
def deposit(self,amt):
self.__bal=self.__bal+amt
def withdraw(self,amt):
if self.__bal-amt<Account.minBalance:
print("Insuff balance")
else:
self.__bal=self.__bal-amt
def printAccount(self):
print(f'AccountNo {self.__accno}')
print(f'CustomerName {self.__cname}')
print(f'Balance {self.__bal}')
def main():
acc1=Account(101,"suresh",50000)
acc1.printAccount()
acc1.withdraw(45000)
256
acc1.printAccount()
acc1.withdraw(2000)
acc2=Account(102,"kishore",6000)
main()
#find output
class A:
x=100
def __init__(self):
self.y=200
def main():
print(A.x) # 100
a1=A()
a2=A()
a1.x=200
a1.y=300
a2.x=400
a2.y=500
print(a1.x,a1.y)
print(a2.x,a2.y)
main()
Ouput:
200 300
400 500
==> class level variable cannot modify with object name. if we trying modify with
==> class level variable can access with object name but cannot modified.
===============
257
==> a method defined inside class with first argument as 'cls' is called class level
method.
==> this method is called with class name, without creating object.
==> inorder to declare class level method we use a decorator called @classmethod
syntax:
@classmethod
def <method-name>(cls,arg1,arg2,arg3,...):
statement-1
statement-2
statement-3
==> class level methods are used in application development for creating objects.
==> class level methods are called factory methods, these methods create object
eg:
class A:
def m1(self):
@classmethod
def m2(cls):
def main():
A.m2()
# A.m1() error
obj1=A()
obj1.m1()
main()
eg:
class Person:
258
def __init__(self,n,a):
self.name=n
self.age=a
@classmethod
def createPerson(cls,n,dob):
a=2020-dob
p=Person(n,a)
return p
def printPerson(self):
print(f'Name :{self.name}')
print(f'Age : {self.age}')
def main():
p1=Person("naresh",40)
p2=Person("suresh",30)
p3=Person.createPerson("kishore",1980)
p4=Person.createPerson("rajesh",1992)
p1.printPerson()
p2.printPerson()
p3.printPerson()
p4.printPerson()
main()
eg:
class Employee:
def __init__(self,eno,en,s,c):
self.__empno=eno
self.__ename=en
self.__salary=s
self.__comm=c
@classmethod
259
def createEmployee(cls,eno,en,s):
c=0
if s>=10000:
c=s*10/100
c=s*5/100
else:
c=s*2/100
e=cls(eno,en,s,c)
return e
def printEmployee(self):
print(f'EmployeeNo {self.__empno}')
print(f'EmployeeName {self.__ename}')
print(f'Salary {self.__salary}')
print(f'Comm {self.__comm}')
def main():
emp1=Employee(101,"naresh",5000,100)
emp2=Employee.createEmployee(102,"suresh",9000)
emp1.printEmployee()
emp2.printEmployee()
main()
static methods
============
==> a method defined inside class without first argument as 'cls' or 'self' is called
static method.
@staticmethod
def method-name(arg1,arg2,...):
260
statement1
statement2
class Math:
@staticmethod
def maxOfIntegers(n1,n2):
if n1>n2:
return n1
else:
return n2
@staticmethod
def power(n,p):
return n**p
def main():
m1=Math.maxOfIntegers(100,200)
m2=Math.power(5,2)
print("Max is ",m1)
print("Result is ",m2)
main()
8/8/2020
========
class reusability
=============
==> the content of one class can be used inside another class in
different ways.
1. composition (has-a)
2. aggregation (use-a)
3. inheritance (is-a)
261
composition(has-a)
===============
==> composition is a process of creating an object of one class inside another class.
1. one-one
2. one-many
3. many-one
4. many-many
# one-many
class Address:
def __init__(self):
self.__street=None
self.__city=None
def setStreet(self,st):
self.__street=st
def setCity(self,c):
self.__city=c
def getStreet(self):
return self.__street
def getCity(self):
return self.__city
class Person:
def __init__(self):
self.__name=None
self.add1=Address()
self.add2=Address()
def setName(self,n):
self.__name=n
def getName(self):
262
return self.__name
def main():
p1=Person()
p1.setName("naresh")
p1.add1.setStreet("S.R.Nager")
p1.add1.setCity("Hyd")
p1.add2.setStreet("M.G.Road")
p1.add2.setCity("Hyd")
print(p1.getName())
print(p1.add1.getStreet())
print(p1.add1.getCity())
print(p1.add2.getStreet())
print(p1.add2.getCity())
main()
# one - one
class Dept:
def __init__(self):
self.__deptno=None
self.__dname=None
def setDeptno(self,dno):
self.__deptno=dno
def setDname(self,dn):
self.__dname=dn
def getDeptno(self):
return self.__deptno
def getDeptName(self):
return self.__dname
class Employee:
def __init__(self):
263
self.__ename=None
self.dept=Dept()
def setName(self,n):
self.__ename=n
def getName(self):
return self.__ename
def main():
emp1=Employee()
emp1.setName("naresh")
emp1.dept.setDeptno(10)
emp1.dept.setDname("Sales")
print(emp1.getName())
print(emp1.dept.getDeptno())
print(emp1.dept.getDeptName())
main()
# many to one
class College:
def __init__(self):
self.__came=None
def setCname(self,cn):
self.__cname=cn
def getCname(self):
return self.__cname
class Student:
def __init__(self):
self.__rno=None
self.__name=None
def setRno(self,rno):
264
self.__rno=rno
def getRno(self):
return self.__rno
def setName(self,name):
self.__name=name
def getName(self):
return self.__name
def main():
Student.college.setCname("NIT")
stud1=Student()
stud2=Student()
stud1.setRno(101)
stud1.setName("naresh")
stud2.setRno(102)
stud2.setName("Suresh")
print(stud1.getRno())
print(stud1.getName())
print(stud2.getRno())
print(stud2.getName())
print(Student.college.getCname())
main()
Aggregation(Use-A)
================
In composition,
265
class Engine:
def start(self):
print("Car start...")
def stop(self):
print("Car stop..")
class Car:
def __init__(self,e):
self.__e=e
def carStart(self):
self.__e.start()
def carStop(self):
self.__e.stop()
def main():
engine1=Engine()
car1=Car(engine1)
car1.carStart()
car1.carStop()
main()
=======================================================
class BSNLSim:
def call(self):
class AirtelSim:
def call(self):
class Mobile:
def __init__(self):
self.__sim=None
def insert(self,s):
266
self.__sim=s
def call(self):
self.__sim.call()
def main():
mobile1=Mobile()
bsnlsim1=BSNLSim()
mobile1.insert(bsnlsim1)
mobile1.call()
airtelsim1=AirtelSim()
mobile1.insert(airtelsim1)
mobile1.call()
main()
10/8/2020
Inheritance(IS_A)
===============
==> Inheritance allows to define class that inherit all the methods and properties from
another class.
==> Inheritance allows to define new class from an existing class. new class is called
==> Inheritance model is called is-relationship. It means that derived class inherit
syntax
======
prperties
methods
267
==>python support the following types inheritances.
3. multiple inheritance
4. hierarchical inheritance
5. hybrid inheritance
def m1(self):
print("m1 of A")
def m2(self):
print("m2 of B")
def main():
objb=B()
objb.m1()
objb.m2()
main()
class A:
def __init__(self):
self.x=100
class B(A):
def __init__(self):
self.y=200
super().__init__()
def main():
268
objb=B()
print(objb.x)
print(objb.y)
main()
==> if constructor method of base class is not called in derived class the properties of
# hierarchical Inheritance
class Employee:
def __init__(self):
self.__empid=None
self.__ename=None
def setEmpid(self,eid):
self.__empid=eid
def setEname(self,en):
self.__ename=en
def getEmpid(self):
return self.__empid
def getEname(self):
return self.__ename
class SalriedEmployee(Employee):
def __init__(self):
self.__salary=None
super().__init__()
def setSalary(self,sal):
self.__salary=sal
269
def getSalary(self):
return self.__salary
class CommEmployee(Employee):
def __init__(self):
self.__comm=None
super().__init__()
def setComm(self,com):
self.__comm=com
def getComm(self):
return self.__comm
def main():
emp1=SalriedEmployee()
emp2=CommEmployee()
emp1.setEmpid(101)
emp1.setEname("rajesh")
emp1.setSalary(50000)
emp2.setEmpid(102)
emp2.setEname("kishore")
emp2.setComm(500)
print(f'{emp1.getEmpid()},{emp1.getEname()},{emp1.getSalary()}')
print(f'{emp2.getEmpid()},{emp2.getEname()},{emp2.getComm()}')
main()
class Alpha:
def __init__(self,x):
self.__x=x
def getX(self):
return self.__x
class Beta(Alpha):
270
def __init__(self,x,y):
self.__y=y
super().__init__(x)
def getY(self):
return self.__y
def main():
b1=Beta(100,200)
print(b1.getX())
print(b1.getY())
main()
# private members of base class are not accessible inside derived class
class A:
def __init__(self):
self.__x=100
class B(A):
def __init__(self):
super().__init__()
def printX(self):
print(self.__x)
def main():
b1=B()
b1.printX()
main()
# public members of base class/super class are accessible inside derived class
class A:
def __init__(self):
self.x=100
class B(A):
def __init__(self):
271
super().__init__()
def printX(self):
print(self.x)
def main():
b1=B()
b1.printX()
main()
=====================================================================
class Account:
def __init__(self,accno,cname,bal):
self.__accno=accno
self.__cname=cname
self.__bal=bal
def getAccno(self):
return self.__accno
def getCname(self):
return self.__cname
def getBal(self):
return self.__bal
def setBal(self,b):
self.__bal=b
class SavingAccount(Account):
def __init__(self,accno,cname,bal,cheqfac):
self.__cheqfac=cheqfac
super().__init__(accno,cname,bal)
def deposit(self,tamt):
b=self.getBal()
b=b+tamt
self.setBal(b)
272
def getCheqFac(self):
return self.__cheqfac
def main():
acc1=SavingAccount(101,"ramesh",6000,True)
print(acc1.getAccno(),acc1.getCname(),acc1.getBal(),acc1.getCheqFac())
acc1.deposit(2000)
main()
Multiple inheritance
================
==> if a class derive more than one base class ,it is called multiple inheritance.
==> in multiple inheritance derived class must call the constructor of base classes.
class A:
def __init__(self):
self.x=100
class B:
def __init__(self):
self.y=200
def __init__(self):
self.z=300
A.__init__(self)
B.__init__(self)
def main():
objc=C()
print(objc.x)
print(objc.y)
print(objc.z)
273
main()
=======================
class A:
def __init__(self,x):
self.__x=x
def getX(self):
return self.__x
class B:
def __init__(self,y):
self.__y=y
def getY(self):
return self.__y
class C(A,B):
def __init__(self,x,y,z):
self.__z=z
A.__init__(self,x)
B.__init__(self,y)
def getZ(self):
return self.__z
def main():
objc=C(100,200,300)
print(objc.getX(),objc.getY(),objc.getZ())
main()
11/8/2020
Hierarchical Inheritance
====================
class Person:
274
def __init__(self,id,name):
self.__id=id
self.__name=name
def getId(self):
return self.__id
def getName(self):
return self.__name
class Student(Person):
def __init__(self,id,name,course):
self.__course=course
super().__init__(id,name)
def setCourse(self,course):
self.__course=course
def getCourse(self):
return self.__course
class Teacher(Person):
def __init__(self,id,name,subject):
self.__subject=subject
super().__init__(id,name)
def getSubject(self):
return self.__subject
class AdminStaff(Person):
def __init__(self,id,name,job):
self.__job=job
super().__init__(id,name)
def getJob(self):
return self.__job
def main():
stud1=Student(101,"naresh","python")
275
t1=Teacher(102,"suresh","java")
ns=AdminStaff(103,"kishore","Acc")
print(stud1.getId(),stud1.getName(),stud1.getCourse())
print(t1.getId(),t1.getName(),t1.getSubject())
print(ns.getId(),ns.getName(),ns.getJob())
main()
protected members
=================
class A:
def __init__(self):
self.__x=100 # private
self._y=200 # protected
self.z=300 # public
class B(A):
def printY(self):
print(self._y)
def main():
obja=A()
print(obja._y)
print(obja.z)
main()
Method Overriding
===============
276
==> redefining of base class instance method or object level method within derived
==> defining method inside derived class with same name and arguments of method
==> method overriding allows to extend or modify functionality of base class method
==> if derived class wants to have different implementation of method exists in base
class Parent:
class Child(Parent):
def sleep(self):
print("child sleep")
def main():
c=Child()
================================================
class A:
def m1(self):
print("Overriden method")
class B(A):
def m1(self):
print("Overriding method")
def main():
objb=B()
277
objb.m1()
main()
==================================================
class Account:
def __init__(self):
self.__accno=None
self.__bal=None
def read(self):
self.__accno=int(input("AccountNo :"))
self.__bal=float(input("Balance :"))
def printAcc(self):
print("AccountNo :",self.__accno)
print("Balance ",self.__bal)
class CurrentAccount(Account):
def __init__(self):
self.__creditCard=None
self.__creditCard=input("Enter Yes/No")
print("CreaditCard :",self.__creditCard)
def main():
acc1=CurrentAccount()
acc1.read()
acc1.printAcc()
main()
==================================================================
object class
278
==========
12/8/2020
object class
==========
__str__() : it is method of object class this method returns type and id of object. this
method called when ever we print variable. this method is called automatically
class Student:
def __init__(self,rno,name):
self.__rno=rno
self.__name=name
return str(self.__rno)+","+self.__name
def main():
stud1=Student(101,"naresh")
print(stud1)
list1=list([10,20,30,40,50])
print(list1)
main()
==> override __str__ to return state of the object whenever print reference variable.
method, becoz of that when ever we print variables of these type, it print values not
address.
279
class Employee:
def __init__(self,eid,en):
self.empid=eid
self.ename=en
def __str__(self):
return str(self.empid)+","+self.ename
def main():
emp1=Employee(101,"suresh")
print(emp1)
list1=list()
list1.append(Employee(102,"kishore"))
list1.append(Employee(103,"naresh"))
print(list1)
e1=list1[0]
print(e1)
main()
__eq__ method
============
userdefined class.
== operator.
def main():
list1=[10,20,30,40,50]
list2=[10,20,30,40,50]
280
b=list1==list2
print(b)
print(id(list1))
print(id(list2))
main()
class Player:
def __init__(self,pn,r):
self.pname=pn
self.runs=r
if self.runs==other.runs:
return True
else:
return False
def main():
p1=Player('rahul',100)
p2=Player('rohit',100)
p3=Player('virat',60)
b=p1==p2 # p1.__eq__(p2)
print(b)
print(id(p1))
print(id(p2))
b=p1==p3 # p1.__eq__(p3)
print(b)
main()
class Alpha:
def __init__(self,x):
self.__x=x
281
def __str__(self):
return str(self.__x)
if self.__x==other.__x:
return True
else:
return False
def main():
a1=Alpha(100)
a2=Alpha(200)
a3=Alpha(100)
print(a1,a2,a3)
b1=a1==a2
b2=a1==a3
print(b1,b2)
main()
==========================
__hash__ method.
eg:
282
class A:
def __init__(self,x):
self.__x=x
def __str__(self):
return str(self.__x)
if self.__x==other.__x:
return True
else:
return False
def __hash__(self):
return self.__x
def main():
obj1=A(100)
obj2=A(200)
set1=set()
set1.add(obj1)
set1.add(obj2)
for s in set1:
print(s)
main()
eg:
class Student:
def __init__(self,rno,name):
self.__rno=rno
self.__name=name
def __str__(self):
return str(self.__rno)+","+self.__name
283
if self.__rno==other.__rno:
return True
else:
return False
def __hash__(self):
return self.__rno
def main():
studSet=set()
studSet.add(Student(101,"naresh"))
studSet.add(Student(102,"suresh"))
studSet.add(Student(101,"kishore"))
for s in studSet:
print(s)
main()
==============================
abstractmethod
=============
@abstractmethod decorator
syntax:
@abstractmethod
def <method-name>(self,arg1,arg2,arg3,..):
pass
284
==> abstract method must override in derived class.
abstract class
============
==> abstract class is a collection of abstract methods and non abstract methods.
==> if class is derived from "ABC" class, it is called abstract base class.
==> abstract class is inherited, but cannot used for creating object.
import abc
class <class-name>(abc.ABC):
variables
method
eg:
class A(ABC):
@abstractmethod
def m1(self):
pass
def main():
obja=A()
main()
==> the above code/program display error becoz we cannot create object of
eg:
class A(ABC):
@abstractmethod
285
def m1(self):
pass
def m2(self):
class B(A):
def m3(self):
print("m2 of B")
def main():
objb=B()
main()
==> the above program display error becoz the class which inherit abstract base
class must override all abstract method if not, the derived calss cannot used for
creating object.
13/8/2020
=========
==> the above program display error becoz the class which inherit abstract base class
must override all abstract method if not, the derived calss cannot used for creating
object.
class Shape(ABC):
def __init__(self):
self._dim1=None
self._dim2=None
def read(self):
self._dim1=float(input("Enter dim1"))
self._dim2=float(input("Enter dim2"))
@abstractmethod
def findArea(self):
286
pass
class Triangle(Shape):
def __init__(self):
super().__init__()
def findArea(self):
return self._dim1*self._dim2*0.5
class Rectangle(Shape):
def __init__(self):
super().__init__()
def findArea(self):
return self._dim1*self._dim2
def main():
t1=Triangle()
t1.read()
r1=Rectangle()
r1.read()
a1=t1.findArea()
a2=r1.findArea()
main()
==> Inheritance is process of grouping all the classes which share common properties
and behaviour.
duck typing
==========
==> Duck typing in computer programming is an application of the duck test— "If it
walks like a duck and it quacks like a duck, then it must be a duck"— to determine if an
==> Duck typing is a concept related to dynamic typing, where the type or the class of
287
an object is less important than the methods it defines. When you use duck typing, you
do not check types at all. Instead, you check for the presence of a given method or
attribute.
==>Python follows the EAFP (Easier to Ask Forgiveness than Permission) rather than
the LBYL (Look Before You Leap) philosophy. The Python philosophy of EAFP is
==> Loosly Coupled Code, The code which work with any
class DebitCard:
def withdraw(self):
class CreditCard:
def withdraw(self):
class EMICard:
def withdraw(self):
class SwappingMachine:
def swap(self,s):
s.withdraw()
class ATM:
def swap(self,s):
s.withdraw()
def main():
card1=DebitCard()
card2=CreditCard()
card3=EMICard()
s1=SwappingMachine()
a1=ATM()
288
s1.swap(card1)
s1.swap(card2)
s1.swap(card3)
a1.swap(card1)
a1.swap(card2)
a1.swap(card3)
main()
eg:
class AirtelSim:
def call(self):
class BsnlSim:
def call(self):
class JioSim:
def call(self):
class Mobile:
def call(self,s):
s.call()
def main():
mobile1=Mobile()
sim1=AirtelSim()
sim2=BsnlSim()
sim3=JioSim()
mobile1.call(sim1)
mobile1.call(sim2)
mobile1.call(sim3)
main()
289
mokey patching
============
runtime.
Monkey patching is a technique that allows you to alter the behavior of objects at
runtime.
14/8/2020
==========
monkey patching
=============
runtime.
Monkey patching is a technique that allows you to alter the behavior of objects at
runtime.
code at run-time.
eg:
class A:
@classmethod
def m1(cls):
print("Hello")
@classmethod
290
def m2(cls):
print("Bye")
def main():
A.m1()
A.m1()
main()
eg:
class A:
def m1(self):
print("Hello")
def m2(self):
print("Bye")
def main():
obj1=A()
obj1.m1()
obj1.m1()
main()
class Employee:
def __init__(self):
self.empno=None
self.ename=None
self.salary=None
self.comm=None
def readEmployee(self):
self.empno=int(input("Enter EmployeeNo"))
self.ename=input("Enter EmployeeName")
self.salary=float(input("Enter Salary"))
291
if self.salary>=10000:
self.comm=self.salary*10/100
self.comm=self.salary*5/100
else:
self.comm=0
def printEmployee(self):
print(self.empno,self.ename,self.salary,self.comm)
#patch
def readEmployeeNew(self):
self.empno=int(input("Enter employeeno"))
self.ename=input("Enter employeename")
self.salary=float(input("Enter salary"))
if self.salary>=20000:
self.comm=self.salary*10/1000
self.comm=self.salary*5/100
else:
self.comm=0
def main():
emp1=Employee()
emp1.readEmployee()
emp1.printEmployee()
emp2=Employee()
Employee.readEmployee=readEmployeeNew
emp2.readEmployee()
emp2.printEmployee()
Employee.readEmployee=Employee.readEmployee
emp3=Employee()
292
emp3.readEmployee()
emp3.printEmployee()
main()
Operator overloading
==================
eg:
class Integer:
def __init__(self,v):
self.value=v
return self.value+other.value
def __str__(self):
return str(self.value)
return self.value-other.value
return self.value*other.value
def main():
a=100
b=200
c=a+b
print(a,b,c)
d=a-b
print(a,b,d)
e=a*b
print(a,b,e)
293
n1=Integer(100)
n2=Integer(200)
n3=n1+n2
print(n1,n2,n3)
n4=n1-n2
print(n1,n2,n4)
n5=n1*n2
print(n1,n2,n5)
main()
==> for every operator there is equal method available in object class.
class Student:
def __init__(self):
self.rno=None
self.sub1=None
self.sub2=None
def readStudent(self):
self.sub1=int(input("Enter subject1"))
self.sub2=int(input("Enter subject2"))
def printStudent(self):
print(self.rno,self.sub1,self.sub2)
return True
else:
return False
def main():
294
stud1=Student()
stud1.readStudent()
stud1.printStudent()
stud2=Student()
stud2.readStudent()
stud2.printStudent()
b=stud1==stud2 # stud1.__eq__(stud2)
print(b)
main()
operator methods
+ __add__
- __sub__
* __mul__
class Employee:
def __init__(self):
self.empno=None
self.salary=None
def readEmployee(self):
self.empno=int(input("Enter empno"))
self.salary=float(input("Enter salary"))
def printEmployee(self):
print(self.empno,self.salary)
return self.salary+other.salary
def main():
emp1=Employee()
emp2=Employee()
emp1.readEmployee()
emp2.readEmployee()
295
total=emp1+emp2
print(total)
emp1.printEmployee()
emp2.printEmployee()
main()
===================================
==> Method Resolution Order is an order in which python search or looks for method
class A:
def m1(self):
print("m1 of A")
class B(A):
def m2(self):
print("m2 of B")
class C(B):
def m3(self):
print("m3 of C")
def main():
objc=C()
objc.m1()
print(C.mro())
main()
15&17/8/2020
Exception Handling or Error Handling
===============================
296
1. syntax errors
2. runtime errors
==> If there is a syntax error within program, it cannot be executed. these error
recognized by python translator/compiler. until these errors are not rectified program
eg:
print("Hello")
print("Bye")
if True:
print("Bye")
runtime error
===========
==> the errors which occurs during execution of program are called runtime errors.
==> why these errors occurs becoz of wrong input given by end user.
eg:
n3=n1/n2
print(n1,n2,n3)
output:
5 2 2.5
3, in <module>
297
n3=n1/n2
eg:
print(x)
output:
12
1, in <module>
==> the error which occurs during the execution of program are called runtime errors
or exceptions.
==> every error is one type/class, whose object created by function and raise
generate.
NameError,ZeroDivisionError,...
list1=list([10,20,30,40,50])
print(list1)
list2=list(10)
298
program execution is terminated. to avoid abnormal termination
==============================
1. try
2. except
3. finally
4. raise
5. assert
1. ValueError
Raised when an operation or function receives an argument that has the right type but
an inappropriate value
2. TypeError
The associated value is a string giving details about the type mismatch.
Passing arguments of the wrong type (e.g. passing a list when an int is expected)
int([10,20,30])
list(10)
3. ZeroDivisionError
4. IndexError
5. KeyError
299
KeyError
Raised when a mapping (dictionary) key is not found in the set of existing keys.
6. NameError
7. exception ModuleNotFoundError
located
try block
=======
==> this block contain the statements which raise and exception.
==> this block contain the statements which has to be monitored for exception
handling.
syntax:
try:
statement-1
statement-2
except block
===========
==> except block is an error handler block. when there is an error/exception within try
syntax:
try:
except <error-type>:
statement
except <error-type>:
statement
==> if try block raise/generate more than one type of exception, it is handled by using
300
mulitple except blocks.
eg:
def main():
try:
z=x/y
print(z)
except ZeroDivisionError:
print("Complete")
main()
eg:
def main():
dict1={'java':5000,'python':4000,'c':2000,'c++':1000}
ans='yes'
while ans!='no':
try:
fees=dict1[key]
print(fees)
except KeyError:
ans=input("Enter answer")
main()
==> it try block raises more than one exception, it is handled using
301
def main():
try:
x=int(input("Enter x value"))
y=int(input("Enter y value"))
z=x/y
print(z)
except ZeroDivisionError:
except ValueError:
main()
=========================================================
==> inorder t handle multiple errors using one except block, we need to
import sys
def main():
try:
n3=n1/n2
print(n3)
except:
print(sys.exc_info())
t=sys.exc_info()
print(t[1])
main()
finally
=====
302
==> finally is not an exception/error handler.
==> it is block which is excuted after try block and except block.
==> this block contain the code which is common for try block
try block.
try:
send message
except type:
error is handled
finally:
3. if there is an error inside try block and not handled by except block, it execute
eg:
def main():
try:
print(x)
except ValueError:
finally:
303
print("Continue")
main()
30&31/7/2020
=============
=============================================
import statement
==============
==> import statement allows to use the content of one module inside another module.
import module-name
module1.py
==========
def power(n,p):
return n**p
def maxTwo(n1,n2):
if n1>n2:
return n1
else:
return n2
module2.py
==========
import module1
def main():
304
res1=module1.power(5,2)
res2=module1.maxTwo(100,200)
print("Result1",res1)
print("Result2",res2)
main()
============================
==> the module name can be imported with another name with the help of the following syntax.
eg;
import module1 as m1
def main():
res1=m1.power(5,2)
res2=m1.maxTwo(100,200)
print(res1)
print(res2)
main()
==========================
==> we can import the content of module inside current module using the following syntax.
============================================
==> we need to check the following condition inorder import executable module as reusable module.
if __name__=='__main__':
main()
module4.py
=========
305
def fun1():
print("inside function1")
def fun2():
print("inside function2")
def fun3():
print("inside function3")
def main():
fun1()
fun2()
fun3()
if __name__=='__main__':
main()
module5.py
==========
import module4
def fun4():
print("inside function4")
def main():
module4.fun1()
fun4()
main()
package
=======
Q: What is package?
==> This file does not contain any code. this file indicates that it
is a package.
306
How to create package?
pip command
============
==> pip is used to install python packages from the python package index and other.
Q: What PyPI?
Open terminal
============
>pip
==> python virtual environment which consist of python software and installed packages(local
repository).
==> python virtual envrironment is used to develop and execute python applications.
==> first step install virtualenv module/tool. which is used to work with virtual environment.
307
virtualenv <evnrionment-name>
(OR)
2. virtualenv <envrionment-name>
==> on creation virtualenvironment, it include python interpreter and default lib and other tools
3. c:\>c:\myenv\Scripts\activate
c:\>c:\myenv\Scripts\deactivate
1/8/2020
========
==> Object oriented programming is not a language. It is a concept which define set of
Q: What is object?
Q: What is class?
308
==> class is encapsulated with properties/attributes and behaviour/methods of object.
C: Python
1. Encapsulation
2. Polymorphism
3. Inheritance
4. class
5. object
Encapsulation:
=============
==> Encapsulation is a process of grouping data and operations which operate on that
Adv:
Data Hiding : preventing data access from unrelated operations is called data hiding.
2. Reusability
3. Security
4. Extensibility
5. Efficiency
=================
309
==> define a class is creating a new datatype/userdefined datatype.
and functions.
syntax of class
============
class <class-name>:
variables
methods/member function
variables
========
3/8/2020
========
=================================
==> object properties are defined using instance variables/object level variables.
2. setattr() function
3. properties class
__init__(self):
==> this constructor method, this method is called automatically at the time of creating
object.
==> any method which suffix and prefix with __ is called magic method and these
310
methods are called automatically.
==> using self, we can create or access object level variables/instance variables.
==> __init__(self) contain the operations which has to be performed at the time of
creating.
eg:
class A:
def __init__(self):
print("object created")
def main():
a1=A()
a2=A()
a3=A()
print(a1)
print(a2)
print(a3)
main()
eg:
class Student:
def __init__(self):
self.rno=0
self.name=""
def main():
stud1=Student()
311
stud2=Student()
stud1.rno=101
stud1.name="naresh"
stud2.rno=102
stud2.name="suresh"
print(stud1.rno,stud1.name)
print(stud2.rno,stud2.name)
main()
eg:
class A:
def __init__(self):
self.x=100
self.y=200
def main():
print(A.x,A.y)
main()
Expl: the above code display syntax error becoz object level variables accessed with
object name not with class name and cannot accessed without creating object.
eg: class A:
def __init__(self):
self.x=100
self.y=200
312
class B:
def __init__(self):
self.__x=100
self.__y=200
def main():
obj1=A()
print(obj1.x,obj1.y)
obj2=B()
print(obj2.__x,obj2.__y)
main()
class Student:
def __init__(self):
self.__rno=101
self.__name="naresh"
self.__course="python"
def main():
stud1=Student()
print(stud1.__rno)
print(stud1.__name)
print(stud1.__course)
list1=list()
list1.append()
main()
4/8/2020
========
313
==> private members are accessible by members(functions/methods) of these same
class Student:
def __init__(self):
self.__rno=101
self.__name="naresh"
self.__course="python"
def main():
stud1=Student()
print(stud1.__rno)
print(stud1.__name)
print(stud1.__course)
list1=list()
list1.append()
main()
methods
========
3. static methods
================================
==> these methods are used to perform operation on object level variables.
314
==> any method defined inside class with first argument 'self' is called object level
==> this method access object level variables using 'self' argument inorder to
syntax:
def <method-name>(self,arg1,arg2,arg3,...):
statement-1
statement-2
==> this method is called with object and cannot called without creating object.
ex:
class Student:
def __init__(self):
self.__rno=101
self.__name="naresh"
self.__course="python"
def printStudent(self):
print(self.__rno)
print(self.__name)
print(self.__course)
def main():
stud1=Student()
# print(stud1.__rno)
# print(stud1.__name)
# print(stud1.__course)
stud1.printStudent()
main()
eg:
class Triangle:
def __init__(self):
315
self.__base=0.0
self.__height=0.0
def setBase(self,b):
self.__base=b
def setHeight(self,h):
self.__height=h
def findArea(self):
return self.__base*self.__height*0.5
def main():
t1=Triangle()
t1.setBase(1.5)
t1.setHeight(2.5)
t1_area=t1.findArea()
t2=Triangle()
t2.setBase(2.5)
t2.setHeight(3.5)
t2_area=t2.findArea()
main()
eg:
class Matrix:
def __init__(self):
self.__m=[[0,0],[0,0]]
def printMatrix(self):
print(col,end=' ')
print()
316
def readMatrix(self):
for i in range(2):
for j in range(2):
self.__m[i][j]=int(input("Enter element"))
def main():
m1=Matrix()
m1.printMatrix()
m2=Matrix()
m2.printMatrix()
m1.readMatrix()
m1.printMatrix()
m2.readMatrix()
m2.printMatrix()
main()
eg:
class Stack:
def __init__(self):
self.__s=[]
self.__top=-1
def push(self,value):
self.__s.append(value)
print("element pushed")
self.__top=self.__top+1
def pop(self):
if self.__top==-1:
print("Stack is empty")
else:
value=self.__s[self.__top]
del self.__s[self.__top]
317
self.__top=self.__top-1
return value
def main():
stack1=Stack()
stack1.push(100)
stack1.push(200)
stack1.push(300)
e1=stack1.pop()
e2=stack1.pop()
print(e1)
print(e2)
main()
eg:
class Calculator:
def __init__(self,n1,n2):
self.__num1=n1
self.__num2=n2
def add(self):
return self.__num1+self.__num2
def sub(self):
return self.__num1-self.__num2
def multiply(self):
return self.__num1*self.__num2
def main():
calc1=Calculator(100,200)
print(calc1.add())
print(calc1.sub())
print(calc1.multiply())
318
main()
3. write a class to represent marks details of student and calculate total,avg and result
5/8/2020
=========
class Circle:
def __init__(self):
self.__r=0.0
self.__r=r
def findArea(self):
return 3.147*self.__r*self.__r
def main():
circle1=Circle()
circle1.setR(1.2)
area1=circle1.findArea()
main()
class Rectangle:
def __init__(self):
self.__l=0.0
self.__b=0.0
def setL(self,l):
self.__l=l
def setB(self,b):
319
self.__b=b
def findArea(self):
return self.__l*self.__b
def main():
rect1=Rectangle()
rect1.setL(1.5)
rect1.setB(2.5)
area1=rect1.findArea()
main()
3. write a class to represent marks details of student and calculate total,avg and
result
class StudentMarks:
def __init__(self):
self.__rno=0
self.__name=""
self.__sub1=0
self.__sub2=0
def readData(self):
self.__rno=int(input("Enter rollno"))
self.__name=input("Enter name")
self.__sub1=int(input("Enter subject1"))
self.__sub2=int(input("Enter subject2"))
def printData(self):
print(f'Rollno {self.__rno}')
print(f'Name {self.__name}')
print(f'Subject1 {self.__sub1}')
print(f'Subject2 {self.__sub2}')
print(f'Total {self.__sub1+self.__sub2}')
320
print(f'Avg {(self.__sub1+self.__sub2)/2}')
if self.__sub1<40 or self.__sub2<40:
print("Result is Fail")
else:
print("Result is Pass")
def main():
studentList=[]
for i in range(n):
s=StudentMarks()
s.readData()
studentList.append(s)
stud.printData()
main()
class Player:
def __init__(self):
self.__name=""
self.__score=0
def setName(self,n):
self.__name=n
def setScore(self,s):
self.__score=s
def getName(self):
return self.__name
def getScore(self):
return self.__score
def main():
321
n=int(input("Enter how many players"))
playerList=list()
for i in range(n):
p=Player()
n=input("Enter name")
s=int(input("Enter score"))
p.setName(n)
p.setScore(s)
playerList.append(p)
tot=0
for p in playerList:
tot=tot+p.getScore()
print(f'{p.getName()}--->{p.getScore()}')
main()
6&7/8/2020
==========
=====================================
=================
==> the variables declared inside the class are called class level
variable.
==> this variable can be accessed with class name without creating
object.
eg:
322
class Account:
def __init__(self,accno,cname,bal):
def deposit(self,amt):
self.__bal=self.__bal+amt
def withdraw(self,amt):
if self.__bal-amt<Account.minBalance:
print("Insuff balance")
else:
self.__bal=self.__bal-amt
def printAccount(self):
print(f'AccountNo {self.__accno}')
print(f'CustomerName {self.__cname}')
print(f'Balance {self.__bal}')
def main():
acc1=Account(101,"suresh",50000)
acc1.printAccount()
acc1.withdraw(45000)
acc1.printAccount()
acc1.withdraw(2000)
acc2=Account(102,"kishore",6000)
main()
#find output
class A:
x=100
def __init__(self):
323
self.y=200
def main():
print(A.x) # 100
a1=A()
a2=A()
a1.x=200
a1.y=300
a2.x=400
a2.y=500
print(a1.x,a1.y)
print(a2.x,a2.y)
main()
Ouput:
200 300
400 500
==> class level variable cannot modify with object name. if we trying modify with
==> class level variable can access with object name but cannot modified.
===============
==> a method defined inside class with first argument as 'cls' is called class level
method.
==> this method is called with class name, without creating object.
==> inorder to declare class level method we use a decorator called @classmethod
syntax:
@classmethod
def <method-name>(cls,arg1,arg2,arg3,...):
324
statement-1
statement-2
statement-3
==> class level methods are used in application development for creating objects.
==> class level methods are called factory methods, these methods create object
eg:
class A:
def m1(self):
@classmethod
def m2(cls):
def main():
A.m2()
# A.m1() error
obj1=A()
obj1.m1()
main()
eg:
class Person:
def __init__(self,n,a):
self.name=n
self.age=a
@classmethod
def createPerson(cls,n,dob):
a=2020-dob
p=Person(n,a)
return p
325
def printPerson(self):
print(f'Name :{self.name}')
print(f'Age : {self.age}')
def main():
p1=Person("naresh",40)
p2=Person("suresh",30)
p3=Person.createPerson("kishore",1980)
p4=Person.createPerson("rajesh",1992)
p1.printPerson()
p2.printPerson()
p3.printPerson()
p4.printPerson()
main()
eg:
class Employee:
def __init__(self,eno,en,s,c):
self.__empno=eno
self.__ename=en
self.__salary=s
self.__comm=c
@classmethod
def createEmployee(cls,eno,en,s):
c=0
if s>=10000:
c=s*10/100
c=s*5/100
else:
c=s*2/100
326
e=cls(eno,en,s,c)
return e
def printEmployee(self):
print(f'EmployeeNo {self.__empno}')
print(f'EmployeeName {self.__ename}')
print(f'Salary {self.__salary}')
print(f'Comm {self.__comm}')
def main():
emp1=Employee(101,"naresh",5000,100)
emp2=Employee.createEmployee(102,"suresh",9000)
emp1.printEmployee()
emp2.printEmployee()
main()
static methods
============
==> a method defined inside class without first argument as 'cls' or 'self' is called
static method.
@staticmethod
def method-name(arg1,arg2,...):
statement1
statement2
class Math:
@staticmethod
def maxOfIntegers(n1,n2):
if n1>n2:
return n1
else:
327
return n2
@staticmethod
def power(n,p):
return n**p
def main():
m1=Math.maxOfIntegers(100,200)
m2=Math.power(5,2)
print("Max is ",m1)
print("Result is ",m2)
main()
8/8/2020
========
class reusability
=============
==> the content of one class can be used inside another class in
different ways.
1. composition (has-a)
2. aggregation (use-a)
3. inheritance (is-a)
composition(has-a)
===============
==> composition is a process of creating an object of one class inside another class.
1. one-one
2. one-many
3. many-one
4. many-many
328
# one-many
class Address:
def __init__(self):
self.__street=None
self.__city=None
def setStreet(self,st):
self.__street=st
def setCity(self,c):
self.__city=c
def getStreet(self):
return self.__street
def getCity(self):
return self.__city
class Person:
def __init__(self):
self.__name=None
self.add1=Address()
self.add2=Address()
def setName(self,n):
self.__name=n
def getName(self):
return self.__name
def main():
p1=Person()
p1.setName("naresh")
p1.add1.setStreet("S.R.Nager")
p1.add1.setCity("Hyd")
p1.add2.setStreet("M.G.Road")
p1.add2.setCity("Hyd")
329
print(p1.getName())
print(p1.add1.getStreet())
print(p1.add1.getCity())
print(p1.add2.getStreet())
print(p1.add2.getCity())
main()
# one - one
class Dept:
def __init__(self):
self.__deptno=None
self.__dname=None
def setDeptno(self,dno):
self.__deptno=dno
def setDname(self,dn):
self.__dname=dn
def getDeptno(self):
return self.__deptno
def getDeptName(self):
return self.__dname
class Employee:
def __init__(self):
self.__ename=None
self.dept=Dept()
def setName(self,n):
self.__ename=n
def getName(self):
return self.__ename
def main():
emp1=Employee()
330
emp1.setName("naresh")
emp1.dept.setDeptno(10)
emp1.dept.setDname("Sales")
print(emp1.getName())
print(emp1.dept.getDeptno())
print(emp1.dept.getDeptName())
main()
# many to one
class College:
def __init__(self):
self.__came=None
def setCname(self,cn):
self.__cname=cn
def getCname(self):
return self.__cname
class Student:
def __init__(self):
self.__rno=None
self.__name=None
def setRno(self,rno):
self.__rno=rno
def getRno(self):
return self.__rno
def setName(self,name):
self.__name=name
def getName(self):
return self.__name
def main():
331
Student.college.setCname("NIT")
stud1=Student()
stud2=Student()
stud1.setRno(101)
stud1.setName("naresh")
stud2.setRno(102)
stud2.setName("Suresh")
print(stud1.getRno())
print(stud1.getName())
print(stud2.getRno())
print(stud2.getName())
print(Student.college.getCname())
main()
Aggregation(Use-A)
================
In composition,
class Engine:
def start(self):
print("Car start...")
def stop(self):
print("Car stop..")
class Car:
def __init__(self,e):
self.__e=e
332
def carStart(self):
self.__e.start()
def carStop(self):
self.__e.stop()
def main():
engine1=Engine()
car1=Car(engine1)
car1.carStart()
car1.carStop()
main()
=======================================================
class BSNLSim:
def call(self):
class AirtelSim:
def call(self):
class Mobile:
def __init__(self):
self.__sim=None
def insert(self,s):
self.__sim=s
def call(self):
self.__sim.call()
def main():
mobile1=Mobile()
bsnlsim1=BSNLSim()
mobile1.insert(bsnlsim1)
mobile1.call()
333
airtelsim1=AirtelSim()
mobile1.insert(airtelsim1)
mobile1.call()
main()
10/8/2020
Inheritance(IS_A)
===============
==> Inheritance allows to define class that inherit all the methods and properties from
another class.
==> Inheritance allows to define new class from an existing class. new class is called
==> Inheritance model is called is-relationship. It means that derived class inherit
syntax
======
prperties
methods
3. multiple inheritance
4. hierarchical inheritance
5. hybrid inheritance
334
class A: # parent class
def m1(self):
print("m1 of A")
def m2(self):
print("m2 of B")
def main():
objb=B()
objb.m1()
objb.m2()
main()
class A:
def __init__(self):
self.x=100
class B(A):
def __init__(self):
self.y=200
super().__init__()
def main():
objb=B()
print(objb.x)
print(objb.y)
main()
==> if constructor method of base class is not called in derived class the properties of
335
==> this calling is done using super().__init__() .
# hierarchical Inheritance
class Employee:
def __init__(self):
self.__empid=None
self.__ename=None
def setEmpid(self,eid):
self.__empid=eid
def setEname(self,en):
self.__ename=en
def getEmpid(self):
return self.__empid
def getEname(self):
return self.__ename
class SalriedEmployee(Employee):
def __init__(self):
self.__salary=None
super().__init__()
def setSalary(self,sal):
self.__salary=sal
def getSalary(self):
return self.__salary
class CommEmployee(Employee):
def __init__(self):
self.__comm=None
super().__init__()
def setComm(self,com):
self.__comm=com
336
def getComm(self):
return self.__comm
def main():
emp1=SalriedEmployee()
emp2=CommEmployee()
emp1.setEmpid(101)
emp1.setEname("rajesh")
emp1.setSalary(50000)
emp2.setEmpid(102)
emp2.setEname("kishore")
emp2.setComm(500)
print(f'{emp1.getEmpid()},{emp1.getEname()},{emp1.getSalary()}')
print(f'{emp2.getEmpid()},{emp2.getEname()},{emp2.getComm()}')
main()
class Alpha:
def __init__(self,x):
self.__x=x
def getX(self):
return self.__x
class Beta(Alpha):
def __init__(self,x,y):
self.__y=y
super().__init__(x)
def getY(self):
return self.__y
def main():
b1=Beta(100,200)
print(b1.getX())
337
print(b1.getY())
main()
# private members of base class are not accessible inside derived class
class A:
def __init__(self):
self.__x=100
class B(A):
def __init__(self):
super().__init__()
def printX(self):
print(self.__x)
def main():
b1=B()
b1.printX()
main()
# public members of base class/super class are accessible inside derived class
class A:
def __init__(self):
self.x=100
class B(A):
def __init__(self):
super().__init__()
def printX(self):
print(self.x)
def main():
b1=B()
b1.printX()
main()
=====================================================================
338
class Account:
def __init__(self,accno,cname,bal):
self.__accno=accno
self.__cname=cname
self.__bal=bal
def getAccno(self):
return self.__accno
def getCname(self):
return self.__cname
def getBal(self):
return self.__bal
def setBal(self,b):
self.__bal=b
class SavingAccount(Account):
def __init__(self,accno,cname,bal,cheqfac):
self.__cheqfac=cheqfac
super().__init__(accno,cname,bal)
def deposit(self,tamt):
b=self.getBal()
b=b+tamt
self.setBal(b)
def getCheqFac(self):
return self.__cheqfac
def main():
acc1=SavingAccount(101,"ramesh",6000,True)
print(acc1.getAccno(),acc1.getCname(),acc1.getBal(),acc1.getCheqFac())
acc1.deposit(2000)
main()
339
Multiple inheritance
================
==> if a class derive more than one base class ,it is called multiple inheritance.
==> in multiple inheritance derived class must call the constructor of base classes.
class A:
def __init__(self):
self.x=100
class B:
def __init__(self):
self.y=200
def __init__(self):
self.z=300
A.__init__(self)
B.__init__(self)
def main():
objc=C()
print(objc.x)
print(objc.y)
print(objc.z)
main()
=======================
class A:
def __init__(self,x):
self.__x=x
def getX(self):
return self.__x
340
class B:
def __init__(self,y):
self.__y=y
def getY(self):
return self.__y
class C(A,B):
def __init__(self,x,y,z):
self.__z=z
A.__init__(self,x)
B.__init__(self,y)
def getZ(self):
return self.__z
def main():
objc=C(100,200,300)
print(objc.getX(),objc.getY(),objc.getZ())
main()
11/8/2020
Hierarchical Inheritance
====================
class Person:
def __init__(self,id,name):
self.__id=id
self.__name=name
def getId(self):
return self.__id
def getName(self):
return self.__name
class Student(Person):
341
def __init__(self,id,name,course):
self.__course=course
super().__init__(id,name)
def setCourse(self,course):
self.__course=course
def getCourse(self):
return self.__course
class Teacher(Person):
def __init__(self,id,name,subject):
self.__subject=subject
super().__init__(id,name)
def getSubject(self):
return self.__subject
class AdminStaff(Person):
def __init__(self,id,name,job):
self.__job=job
super().__init__(id,name)
def getJob(self):
return self.__job
def main():
stud1=Student(101,"naresh","python")
t1=Teacher(102,"suresh","java")
ns=AdminStaff(103,"kishore","Acc")
print(stud1.getId(),stud1.getName(),stud1.getCourse())
print(t1.getId(),t1.getName(),t1.getSubject())
print(ns.getId(),ns.getName(),ns.getJob())
main()
protected members
=================
342
==> protected members are prefix single underscore _
class A:
def __init__(self):
self.__x=100 # private
self._y=200 # protected
self.z=300 # public
class B(A):
def printY(self):
print(self._y)
def main():
obja=A()
print(obja._y)
print(obja.z)
main()
Method Overriding
===============
==> redefining of base class instance method or object level method within derived
==> defining method inside derived class with same name and arguments of method
==> method overriding allows to extend or modify functionality of base class method
==> if derived class wants to have different implementation of method exists in base
343
class Parent:
class Child(Parent):
def sleep(self):
print("child sleep")
def main():
c=Child()
================================================
class A:
def m1(self):
print("Overriden method")
class B(A):
def m1(self):
print("Overriding method")
def main():
objb=B()
objb.m1()
main()
==================================================
class Account:
def __init__(self):
self.__accno=None
self.__bal=None
def read(self):
344
self.__accno=int(input("AccountNo :"))
self.__bal=float(input("Balance :"))
def printAcc(self):
print("AccountNo :",self.__accno)
print("Balance ",self.__bal)
class CurrentAccount(Account):
def __init__(self):
self.__creditCard=None
self.__creditCard=input("Enter Yes/No")
print("CreaditCard :",self.__creditCard)
def main():
acc1=CurrentAccount()
acc1.read()
acc1.printAcc()
main()
==================================================================
object class
==========
12/8/2020
object class
==========
345
==> object class is a base class of all class in python.
__str__() : it is method of object class this method returns type and id of object. this
method called when ever we print variable. this method is called automatically
class Student:
def __init__(self,rno,name):
self.__rno=rno
self.__name=name
return str(self.__rno)+","+self.__name
def main():
stud1=Student(101,"naresh")
print(stud1)
list1=list([10,20,30,40,50])
print(list1)
main()
==> override __str__ to return state of the object whenever print reference variable.
method, becoz of that when ever we print variables of these type, it print values not
address.
class Employee:
def __init__(self,eid,en):
self.empid=eid
self.ename=en
def __str__(self):
return str(self.empid)+","+self.ename
def main():
emp1=Employee(101,"suresh")
346
print(emp1)
list1=list()
list1.append(Employee(102,"kishore"))
list1.append(Employee(103,"naresh"))
print(list1)
e1=list1[0]
print(e1)
main()
__eq__ method
============
userdefined class.
== operator.
def main():
list1=[10,20,30,40,50]
list2=[10,20,30,40,50]
b=list1==list2
print(b)
print(id(list1))
print(id(list2))
main()
class Player:
def __init__(self,pn,r):
347
self.pname=pn
self.runs=r
if self.runs==other.runs:
return True
else:
return False
def main():
p1=Player('rahul',100)
p2=Player('rohit',100)
p3=Player('virat',60)
b=p1==p2 # p1.__eq__(p2)
print(b)
print(id(p1))
print(id(p2))
b=p1==p3 # p1.__eq__(p3)
print(b)
main()
class Alpha:
def __init__(self,x):
self.__x=x
def __str__(self):
return str(self.__x)
if self.__x==other.__x:
return True
else:
return False
def main():
348
a1=Alpha(100)
a2=Alpha(200)
a3=Alpha(100)
print(a1,a2,a3)
b1=a1==a2
b2=a1==a3
print(b1,b2)
main()
==========================
__hash__ method.
eg:
class A:
def __init__(self,x):
self.__x=x
def __str__(self):
return str(self.__x)
if self.__x==other.__x:
return True
349
else:
return False
def __hash__(self):
return self.__x
def main():
obj1=A(100)
obj2=A(200)
set1=set()
set1.add(obj1)
set1.add(obj2)
for s in set1:
print(s)
main()
eg:
class Student:
def __init__(self,rno,name):
self.__rno=rno
self.__name=name
def __str__(self):
return str(self.__rno)+","+self.__name
if self.__rno==other.__rno:
return True
else:
return False
def __hash__(self):
return self.__rno
def main():
studSet=set()
350
studSet.add(Student(101,"naresh"))
studSet.add(Student(102,"suresh"))
studSet.add(Student(101,"kishore"))
for s in studSet:
print(s)
main()
==============================
abstractmethod
=============
@abstractmethod decorator
syntax:
@abstractmethod
def <method-name>(self,arg1,arg2,arg3,..):
pass
abstract class
============
==> abstract class is a collection of abstract methods and non abstract methods.
==> if class is derived from "ABC" class, it is called abstract base class.
==> abstract class is inherited, but cannot used for creating object.
351
has to be followed by every derived class.
import abc
class <class-name>(abc.ABC):
variables
method
eg:
class A(ABC):
@abstractmethod
def m1(self):
pass
def main():
obja=A()
main()
==> the above code/program display error becoz we cannot create object of
eg:
class A(ABC):
@abstractmethod
def m1(self):
pass
def m2(self):
class B(A):
def m3(self):
print("m2 of B")
def main():
352
objb=B()
main()
==> the above program display error becoz the class which inherit abstract base
class must override all abstract method if not, the derived calss cannot used for
creating object.
13/8/2020
=========
==> the above program display error becoz the class which inherit abstract base class
must override all abstract method if not, the derived calss cannot used for creating
object.
class Shape(ABC):
def __init__(self):
self._dim1=None
self._dim2=None
def read(self):
self._dim1=float(input("Enter dim1"))
self._dim2=float(input("Enter dim2"))
@abstractmethod
def findArea(self):
pass
class Triangle(Shape):
def __init__(self):
super().__init__()
def findArea(self):
return self._dim1*self._dim2*0.5
class Rectangle(Shape):
def __init__(self):
353
super().__init__()
def findArea(self):
return self._dim1*self._dim2
def main():
t1=Triangle()
t1.read()
r1=Rectangle()
r1.read()
a1=t1.findArea()
a2=r1.findArea()
main()
==> Inheritance is process of grouping all the classes which share common properties
and behaviour.
duck typing
==========
==> Duck typing in computer programming is an application of the duck test— "If it
walks like a duck and it quacks like a duck, then it must be a duck"— to determine if an
==> Duck typing is a concept related to dynamic typing, where the type or the class of
an object is less important than the methods it defines. When you use duck typing, you
do not check types at all. Instead, you check for the presence of a given method or
attribute.
==>Python follows the EAFP (Easier to Ask Forgiveness than Permission) rather than
the LBYL (Look Before You Leap) philosophy. The Python philosophy of EAFP is
==> Loosly Coupled Code, The code which work with any
354
class DebitCard:
def withdraw(self):
class CreditCard:
def withdraw(self):
class EMICard:
def withdraw(self):
class SwappingMachine:
def swap(self,s):
s.withdraw()
class ATM:
def swap(self,s):
s.withdraw()
def main():
card1=DebitCard()
card2=CreditCard()
card3=EMICard()
s1=SwappingMachine()
a1=ATM()
s1.swap(card1)
s1.swap(card2)
s1.swap(card3)
a1.swap(card1)
a1.swap(card2)
a1.swap(card3)
main()
eg:
355
class AirtelSim:
def call(self):
class BsnlSim:
def call(self):
class JioSim:
def call(self):
class Mobile:
def call(self,s):
s.call()
def main():
mobile1=Mobile()
sim1=AirtelSim()
sim2=BsnlSim()
sim3=JioSim()
mobile1.call(sim1)
mobile1.call(sim2)
mobile1.call(sim3)
main()
mokey patching
============
runtime.
Monkey patching is a technique that allows you to alter the behavior of objects at
runtime.
356
14/8/2020
==========
monkey patching
=============
runtime.
Monkey patching is a technique that allows you to alter the behavior of objects at
runtime.
code at run-time.
eg:
class A:
@classmethod
def m1(cls):
print("Hello")
@classmethod
def m2(cls):
print("Bye")
def main():
A.m1()
A.m1()
main()
357
eg:
class A:
def m1(self):
print("Hello")
def m2(self):
print("Bye")
def main():
obj1=A()
obj1.m1()
obj1.m1()
main()
class Employee:
def __init__(self):
self.empno=None
self.ename=None
self.salary=None
self.comm=None
def readEmployee(self):
self.empno=int(input("Enter EmployeeNo"))
self.ename=input("Enter EmployeeName")
self.salary=float(input("Enter Salary"))
if self.salary>=10000:
self.comm=self.salary*10/100
self.comm=self.salary*5/100
else:
self.comm=0
def printEmployee(self):
358
print(self.empno,self.ename,self.salary,self.comm)
#patch
def readEmployeeNew(self):
self.empno=int(input("Enter employeeno"))
self.ename=input("Enter employeename")
self.salary=float(input("Enter salary"))
if self.salary>=20000:
self.comm=self.salary*10/1000
self.comm=self.salary*5/100
else:
self.comm=0
def main():
emp1=Employee()
emp1.readEmployee()
emp1.printEmployee()
emp2=Employee()
Employee.readEmployee=readEmployeeNew
emp2.readEmployee()
emp2.printEmployee()
Employee.readEmployee=Employee.readEmployee
emp3=Employee()
emp3.readEmployee()
emp3.printEmployee()
main()
Operator overloading
==================
359
which operator on userdefined datatypes.
eg:
class Integer:
def __init__(self,v):
self.value=v
return self.value+other.value
def __str__(self):
return str(self.value)
return self.value-other.value
return self.value*other.value
def main():
a=100
b=200
c=a+b
print(a,b,c)
d=a-b
print(a,b,d)
e=a*b
print(a,b,e)
n1=Integer(100)
n2=Integer(200)
n3=n1+n2
print(n1,n2,n3)
n4=n1-n2
print(n1,n2,n4)
n5=n1*n2
360
print(n1,n2,n5)
main()
==> for every operator there is equal method available in object class.
class Student:
def __init__(self):
self.rno=None
self.sub1=None
self.sub2=None
def readStudent(self):
self.sub1=int(input("Enter subject1"))
self.sub2=int(input("Enter subject2"))
def printStudent(self):
print(self.rno,self.sub1,self.sub2)
return True
else:
return False
def main():
stud1=Student()
stud1.readStudent()
stud1.printStudent()
stud2=Student()
stud2.readStudent()
stud2.printStudent()
b=stud1==stud2 # stud1.__eq__(stud2)
361
print(b)
main()
operator methods
+ __add__
- __sub__
* __mul__
class Employee:
def __init__(self):
self.empno=None
self.salary=None
def readEmployee(self):
self.empno=int(input("Enter empno"))
self.salary=float(input("Enter salary"))
def printEmployee(self):
print(self.empno,self.salary)
return self.salary+other.salary
def main():
emp1=Employee()
emp2=Employee()
emp1.readEmployee()
emp2.readEmployee()
total=emp1+emp2
print(total)
emp1.printEmployee()
emp2.printEmployee()
main()
===================================
362
==> Method Resolution Order is an order in which python search or looks for method
class A:
def m1(self):
print("m1 of A")
class B(A):
def m2(self):
print("m2 of B")
class C(B):
def m3(self):
print("m3 of C")
def main():
objc=C()
objc.m1()
print(C.mro())
main()
15&17/8/2020
Exception Handling or Error Handling
===============================
1. syntax errors
2. runtime errors
==> If there is a syntax error within program, it cannot be executed. these error
recognized by python translator/compiler. until these errors are not rectified program
eg:
print("Hello")
363
print("Bye")
if True:
print("Bye")
runtime error
===========
==> the errors which occurs during execution of program are called runtime errors.
==> why these errors occurs becoz of wrong input given by end user.
eg:
n3=n1/n2
print(n1,n2,n3)
output:
5 2 2.5
3, in <module>
n3=n1/n2
eg:
print(x)
output:
364
12
1, in <module>
==> the error which occurs during the execution of program are called runtime errors
or exceptions.
==> every error is one type/class, whose object created by function and raise
generate.
NameError,ZeroDivisionError,...
list1=list([10,20,30,40,50])
print(list1)
list2=list(10)
==============================
365
==> the following keywords are used to handler errors.
1. try
2. except
3. finally
4. raise
5. assert
1. ValueError
Raised when an operation or function receives an argument that has the right type but
an inappropriate value
2. TypeError
The associated value is a string giving details about the type mismatch.
Passing arguments of the wrong type (e.g. passing a list when an int is expected)
int([10,20,30])
list(10)
3. ZeroDivisionError
4. IndexError
5. KeyError
KeyError
Raised when a mapping (dictionary) key is not found in the set of existing keys.
6. NameError
7. exception ModuleNotFoundError
located
366
try block
=======
==> this block contain the statements which raise and exception.
==> this block contain the statements which has to be monitored for exception
handling.
syntax:
try:
statement-1
statement-2
except block
===========
==> except block is an error handler block. when there is an error/exception within try
syntax:
try:
except <error-type>:
statement
except <error-type>:
statement
==> if try block raise/generate more than one type of exception, it is handled by using
eg:
def main():
try:
z=x/y
367
print(z)
except ZeroDivisionError:
print("Complete")
main()
eg:
def main():
dict1={'java':5000,'python':4000,'c':2000,'c++':1000}
ans='yes'
while ans!='no':
try:
fees=dict1[key]
print(fees)
except KeyError:
ans=input("Enter answer")
main()
==> it try block raises more than one exception, it is handled using
def main():
try:
x=int(input("Enter x value"))
y=int(input("Enter y value"))
z=x/y
print(z)
except ZeroDivisionError:
368
print("cannot divide number with zero")
except ValueError:
main()
=========================================================
==> inorder t handle multiple errors using one except block, we need to
import sys
def main():
try:
n3=n1/n2
print(n3)
except:
print(sys.exc_info())
t=sys.exc_info()
print(t[1])
main()
finally
=====
==> it is block which is excuted after try block and except block.
==> this block contain the code which is common for try block
try block.
369
try:
send message
except type:
error is handled
finally:
3. if there is an error inside try block and not handled by except block, it execute
eg:
def main():
try:
print(x)
except ValueError:
finally:
print("Continue")
main()
371
def main():
u=input("Enter Username")
p=input("Enter Password")
try:
x=login(u,p)
print(x)
except ValueError:
t=sys.exc_info()
print(t[1])
main()
custom errortypes or userdefined error types
=====================================
==> each error type is one class.
==> userdefined errortype is also class which must inherit exception class.
syntax:
class <exception-class-name>(exception):
def __init__(self):
super().__init__()
eg:
class LoginError(Exception): # user define error type
def __init__(self):
super().__init__()
def login(user,password):
if user=='nit' and password=='nit123':
return "welcome to my application"
else:
raise LoginError()
def main():
u=input("Enter username")
p=input("Enter password")
try:
r=login(u,p)
print(r)
except LoginError:
372
print("invalid user name or password")
main()
eg:
class InsuffBalError(Exception):
def __init__(self):
super().__init__()
class Account:
def __init__(self,accno,balance):
self.accno=accno
self.balance=balance
def withdraw(self,tamt):
if self.balance<tamt:
raise InsuffBalError()
else:
self.balance=self.balance-tamt
def getBalance(self):
return self.balance
def getAccno(self):
return self.accno
def main():
acc1=Account(101,5000)
print(acc1.getAccno(),acc1.getBalance())
try:
acc1.withdraw(2000)
print(acc1.getAccno(),acc1.getBalance())
acc1.withdraw(4000)
print(acc1.getAccno(),acc1.getBalance())
except InsuffBalError:
print("Balance not avl")
main()
assert keyword
=============
==> assert keyword is used for debugging code.
==> assert keyword is used to check the given condition is True or False
373
syntax:
assert test
assert test,"message"
==> if test condition is True it continue statement otherwise raises AssertionError.
==> it used by only programmer for debugging purpose.
==> after debugging these assertions are removed from program.
a=6
assert a==5
print("hello")
print("bye")
files
====
Q: What is a file?
==> file is a collection of data.
==> file is used to save the data permanently.
==> the data which is stored in RAM is temp, inorder
to persist data we use files or database.
Inorder to work with files, we need follow these steps.
1. open the file
2. write or read data
3. close file
types of files
==========
==> there are two types of files.
1. text files
2. binary files
==> text file is a collection of characters. the data is stored in character format.
==> binary file is a collection of bytes. the data will be stored in one byte format.
text files
=======
==> text file is a collection of characters. the data is stored in character format.
open()
=====
open(file, mode='r')
374
Open file and return a corresponding file object. If the file cannot be opened, an
OSError is raised.
file is a path-like object giving the pathname
mode is an optional string that specifies the mode in which the file is opened. It
defaults to 'r' which means open for reading in text mode.
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open for updating (reading and writing)
"w"
open for writing, truncating the file first. if file with name is already exists it
truncate/delete and write data.
write(s)
Write the string s to the stream and return the number of characters written.
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each
of the lines provided to have a line separator at the end
eg: file is created in current working directory
def main():
f=open("file1.txt","w")
s="Python is a object oriented programming language"
f.write(s)
f.close()
main()
eg: file is created in give path
def main():
f=open("d:\\file1.txt","w")
s="Python is a object oriented programming language"
f.write(s)
f.close()
375
main()
eg: writing inside file using print function
def main():
f=open("student.txt","w")
ans="yes"
while ans!="no":
rno=input("Enter rollno")
name=input("Enter name")
course=input("Enter course")
print(rno,name,course,file=f)
ans=input("Add another student")
f.close()
main()
# writing more than one string
def main():
l=["keyboard\n","mouse\n","monitor\n","harddisk\n"]
f=open("file2.txt","w")
f.writelines(l)
f.close()
main()
"r"
===
open for reading (default). if file not exists it raises OSError
read(size=-1)
Read and return at most size characters from the stream as a single str. If size is
negative or None, reads until EOF.
readline(size=-1)
Read until newline or EOF and return a single str. If the stream is already at EOF, an
empty string is returned.
If size is specified, at most size characters will be read.
eg:
# reading complete file content
def main():
try:
376
f=open("file10.txt","r")
s=f.read()
print(s)
f.close()
except FileNotFoundError:
print("File not exists")
main()
eg:
# reading speficied number of characters
def main():
try:
f=open("file1.txt","r")
s=f.read(10)
print(s)
f.close()
except FileNotFoundError:
print("File not exists")
main()
# write a program to count number vowels in a given file
def main():
f=open("file1.txt","r")
count=0
while True:
ch=f.read(1)
if ch=='':
break
elif ch in "aeiouAEIOU":
count+=1
print("count of vowels ",count)
f.close()
main()
eg:
def main():
f=open("file2.txt","r")
377
l1=f.readline()
print(l1)
l2=f.readlines()
print(l2)
main()
eg: appnd to the existing file
def main():
f=open("file1.txt","a")
f.write("This is appended text")
f.close()
main()
eg: "x" mode ==> if the file is exists with given filename, it raises FileExistsError
def main():
f=open("file1.txt","x") ==> this file1.txt is exists so we can create another file with
same name
f.write("more text")
f.close()
main()
Serialization and DeSerialization (OR) “pickling” and “unpickling”.
======================================================
pickle — Python object serialization
The pickle module implements binary protocols for serializing and de-serializing a
Python object structure. “Pickling” is the process whereby a Python object hierarchy
is converted into a byte stream, and “unpickling” is the inverse operation, whereby a
byte stream (from a binary file or bytes-like object) is converted back into an object
hierarchy. Pickling (and unpickling) is alternatively known as “serialization”,
“marshalling,” or “flattening”; however, to avoid confusion, the terms used here are “pickling” and
“unpickling”.
a=100 ==> bytes ==> pickling
b=1.5 ==> bytes ==> pickling
s=Student() ==> bytes ==> pickling
object ==> bytes ==> pickling
bytes ==> object ==> unpickling
pickle module provide the following functions.
378
pickle.dump(obj, file)
Write the pickled representation of the object obj to the open file object file.
eg:
import pickle
def main():
f=open("file3","wb")
x=100
y=1.5
z=1+2j
pickle.dump(x,f) # type information , properties,data
pickle.dump(y,f)
pickle.dump(z,f)
f.close()
main()
py479.py
class Employee:
def __init__(self):
self.__empno=0
self.__ename=None
self.__salary=None
def readEmployee(self):
self.__empno=int(input("enter empno"))
self.__ename=input("enter ename")
self.__salary=float(input("enter salary"))
def printEmployee(self):
print(f'{self.__empno},{self.__ename},{self.__salary}')
py480.py ==> writing employee details into file
from py479 import Employee
from pickle import *
def main():
f=open("emp.ser","wb")
e1=Employee()
e1.readEmployee()
e2=Employee()
379
e2.readEmployee()
dump(e1,f)
dump(e2,f)
f.close()
main()
how to read these objects from file?
reading is process of converting bytes into object, this process is called
deserialization or unpickling.
pickle.load(file)
Read the pickled representation of an object from the open file object file and return
the reconstituted object hierarchy specified therein.
from pickle import *
def main():
f=open("file3","rb")
x=load(f)
y=load(f)
z=load(f)
print(x)
print(y)
print(z)
f.close()
main()
eg:
from py479 import Employee
from pickle import *
def main():
f=open("emp.ser","rb")
emp1=load(f)
emp2=load(f)
emp1.printEmployee()
emp2.printEmployee()
f.close()
main()
object ==> bytes ==> pickling/serialization
380
bytes ==> object ==> unpicking/deserialization
CSV files
========
==> CSV stands comma separated values.
==> CSV is a standard import and export format.
csv — CSV File Reading and Writing
The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases.
The csv module implements classes to read and write tabular data in CSV format. It
allows programmers to say, “write this data in the format preferred by Excel,” or “read
data from this file which was generated by Excel,” without knowing the precise details
of the CSV format used by Excel. Programmers can also describe the CSV formats
understood by other applications or define their own special-purpose CSV formats.
The csv module’s reader and writer objects read and write sequences. Programmers
can also read and write data in dictionary form using the DictReader and DictWriter
classes.
21/8/2020
=========
CSV files
========
==> CSV stands comma separated values.
==> CSV is a standard import and export format.
csv — CSV File Reading and Writing
The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases.
The csv module implements classes to read and write tabular data in CSV format. It
allows programmers to say, “write this data in the format preferred by Excel,” or “read
data from this file which was generated by Excel,” without knowing the precise details
of the CSV format used by Excel. Programmers can also describe the CSV formats
understood by other applications or define their own special-purpose CSV formats.
The csv module’s reader and writer objects read and write sequences. Programmers
can also read and write data in dictionary form using the DictReader and DictWriter
classes.
381
Reading from csv file
==================
1. open microsoft excel
2. prepare data
Empno Ename Salary Deptno
1 aaa 5000 10
2 bbb 4000 10
3 ccc 3000 20
4 ddd 7000 30
5 eee 9000 10
6 fff 8000 30
7 ggg 6700 20
8 iiii 5600 10
9 hhh 4500 20
10 kkk 3500 10
3. save the file with employee.csv ==> file type ==> csv
eg:
import csv
def main():
f=open("d:\\employee.csv","r")
r=csv.reader(f)
for row in r:
print(row)
f.close()
main()
eg:
import csv
def main():
f=open("d:\\employee.csv","r")
r=csv.reader(f)
l=list(r)
print(l)
for row in l:
print(row[2])
382
s=0
del l[0]
print(l)
for row in l:
s=s+int(row[2])
print("total is",s)
f.close()
main()
create csv file or writing into csv format
=================================
csv.writer(csvfile)
==> this function return csvwriter object.
writerow() is method of writer object which is used
to write one row/list.
import csv
def main():
f=open("sales.csv","w",newline='')
wobj=csv.writer(f)
wobj.writerow(['name','sales'])
wobj.writerow(['naresh',60000])
wobj.writerow(['suresh',80000])
wobj.writerow(['kishore',45000])
f.close()
main()
writerows() this method write more than one row,
this multiple rows are represented using nested lists.
import csv
def main():
f=open("players.csv","w",newline='')
players=[]
n=int(input("enter how many players"))
for i in range(n):
p=[]
name=input("enter name")
383
runs=int(input("enter runs"))
p.append(name)
p.append(runs)
players.append(p)
wobj=csv.writer(f)
wobj.writerows(players)
f.close()
main()
eg:
import csv
def main():
f=open("players.csv","r")
robj=csv.reader(f)
players=list(robj)
print(players)
s=0
for row in players:
s=s+int(row[1])
print("Total Score",s)
main()
class csv.DictWriter(f, fieldnames)
Create an object which operates like a regular writer but maps dictionaries onto
output rows
import csv
def main():
sales_dict={'2015':[50000,7000,90000],'2016':[70000,9000,9000],'2017':
[80000,90000],'2018':[90000]}
print(sales_dict)
f=open("sales1.csv","w")
swobj=csv.DictWriter(f,fieldnames=['2015','2016','2017','2018'])
swobj.writeheader()
swobj.writerow(sales_dict)
f.close()
384
main()
24 and 25/08/2020
class csv.DictReader(f, fieldnames=None)
Create an object that operates like a regular reader but maps the information in each row to a dict whose
keys are given by the optional fieldnames parameter.
import csv
def main():
f=open("sales1.csv","r")
d=csv.DictReader(f)
l=list(d)
print(l)
main()
JSON file
========
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
It is easy for humans to read and write. It is easy for machines to parse and generate.
JSON is standard way of interchaning data between two different application and these applications are
written in same language or different language.
JSON is a text format that is completely language independent but uses conventions that are familiar
programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many
others. These properties make JSON an ideal data-interchange language.
inorder parse json data, python provide json module.
create the json file.
{"name":"naresh",
"course":["java","python"]}
save this file with student_details.json
# reading content of json file
import json
def main():
f=open("g:\\student_details.json","r")
d=json.load(f)
print(d)
385
print(d['name'])
print(d['course'])
f.close()
main()
# converting dict into json
import json
def main():
emp_dict={'empno':101,'ename':'kishore','salary':50000}
emp=json.dumps(emp_dict)
print(type(emp_dict))
print(type(emp))
print(emp_dict)
print(emp)
print(emp_dict["ename"])
main()
# writing dict into json file
import json
def main():
f=open("g:\\product.json","w")
p={'pname':'keyboard','price':3000}
json.dump(p,f)
f.close()
main()
OS module
=========
==> os module is used to interact with operating system (OR) this module allows python application to
communicate with operating system.
==> This module provides a portable way of using operating system dependent functionality.
1. creating directory or folder
os.mkdir(path)
Create a directory named path with numeric mode mode
import os
def main():
os.mkdir("g:\\folder1")
386
print("folder created")
main()
2. changing directory
os.chdir(path)
Change the current working directory to path.
3. os.getcwd()
Return a string representing the current working directory.
import os
def main():
print(os.getcwd())
os.chdir("g:\\folder1")
print(os.getcwd())
f=open("file1","w")
f.write("Hello Python")
f.close()
main()
4. os.listdir(path='.')
Return a list containing the names of the entries in the directory given by path
import os
def main():
l=os.listdir("g:\\project11am")
print(l)
print(len(l))
for name in l:
print(name)
main()
5. os.rmdir(path)
Remove (delete) the directory path. If the directory does not exist or is not empty, an FileNotFoundError
or an OSError .
import os
def main():
dname=input("Enter directory name")
try:
os.rmdir(dname)
387
print('directory deleted')
except FileNotFoundError:
print("Dictory not exists")
except OSError:
print("Directory not empty")
main()
6. os.rename(src, dst)
Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError .
import os
def main():
src_name=input("Enter source file name")
dest_name=input("Enter dest file name")
os.rename(src_name,dest_name)
print("file renamed")
main()
7. os.remove(path)
Remove (delete) the file path.
import os
def main():
fname=input("Enter filename to delete")
os.remove(fname)
print("File deleted")
main()
26-08-2020
re.search(pattern, string)
Scan through string looking for the first location where the regular expression pattern produces a match,
and return a corresponding match object. Return None if no position in the string matches the pattern.
Example1:
import re
def main():
str1="python is a programming language"
m1=re.search(r'is',str1)
print(m1)
388
m2=re.search(r'the',str1)
print(m2)
print(m1.span())
print(m1.group())
main()
Example2:
import re
def main():
str1="python java python java"
m=re.search(r'java',str1)
print(m)
print(m.span())
print(m.group())
main()
re.match(pattern, string)
If zero or more characters at the beginning of string match the regular expression pattern, return a
corresponding match object. Return None if the string does not match the pattern;
re.findall(pattern, string)
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-
right, and matches are returned in the order found.
Example3:
import re
def main():
str1="python java python java python"
l=re.findall(r'java',str1)
print(l)
m=re.match(r'p',str1)
print(m)
m=re.match(r'q',str1)
print(m)
main()
The special characters which are used to represent patterns
.(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been
specified, this matches any character including a newline.
389
import re
def main():
str1="this is string\npython"
l=re.findall(r'.',str1)
print(l)
str1 = "\npython"
m=re.match(r'.',str1)
if m==None:
print("String should not start with newline")
else:
print("valid")
main()
import re
def main():
str1="python is programming"
m=re.search(r'i.',str1)
if m!=None:
print(m.group())
print(m.span())
str2="py jy ny ppy jpy"
l=re.findall(r'.y',str2)
print(l)
main()
^ (Caret.) Matches the start of the string.
import re
def main():
names=['suresh','ramesh','kishore','\nrajesh']
for name in names:
m=re.search(r'^.',name)
if m!=None:
print(name)
main()
$ Matches the end of the string or just before the newline at the end of the string
import re
390
def main():
names=['rama rao','krishna rao','ramesh','kishore']
for name in names:
m=re.search(r'..o$',name)
if m!=None:
print(name)
main()
* Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are
possible.
import re
def main():
str1='abc abb acb a bca'
l=re.findall(r'ab*',str1)
print(l)
main()
+ Causes the resulting RE to match 1 or more repetitions of the preceding RE.
? Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
{m} Specifies that exactly m copies of the previous RE should be matched
{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match
as many repetitions as possible.
[] Used to indicate a set of characters. In a set:
匹haracters can be listed individually ['a','b','c']
紐anges of characters can be indicated by giving two characters and separating them by a '-', [A-
Z] [a-z] [0-9]
[A-Za-z0-9]
eg: date validation
def main():
d=input('input date')
m=re.search(r'[0-9]{2}-[0-9]{2}-[0-9]{4}',d)
if m!=None:
print(d,"is valid")
else:
print(d,"is invalid")
main()
391
eg: email validation
def main():
email=input("Enter mail-id")
m=re.search(r'[a-z0-9A-Z]+@[a-z]+\.[a-z]+',email)
if m!=None:
print(email,"is valid")
else:
print(email,"is invalid")
main()
27-08-2020
() ==> capture and group
Eg:
import re
def main():
str1="date of birth of a person is 01-02-2020"
m=re.search(r'([0-9]{2})-([0-9]{2})-([0-9]{4})',str1)
print(m)
print(m.group())
print(m.group(1))
print(m.group(2))
print(m.group(3))
main()
Eg:
import re
def main():
email="emailid is nareshit@gmail.com"
m=re.search(r'([a-z0-9A-Z]+)@([a-z]+\.[a-z]+)',email)
print(m.group())
print(m.group(1))
print(m.group(2))
main()
Special sequence characters or escape characters
==========================================
392
\A Matches only at the start of the string.
\b Matches the empty string, but only at the beginning or end of a word
import re
def main():
str1="the their they the"
l=re.findall(r'the',str1)
print(l)
l=re.findall(r'\bthe\b',str1)
print(l)
main()
\B Matches the empty string, but only when it is not at the beginning or end of a word
import re
def main():
str1 = "the their they the python"
l=re.findall(r'\Bthe\B',str1)
print(l)
main()
\d Matches any decimal digit; this is equivalent to [0-9].
import re
def main():
str1="python version 3.8"
m=re.search(r'\d',str1)
print(m.group())
l=re.findall(r'\d',str1)
print(l)
m=re.match(r'\d',str1)
print(m)
main()
import re
def main():
str1="mobile no 997766555"
m=re.search(r'\d{9}',str1)
print(m.group())
main()
393
\D Matches any character which is not a decimal digit
import re
def main():
str1="NareshIt MobileNO: 877665544"
l=re.findall(r'\D',str1)
print(l)
l=re.findall(r'\d',str1)
print(l)
main()
\s Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].
28-08-2020
\s Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].
\SMatches any character which is not a whitespace character. This is the opposite of \s.
import re
def main():
str1="python programming\nlanguage"
l=re.findall(r'\s',str1)
print(l)
l=re.findall(r'\S',str1)
print(l)
str2="python programming\tlangauge\nOOP"
l=re.findall(r'\s',str2)
print(l)
main()
\w
Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_].
\W Matches any character which is not a word character This is the opposite of \w
import re
def main():
uname=input("Enter username")
s=re.search(r'\W',uname)
if s==None:
394
print('valid user name')
else:
print('invalid username')
main()
\Z Matches only at the end of the string.
re.split(pattern, string, maxsplit=0)
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit
splits occur, and the remainder of the string is returned as the final element of the list.
import re
def main():
str1="python language\npython\tscripting\vlanguage"
l=re.split(r'\s',str1)
print(l)
main()
import re
def main():
str1="python,langauge:python;scripting.lagnauge"
l=re.split(r'[,:;\.]',str1)
print(l)
main()
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the
replacement repl. If the pattern isn’t found, string is returned unchanged
import re
def main():
str1="python is a programming langauge"
str2=re.sub(r'\s','-',str1)
print(str1)
print(str2)
str3="python is\na\tprogramming\rlangauge"
str4=re.sub(r'\s'," ",str3)
print(str3)
print(str4)
395
main()
Multithreading
============
Types Applications
================
1. Single task applications
2. Multitasking applications
==> A task is an operation performed program.
==> An application or program allows to perform one operation at a time is called single task application
or program.
def task1():
print("Inside task1")
def task2():
print("Inside task2")
def task3():
print("Inside task3")
def main():
task1()
task2()
task3()
main()
==> default flow of execution is seq. until task1() execution is completed task2() is not executed.
Multitasking applications
====================
==> an application which allows to perform more than one operation or task concurrently is called
multitasking.
==> In multitasking application each task is execution in a
separate path, this is called thread.
==> threads are used to develop multitasking applications.
==> thread is independent path of execution within program.
==> thread perform operation independent of other operations.
==> threads will be executed concurrently.
==> multitasking applications uses cpu idle time or resources.
==> python provide threading module, to develop multithreading applications.
396
31 Aug 2020
Multitasking applications
====================
==> an application which allows to perform more than one operation or task concurrently is called
multitasking.
==> In multitasking application each task is execution in a
separate path, this is called thread.
==> threads are used to develop multitasking applications.
==> thread is independent path of execution within program.
==> thread perform operation independent of other operations.
==> threads will be executed concurrently.
==> multitasking applications uses cpu idle time or resources.
==> python provide threading module, to develop multithreading applications.
How to create thread?
==> A thread is created by inheriting Thread class
==> A thread is created using callable object.
1. Creating thread by inheriting thread class.
syntax:
class <thread-class-name>(Thread):
def run(self):
statements
==> inherit Thread class and provide implementation or operation by overriding run() method of Thread
class.
==> thread execution is done by calling run method.
Scheduler
========
397
from threading import *
# even thread is used for generating even numbers
class EvenThread(Thread):
def run(self):
for n in range(1,20):
if n%2==0:
print("Even :",n)
class OddThread(Thread):
def run(self):
for n in range(1,20):
if n%2!=0:
print("Odd :",n)
def main():
e1=EvenThread()
o1=OddThread()
e1.start()
o1.start()
main()
# creating thread without inheriting Thread class
# create thread object and send as target
# easy to maintain, if any chages in functionality of thread
# not required to modify thread, change only functionlaity.
from threading import *
def even():
for n in range(20):
if n%2==0:
print("Even :",n)
def odd():
for n in range(20):
if n%2!=0:
print("Odd :",n)
398
def main():
t1=Thread(target=even)
t2=Thread(target=odd)
t1.start()
t2.start()
main()
start()
Start the thread’s activity.
run()
Method representing the thread’s activity.
name
A string used for identification purposes only. It has no semantics. Multiple threads may be given the same
name. The initial name is set by the constructor.
getName()
setName()
Old getter/setter API for name; use it directly as a property instead.
from threading import *
class AlphaThread(Thread):
def run(self):
for n in range(65,91):
print(self.getName(),chr(n))
def main():
t1=AlphaThread()
t2=AlphaThread()
t1.name="Naresh"
t2.name="Ramesh"
t1.start()
t2.start()
main()
join(timeout=None) ==> interrupted method
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called
terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
1thread ==> generating sum 10 numbers
399
2thread ==> use the sum generated 1thread
from threading import *
class SumThread(Thread):
def __init__(self):
super().__init__()
self.s=0
def run(self):
for n in range(1,20):
self.s=self.s+n
class PrintSumThread(Thread):
def __init__(self):
super().__init__()
self.st=SumThread()
def run(self):
self.st.start()
self.st.join()
print("sum is ",self.st.s)
def main():
p=PrintSumThread()
p.start()
main()
from threading import *
class HelloThread(Thread):
def run(self):
for i in range(1,10):
print("Hello")
class ByeThread(Thread):
def __init__(self):
super().__init__()
self.ht=HelloThread()
def run(self):
self.ht.start()
400
self.ht.join()
for n in range(1,10):
print("Bye")
def main():
bt=ByeThread()
bt.start()
main()
Thread Synchornization OR Thread Locking
01 sep 2020
Thread Synchornization OR Thread Locking
====================================
==> synchronization is process a thread acq lock of the object, so that other thread cannot perform operation
until this thread execution is completed.
==> when more than one thread operate on shared resource, when one thread is doing operation not
allowing another thread to peform operation is called synchronization.
==> this allows you to develop thread safe applications.
lock
===
class threading.Lock
The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to
acquire it block, until it is released; any thread may release it.
acquire(blocking=True, timeout=-1)
Acquire a lock, blocking or non-blocking.
release()
Release a lock. This can be called from any thread, not only the thread which has acquired the lock.
from threading import *
class Bus:
def __init__(self):
self.seats=40
self.l=Lock()
def reservation(self,name,s):
self.l.acquire()
401
for i in range(s):
self.seats=self.seats-1
print(name,"Your seats are reserved")
print(name,"availabl seats are",self.seats)
self.l.release()
class ReserveThread(Thread):
def __init__(self,b,s,name):
super().__init__()
self.bus=b
self.n=s
self.name=name
def run(self):
self.bus.reservation(self.name,self.n)
def main():
bus1=Bus()
t1=ReserveThread(bus1,10,"hemanth")
t2=ReserveThread(bus1,5,"Nilesh")
t3=ReserveThread(bus1,10,"Niyas")
t1.start()
t2.start()
t3.start()
main()
daemon thread
=============
02 Sept 2020
daemon thread
=============
daemon
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set
before start() is called, otherwise RuntimeError is raised
402
daemon thread is least priority thread.
this thread also called background thread.
this thread execution completed when all user thread execution is completed.
t1 t2
user thread daemon thread
t2.daemon=True
from threading import *
class Thread1(Thread):
def run(self):
for i in range(1,10):
print("Inside Thread1 ",i)
class Thread2(Thread):
def run(self):
for i in range(1,10):
print("Inside Thread2 ",i)
def main():
t1=Thread1()
t2=Thread2()
t1.daemon=True
t1.start()
t2.start()
main()
=====================================================================
Python Database Communication
==> Python is a programming language and every language is used as front end. database can be used as
backend for storing or saving data.
==> There are number of database libraries provided by database vendors inorder to communicate with
database.
python
program =============> python =======> Database
database communication
403
lib
python program ===> mysqlconnector_python ===> mysql database
python program ===> cx_Oracle ===> Oracle database
==> install mysqldatabase
https://dev.mysql.com/downloads/installer/
==> open mysQL 8.0 Command Line Client
How to create database in mysql?
==> Data will be stored inside database in the form of tables.
create database <database name>;
mysql> create database db1;
How to open created database ?
use <database-name>
mysql> use db2
Database changed
==> Every database support one langauge called SQL(Structured Query Language).
DDL (Data Definition Language)
create
alter
drop
DML (Data Manipulation Language)
insert
update
delele
DRL (Data Read Language)
select
TCL (Transaction Control langauge)
commit
rollback
how to create table?
==> inside database the data will be stored inside table.
==> table is collecton rows and columns.
create table <table-name>(<column-name> <data-type>,<column-name> <datatype>,
<column-name> <datatype>,..)
Mysql Datatypes
404
==============
int ==> integer
float ==> float
varchar ==> string
date ==> date
create table student(rollno int(5) primary key,
name varchar(20),
course varchar(20),
fee float(10,2));
How to insert values into table?
insert command is used to insert a row into database table.
insert into <table-name> values(value1,value2,value3,....)
insert into student values(101,'naresh','python',4000)
How to read data from database table?
select command used to read database database table
select * from <table-name>; ==> completed table data
select <colname>,<colname>,<colname> from <table-name>; ==> read content selected columns.
select * from student;
select rollno,name from student;
To read selected rows we can use where condition.
select * from student where rollno=101;
update command
==> inorder to replace values we use update command.
update <table-name> set <col-name>=<value>,<col-name>=<value>;
update <table-name> set <col-name>=<value> where <condition>;
delete command
=============
==> inorder to delete rows, we use delete command
delete from table-name; ==> this delete all rows
delete from table-name where <condition>; ==> delete selected rows
How python program communicate with mysql database?
==> mysql database provide a library called mysql-connector-python
pip install mysql-connector-python
Basic Steps to communicate with database.
405
1. Open Connection to Database
2. Send SQL statements( This done using cursor)
3. Get the results of SQL statements
4. close cursor
5. close connection
How to open/establish connection to database?
mysql.connector
mysql ==> package
connector ==> package
mysql.connector.connect() ==> connect() is a function, which establish connection to database and return
connection object.
406
This method executes the given database operation (query or command). The parameters found in the tuple
or dictionary params are bound to the variables in the operation. Specify variables using %s or %(name).
syntax: execute(command/operation,params=(value,value,value,..))
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
c=cn.cursor()
cmd="insert into student values(%s,%s,%s,%s)"
rno=int(input("Enter rollno"))
name=input("Enter name")
course=input("Enter course")
fee=float(input("Enter fee"))
c.execute(cmd,params=(rno,name,course,fee))
r=c.rowcount
print(r)
cn.commit()
cn.close()
main()
===============================================================
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
c=cn.cursor()
cmd="insert into student values(%s,%s,%s,%s)"
ans="yes"
while ans!="no":
rno=int(input("Enter rollno"))
name=input("Enter name")
course=input("Enter course")
407
fee=float(input("Enter fee"))
c.execute(cmd,params=(rno,name,course,fee))
r=c.rowcount
print(r)
ans=input("Continue yes/no")
cn.commit()
cn.close()
main()
=====================================================================
# write a program to update course and fees of student
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
c=cn.cursor()
cmd="update student set course=%s,fee=%s where rollno=%s"
rno=int(input("Enter rollno"))
course=input("Enter new course")
f=float(input("Enter Fee"))
c.execute(cmd,(course,f,rno))
rc=c.rowcount
if rc==0:
print("no rows are updated")
else:
print("details are updated")
cn.commit()
cn.close()
main()
====================================================================
# write a program to delete row from database table
import mysql.connector
def main():
cn=mysql.connector.connect(user="root",password="root",database="db2")
408
c=cn.cursor()
cmd="delete from student where rollno=%s"
rno=int(input("Enter rollno"))
c.execute(cmd,params=(rno,))
rc=c.rowcount
if rc==0:
print("invalid rollno")
else:
print("student deleted from databse table")
cn.commit()
cn.close()
main()
=====================================================================
Reading data from database table
============================
==> select command read data from databse table and store result into cursor.
==> to read/fetch this data cursor provide the following methods.
1. fetchone()
2. fetchmany(n)
3. fetchall()
fetchone()
==> This method retrieves the next row of a query result set and returns a single sequence, or None if no
more rows are available
import mysql.connector
def main():
cn=mysql.connector.connect(database="db2",user="root",password="root")
c=cn.cursor()
cmd="select * from student"
c.execute(cmd)
row1=c.fetchone()
row2=c.fetchone()
row3=c.fetchone()
row4=c.fetchone()
409
print(row1)
print(row2)
print(row3)
print(row4)
main()
fetchmany(n)
===========
==> this required n value which is number of rows.
==> this method also return list of tuples where each tuple is one row.
import mysql.connector
def main():
cn=mysql.connector.connect(database="db2",user="root",password="root")
410
c=cn.cursor()
cmd="select * from student"
c.execute(cmd)
rows=c.fetchmany(2)
print(rows)
cn.close()
main()
AddressBook
===========
person_table
===========
name ==> varchar(20) ==> primary key
hno ==> varchar(15)
street ==> varchar(20)
city ==> varchar(20)
state ==> varchar(20)
phoneno ==> varchar(12)
*****Address Book****
1. Adding Address
2. Updating Address
3. Delete Address
4. Display Address
5. View All Addresses
6. Exit
Enter your option :
Communicating with Oracle Database
===============================
==> python uses library called cx_Oracle.
==> this library is provided oracle vendor.
==> using cx_Oracle we can able to communicate oracle database.
pip install cx_Oracle
Build one case study based on cursors and sql concepts
Already discussed in class (some photos are in mobile)
411
05th Sept 2020
Jupyter Notebook
=============
Q: What is jupyter notebook?
==> jupyter notebook is a IDE.
==> jupyter notebook is a web application which allow create documents which contain live code
,equations, visualizations and text.
==> install anacond
==> with anaconda is python distribution which is used for developing datascience related applications or
projects.
==> when anaconda is installed, with this will get,
python software, jupyter,spyder ide's
==> all datascience related tools(numpy,pandas,matplotlib,....)
numpy
======
Q: What is numpy?
==> numpy stands for numerical python.
==> numpy is an open source library.
==> numpy library provide multidim array objects.
==> list is not array. it is collection where group all the objects. becoz list does not have dim. list can hold
difference types of data(hetrogenious). it is dynamic in size.
==> array is a collection of similer type data elements. array is having dim.
412
in array data is stored as scalar type(value).
==> list data is stored as objects, it occupy more space. it is not eff.
==> in array data stored is as value but not as objects, it is more eff.
How to create numpy array?
array()
=====
==> array() is predefined function which create an ndarray object.
==> ndarray is class.
==> the array created in numpy is represented as ndarray object.
array(object,dtype)
object ==> it is an array or any sequence.
dtype ==> datatype which descibe datatype of array object.
import numpy as np
a1=np.array([10,20,30,40,50])
print(a1)
print(type(a1))
[10 20 30 40 50]
<class 'numpy.ndarray'>
=========================================
a2=np.array([[10,20],[30,40]])
print(a2)
print(type(a2))
[[10 20]
[30 40]]
<class 'numpy.ndarray'>
==============================================
numpy datatypes
signed integer datatypes : +ve and -ve
int8 ==> -128 to +127
int16 ==> -32768 to +32767
int32
int64
unsigned integer datatype : +ve
413
uint8
uint16
uint32
uint64
float ==> real numbers or floating point number
float16
float 32
float64
complex ==> complex numbers
=============================================================
a3=np.array([10,20,30,40,50],dtype=np.int8)
print(a3)
[10 20 30 40 50]
=======================================================
a4=np.array([200,300,400,500],dtype=np.int8)
print(a4)
[ -56 44 -112 -12]
========================================================
a5=np.array([1.5,2.5,3.5],dtype=np.float)
print(a5)
[1.5 2.5 3.5]
========================================================
a6=np.array([10,20,30,40,50],dtype=np.float)
print(a6)
[10. 20. 30. 40. 50.]
==========================================================
a7=np.array(['naresh','suresh','rajesh'])
print(a7)
print(a7.dtype)
==========================================================
dtype() funcion is used create user defined datatype.
dtype([(fieldname,datatype),(fieldname,datatype),(fieldname,datatype)])
emptype=np.dtype([('empno','i1'),('ename','S20'),('salary','f4')])
emparray=np.array([(101,'suresh',5000.0),(102,'kishore',8000.0)],dtype=emptype)
414
print(emparray)
[(101, b'suresh', 5000.) (102, b'kishore', 8000.)]
=====================================================================
shape
=====
==> shape is a property of numpy array.
==> it is a property or attribute of numpy array object.
==> this attribute return dim of array of object.
==> it return dim as tuple.
array1=np.array([10,20,30,40,50])
array2=np.array([[10,20,30],[40,50,60]])
print(array1)
print(array2)
print(array1.shape)
print(array2.shape)
==> it is used to modify or read shape of array.
array3=np.array([10,20,30,40,50,60,70,80,90])
print(array3)
array3.shape=(3,3)
print(array3)
reshape()
========
==> reshape function modify shape and return modification as new array.
array4=np.array([10,20,30,40,50,60,70,80,90])
print(array4)
array5=array4.reshape(3,3)
print(array4)
print(array5)
ndim
====
==> this attribute return number of array dim.
array6=np.array([10,20,30,40,50])
print(array6)
print(array6.ndim)
415
array7=np.array([[10,20],[30,40]])
print(array7)
print(array7.ndim)
itemsize
=======
This attribute return the size of each item of array in bytes.
array8=np.array([10,20,30,40,50],dtype=np.int8)
print(array8)
print(array8.itemsize)
array9=np.array([1.5,2.5,3.5],dtype=np.float16)
print(array9)
print(array9.itemsize)
Indexing ans slicing
================
==> indexing allows to read only one value.
==> slicing allows to read more than one value.
==> array always follows zero based index.
416
print(a)
print(a[1:])
print(a[1::2])
print(a[-1::-1])
... is called ellipsis operator which is used to read row or column.
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print(a[...,1])
print(a[...,0])
print(a[...,2])
print(a[0,...])
print(a[1,...])
print(a[2,...])
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print(a[...,1:])
print(a[...,0:2])
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
for row in a:
for col in row:
print(col)
====================================================================
Creating numpy array using other functons
1. empty() ==> this function create ndarray without init, with the give shape
a=np.empty([3,3],dtype=np.int)
print(a)
b=np.empty([2,3],dtype=np.int)
print(b)
==> it will create an array with unknown value.
2. zeros() ==> this function create ndarray with zero values, with given shape
a=np.zeros([3,3],dtype=np.int)
print(a)
b=np.zeros([2,4])
print(b)
417
3. ones() ==> this function create ndarray with 1 values, with given shape.
a=np.ones([3,3])
b=np.ones([3,3],dtype=np.int)
print(a)
print(b)
4. arange() ==> this function create ndarray object using range.
arange(start,stop,step,dtype=<type>)
a=np.arange(1,11)
print(a)
a.shape=(2,5)
print(a)
a.shape=(5,2)
print(a)
b=np.arange(1,11,2)
print(b)
b.shape=(5,1)
print(b)
5. linspace() : it is similer to arange(), in the place of step, we define number of elements or values. This
linespace function create ndarray object using start and stop evenly it generate values.
a=np.linspace(1,50,6)
print(a)
b=np.linspace(1,10,6)
print(b)
a.shape=(2,3)
b.shape=(3,2)
print(a)
print(b)
5. logspace() :
logspace(start,stop,num,base=10)
==> this function return ndarray object with start,stop and number of values.
==> it generate elements using log. default base 10.
a=np.logspace(1,50,5)
print(a)
=====================================================================
418
broadcasting
==> broadcasting is process of converting result martix into specific shape when perform arithmetic
operations.
==> if two arrays are with same shape, it does not perform broadcasting.
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([[5,6,7],[8,9,5]])
matrix3=matrix1+matrix2
print(matrix1)
print(matrix2)
print(matrix3)
[1,2,3 [5,6,7 [6,8,10
4,5,6] + 8,9,5] = 12,14,11]
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([1,2,3])
matrix3=matrix1+matrix2
print(matrix1)
print(matrix2)
print(matrix3)
output:
[[1 2 3]
[4 5 6]]
[1 2 3]
[[2 4 6]
[5 7 9]]
import numpy as np
419
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([[4,5,6],[7,8,9]])
matrix3=matrix1+matrix2
print(matrix1)
print(matrix2)
print(matrix3)
matrix4=matrix1.__add__(matrix2)
print(matrix4)
==============================================================
matrix1=np.array([[1,2,3],[4,5,6]])
matrix2=np.array([[4,5,6],[7,8,9]])
matrix3=matrix1+matrix2
matrix4=matrix1-matrix2
matrix5=matrix1*matrix2
print(matrix1)
print(matrix2)
print(matrix3)
print(matrix4)
print(matrix5)
===============================================================
The following opertions belongs to string (OR) vectorized strings
add() ==> return concat of strings. it will return array by concat element wise.
array1=np.array(['abc','xyz','pqr'])
array2=np.array(['mno','bca','wqe'])
array3=np.char.add(array1,array2)
print(array1)
print(array2)
print(array3)
420
lower() ==> return all the elements/string of array into lowercase
title() ==> return all the elements/string of array convert into title case
capitalize() ==> return all the elementsstring of array convert into capitalize, first letter word is converted
uppercase.
array1=np.array(['java','python','oracle','.net'])
array2=np.char.upper(array1)
print(array1)
print(array2)
array3=np.char.lower(array2)
print(array3)
array4=np.char.capitalize(array2)
print(array4)
array5=np.array(['python language','oracle database'])
array6=np.char.title(array5)
print(array5)
print(array6)
====================================================================
Adding and removing elements from numpy array
append() ==> append the values at the end of array
nump.append(array,values,axis)
array ===> input array
values ==> list of values
axis ==> axis is row or col ==> axis-0 or axis-1
array and values are required arguments.
array1=np.array([10,20,30,40,50])
print(array1)
array2=np.append(array1,[60,70,80])
print(array2)
array3=np.array([[1,2,3],[4,5,6]])
array4=np.append(array3,[[7,8,9]],axis=0)
print(array3)
print(array4)
array5=np.append(array3,[[9,8,7],[1,2,3]],axis=1)
421
print(array5)
==============================================================
numpy.delete()
=============
numpy.delete(arr, obj, axis=None)
Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those
entries not returned by arr[obj].
import numpy as np
def main():
array1=np.array([10,20,30,40,50,60,70,80,90,100])
print(array1)
array2=np.where(array1<=50)
print(array2)
array3=array1.take(array2)
print(array3)
main()
numpy.genfromtxt
===============
Load data from a text file, with missing values handled as specified.
import numpy as np
def main():
a=np.genfromtxt("d:\\studentdata.csv",dtype=None,skip_header=1,delimiter=",")
422
print(a)
for row in a:
print(row[0],row[1],row[2],row[3])
main()
numpy.tofile()
===========
Write array to a file as text or binary (default).
import numpy as np
def main():
array1=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(array1)
array1.tofile("file1",sep=",")
print("array is stored inside the file")
array2=np.loadtxt("file1",delimiter=",",dtype=np.int8)
print(array2)
array2.shape=(3,3)
print(array2)
main()
numpy.random
============
import numpy as np
def main():
a1=np.random.random(5)
print(a1)
print(a1[0],a1[1],a1[2],a1[3],a1[4])
a2=np.random.randint(10,20,(3,3))
print(a2)
a3=np.random.normal(0,1,5)
print(a3)
main()
Pandas
=======
423
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool/library,
built on top of the Python programming language.
Pandas is a high-level data manipulation tool developed by Wes McKinney.
1. Series (1-D)
2. DataFrame (2-D)
3. Panel (3-D)
424
6. Provide the functions for finding missing data
7. Operations for inserting and removing data rows and columns.
==> Pandas does not comes with python software.
builtins,sys,os,tkinter,io,.... default modules comes with python softwares.
==> This is third party lib. to install this.
pip install pandas
Q: What is data structure?
==> data structure define set of rules and reg for organizing of data in memory.
==> by following these rules and reg we can solve given problem easy.
Series
======
==> Series is one dim labeld array. Series can hold
any type data (integer,float,complex,string,object,...)
==> The axis labels are called index.
==> Series allows homgenious data(similer type).
==> Series size is immutable(the size of series cannot incr or descr after creation).
==> Data stored inside Series are mutable.
==> Series is a predefined datatype which is used to represent Series object.
==> Series can be created in different ways.
1. array
2. dict
3. scalar values or constants or literals.
import pandas as pd
# creating empty Series
s=pd.Series()
print(s)
==> If the datatype is not defined at the time creating Series, the default datatype is Float.
creating series using ndarray
========================
=> we can create series using numpy array.
import pandas as pd
import numpy as np
data=np.array([10,20,30,40,50])
s=pd.Series(data) # creating Series using ndarray
425
print(s)
print(data)
data=np.array(['naresh','suresh','kishore'])
s=pd.Series(data)
print(s)
==================================================================
import pandas as pd
import numpy as np
data=np.array([10,20,30,40,50])
s=pd.Series(data) # creating Series using ndarray
print(s)
print(data)
data=np.array(['naresh','suresh','kishore'])
s=pd.Series(data,index=['name1','name2','name3'])
print(s)
sales_data=np.array([10000,20000,30000,40000])
s=pd.Series(sales_data,index=[2016,2017,2018,2019])
print(s)
creating Series using dictionary
==========================
in dictionary key is customized index, which is mapped with value
import pandas as pd
dict={'java':4000,'python':5000,'C++':3000}
s1=pd.Series(dict)
print(s1)
s2=pd.Series(dict,index=['C++','java','python','oracle'])
print(s2)
==> Missing element/value is defined with NaN( Not a Number)
import pandas as pd
dict1={1:1000,2:2000,3:4000,5:5000}
s1=pd.Series(dict1)
print(s1)
s2=pd.Series(dict1,index=[10,20,30,40,50])
print(s2)
426
Creating Series using Scalar value
=============================
==> Pandas allows to create Series using Scalar value.
==> Scalar value is an individual value.
==> If index is defined this value repeated to match with length
of index.
import pandas as pd
s=pd.Series(45,index=[1,2,3,4,5])
print(s)
Accessing elements/data from Series
===============================
==> Reading elements from Series is done in different ways.
1. Using its positions
2. Using its labels/index
3. Using slicling
==> positions are default index, every element pos starts at 0.
==> custome index is called labels
import pandas as pd
import numpy as np
s1=pd.Series(np.array([100,200,300,400,500]))
print(s1)
print(s1[0],s1[1],s1[2],s1[3],sep=',')
s2=pd.Series(np.array([100,200,300,400,500]),index=['a','b','c','d','e'])
print(s2)
print(s2['a'],s2['b'],s2['c'],sep=',')
print(s2[0],s2[1],s2[2],sep=',')
#print(s2['f'])
#print(s2[10])
import pandas as pd
import numpy as np
s=pd.Series(np.array([100,200,300,400,500]),index=[0,1,2,3,4])
print(s[0],s[1],s[2])
Inoder to read more than one value we use slicing.
import pandas as pd
427
import numpy as np
s=pd.Series(np.array([10,20,30,40,50]))
print(s)
print(s[:3])
print(s[-3:])
print(s[2:4])
print(s[-1::-1])
reading more than one value using pos and indexes.
these pos or index are represented as list.
import numpy as np
import pandas as pd
s=pd.Series(np.array([10,20,30,40,50]),index=['a','b','c','d','e'])
print(s)
print(s[['a','b','e']])
print(s[[0,1,2]])
Binary Operations of Series
======================
==> Series provide the following methods to perform binary opeations.
add() ==> This method is for adding two series
sub() ==> This method is for subtract two series
mul() ==> This method is for multiplying series
sum() ==> This return sum of elements of series
prod() ==> This return product of values of elements
mean() ==> return the mean values.
div() ==> This method is used to divide two series
count() ==> return the length of series
combine_first() ==> combine two series into one
import pandas as pd
s1=pd.Series([1,2,3,4,5])
print(s1)
s2=pd.Series([6,7,8,9,10])
print(s2)
s3=s1.add(s2)
print(s3)
428
s4=s2.sub(s1)
print(s4)
s5=s1.mul(s2)
print(s5)
sr1=pd.Series([1,2,3])
sr2=pd.Series([4,5,6,7,8])
sr3=sr1.add(sr2,fill_value=0)
print(sr3)
sr4=sr1.add(1)
print(sr4)
import pandas as pd
sales_2018=pd.Series([1000,2000,3000,4000,5000,6000],index=['jan','feb','mar','apr','may','jun'])
sales_2019=pd.Series([4000,5000,6000,7000,8000,9000],index=['jan','feb','mar','apr','may','jun'])
total_sales=sales_2018.add(sales_2019)
print(sales_2018)
print(sales_2019)
print(total_sales)
diff_sales=sales_2019.sub(sales_2018)
print(diff_sales)
sales_2018.combine_first(sales_2019)
print(sales_2018)
DataFrame
=========
==> DataFrame is 2D array.
==> DataFrame allows represent data in table format
==> DataFrame is collection of rows and columns.
==> DataFrame allows custom labels for rows and columns
==> DataFrame is an imp data structure of pandas, it allows
organize data in rows and columns.
How to create DataFrame?
==> DataFrame can be created using the following methods.
1. Lists
2. dict
3. Series
429
4. numpy arrays
5. existing DataFrame
==> Pandas provide DataFrame type/class, which can be used to create DataFrame.
How to create DataFrame using lists
==============================
import pandas as pd
# creating empty dataframe
df1=pd.DataFrame()
print(df1)
# creating dataframe with one column
list1=[10,20,30,40,50]
df2=pd.DataFrame(list1)
print(df2)
# creating dataframe with multiple columns
list_courses=[['python',4000],['java',2000],['oracle',1000]]
df3=pd.DataFrame(list_courses,columns=['coursename','fees'],dtype=float)
print(df3)
# creating dataframe using dictionary
dict1={'coursename':['python','oracle','java','c','c++'],'fee':[4000,1000,2000,1000,1500]}
df4=pd.DataFrame(dict1,columns=['coursename','fee'])
print(df4)
# creating dataframe using Series
s1=pd.Series(['python','oracle','java'],index=['a','b','c'])
s2=pd.Series([4000,1000,2000],index=['a','b','c'])
dict1={'courses':s1,'fee':s2}
df5=pd.DataFrame(dict1)
print(df5)
# creating dataframe using Series
s1=pd.Series(['python','oracle','java','c','c++'])
s2=pd.Series([4000,1000,2000,1000,1500,3000,2000])
dict1={'courses':s1,'fee':s2}
df5=pd.DataFrame(dict1)
print(df5)
import pandas as pd
430
df=pd.read_csv("d:\\product.csv")
print(df)
Manipulating rows and columns
==========================
selecting column
=============
==> column is identified with the name.
==> column can be read using column name.
dataframe['column-name']
import pandas as pd
df=pd.read_csv("/content/employee.csv")
print(df)
print(df['Empno'],df['Ename'])
adding column
============
==> the new column can be added with the following syntax.
dataframe['column-name']=[column values are created using series or dict]
dict1={'coursename':['python','oracle','java','c','c++'],'fee':[4000,1000,2000,1000,1500]}
df4=pd.DataFrame(dict1,columns=['coursename','fee'])
print(df4)
df4['duration']=pd.Series([1,2,3,4,5])
print(df4)
df4['col1']=pd.Series(['one','two','three','four','five'])
print(df4)
import tkinter as tk
from tkinter import messagebox
from time import gmtime, strftime
431
def is_number(s):
try:
float(s)
return 1
except ValueError:
return 0
def check_acc_nmb(num):
try:
fpin=open(num+".txt",'r')
except FileNotFoundError:
messagebox.showinfo("Error","Invalid Credentials!\nTry Again!")
return 0
fpin.close()
return
def home_return(master):
master.destroy()
Main_Menu()
def write(master,name,oc,pin):
f1=open("Accnt_Record.txt",'r')
accnt_no=int(f1.readline())
accnt_no+=1
f1.close()
432
f1=open("Accnt_Record.txt",'w')
f1.write(str(accnt_no))
f1.close()
fdet=open(str(accnt_no)+".txt","w")
fdet.write(pin+"\n")
fdet.write(oc+"\n")
fdet.write(str(accnt_no)+"\n")
fdet.write(name+"\n")
fdet.close()
frec=open(str(accnt_no)+"-rec.txt",'w')
frec.write("Date Credit Debit Balance\n")
frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+oc+"
"+oc+"\n")
frec.close()
def crdt_write(master,amt,accnt,name):
if(is_number(amt)==0):
messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
master.destroy()
return
fdet=open(accnt+".txt",'r')
pin=fdet.readline()
camt=int(fdet.readline())
fdet.close()
amti=int(amt)
cb=amti+camt
433
fdet=open(accnt+".txt",'w')
fdet.write(pin)
fdet.write(str(cb)+"\n")
fdet.write(accnt+"\n")
fdet.write(name+"\n")
fdet.close()
frec=open(str(accnt)+"-rec.txt",'a+')
frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+str(amti)+"
"+str(cb)+"\n")
frec.close()
messagebox.showinfo("Operation Successfull!!","Amount Credited Successfully!!")
master.destroy()
return
def debit_write(master,amt,accnt,name):
if(is_number(amt)==0):
messagebox.showinfo("Error","Invalid Credentials\nPlease try again.")
master.destroy()
return
fdet=open(accnt+".txt",'r')
pin=fdet.readline()
camt=int(fdet.readline())
fdet.close()
if(int(amt)>camt):
messagebox.showinfo("Error!!","You dont have that amount left in your
account\nPlease try again.")
else:
amti=int(amt)
cb=camt-amti
fdet=open(accnt+".txt",'w')
fdet.write(pin)
fdet.write(str(cb)+"\n")
434
fdet.write(accnt+"\n")
fdet.write(name+"\n")
fdet.close()
frec=open(str(accnt)+"-rec.txt",'a+')
frec.write(str(strftime("[%Y-%m-%d] [%H:%M:%S] ",gmtime()))+" "+"
"+str(amti)+" "+str(cb)+"\n")
frec.close()
messagebox.showinfo("Operation Successfull!!","Amount Debited Successfully!!")
master.destroy()
return
def Cr_Amt(accnt,name):
creditwn=tk.Tk()
creditwn.geometry("600x300")
creditwn.title("Credit Amount")
creditwn.configure(bg="orange")
fr1=tk.Frame(creditwn,bg="blue")
l_title=tk.Message(creditwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(creditwn,relief="raised",text="Enter Amount to be credited: ")
e1=tk.Entry(creditwn,relief="raised")
l1.pack(side="top")
e1.pack(side="top")
b=tk.Button(creditwn,text="Credit",relief="raised",command=lambda:crdt_write(creditwn,e1.g
et(),accnt,name))
b.pack(side="top")
creditwn.bind("<Return>",lambda x:crdt_write(creditwn,e1.get(),accnt,name))
def De_Amt(accnt,name):
debitwn=tk.Tk()
435
debitwn.geometry("600x300")
debitwn.title("Debit Amount")
debitwn.configure(bg="orange")
fr1=tk.Frame(debitwn,bg="blue")
l_title=tk.Message(debitwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(debitwn,relief="raised",text="Enter Amount to be debited: ")
e1=tk.Entry(debitwn,relief="raised")
l1.pack(side="top")
e1.pack(side="top")
b=tk.Button(debitwn,text="Debit",relief="raised",command=lambda:debit_write(debitwn,e1.ge
t(),accnt,name))
b.pack(side="top")
debitwn.bind("<Return>",lambda x:debit_write(debitwn,e1.get(),accnt,name))
def disp_bal(accnt):
fdet=open(accnt+".txt",'r')
fdet.readline()
bal=fdet.readline()
fdet.close()
messagebox.showinfo("Balance",bal)
def disp_tr_hist(accnt):
disp_wn=tk.Tk()
disp_wn.geometry("900x600")
436
disp_wn.title("Transaction History")
disp_wn.configure(bg="orange")
fr1=tk.Frame(disp_wn,bg="blue")
l_title=tk.Message(disp_wn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
fr1=tk.Frame(disp_wn)
fr1.pack(side="top")
l1=tk.Message(disp_wn,text="Your Transaction
History:",padx=100,pady=20,width=1000,bg="blue",fg="orange",relief="raised")
l1.pack(side="top")
fr2=tk.Frame(disp_wn)
fr2.pack(side="top")
frec=open(accnt+"-rec.txt",'r')
for line in frec:
l=tk.Message(disp_wn,anchor="w",text=line,relief="raised",width=2000)
l.pack(side="top")
b=tk.Button(disp_wn,text="Quit",relief="raised",command=disp_wn.destroy)
b.pack(side="top")
frec.close()
def logged_in_menu(accnt,name):
rootwn=tk.Tk()
rootwn.geometry("1600x500")
rootwn.title("UNITED BANK-"+name)
rootwn.configure(background='orange')
fr1=tk.Frame(rootwn)
fr1.pack(side="top")
l_title=tk.Message(rootwn,text="SIMPLE BANKING\n
SYSTEM",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor
="center")
l_title.config(font=("Courier","50","bold"))
437
l_title.pack(side="top")
label=tk.Label(text="Logged in as:
"+name,relief="raised",bg="black",fg="white",anchor="center",justify="center")
label.pack(side="top")
img2=tk.PhotoImage(file="credit.gif")
myimg2=img2.subsample(2,2)
img3=tk.PhotoImage(file="debit.gif")
myimg3=img3.subsample(2,2)
img4=tk.PhotoImage(file="balance1.gif")
myimg4=img4.subsample(2,2)
img5=tk.PhotoImage(file="transaction.gif")
myimg5=img5.subsample(2,2)
b2=tk.Button(image=myimg2,command=lambda: Cr_Amt(accnt,name))
b2.image=myimg2
b3=tk.Button(image=myimg3,command=lambda: De_Amt(accnt,name))
b3.image=myimg3
b4=tk.Button(image=myimg4,command=lambda: disp_bal(accnt))
b4.image=myimg4
b5=tk.Button(image=myimg5,command=lambda: disp_tr_hist(accnt))
b5.image=myimg5
img6=tk.PhotoImage(file="logout.gif")
myimg6=img6.subsample(2,2)
b6=tk.Button(image=myimg6,relief="raised",command=lambda: logout(rootwn))
b6.image=myimg6
b2.place(x=100,y=150)
b3.place(x=100,y=220)
b4.place(x=900,y=150)
b5.place(x=900,y=220)
b6.place(x=500,y=400)
438
def logout(master):
def check_log_in(master,name,acc_num,pin):
if(check_acc_nmb(acc_num)==0):
master.destroy()
Main_Menu()
return
def log_in(master):
master.destroy()
loginwn=tk.Tk()
loginwn.geometry("600x300")
loginwn.title("Log in")
loginwn.configure(bg="orange")
fr1=tk.Frame(loginwn,bg="blue")
l_title=tk.Message(loginwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(loginwn,text="Enter Name:",relief="raised")
439
l1.pack(side="top")
e1=tk.Entry(loginwn)
e1.pack(side="top")
l2=tk.Label(loginwn,text="Enter account number:",relief="raised")
l2.pack(side="top")
e2=tk.Entry(loginwn)
e2.pack(side="top")
l3=tk.Label(loginwn,text="Enter your PIN:",relief="raised")
l3.pack(side="top")
e3=tk.Entry(loginwn,show="*")
e3.pack(side="top")
b=tk.Button(loginwn,text="Submit",command=lambda:
check_log_in(loginwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
b.pack(side="top")
b1=tk.Button(text="HOME",relief="raised",bg="black",fg="white",command=lambda:
home_return(loginwn))
b1.pack(side="top")
loginwn.bind("<Return>",lambda
x:check_log_in(loginwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
def Create():
crwn=tk.Tk()
crwn.geometry("600x300")
crwn.title("Create Account")
crwn.configure(bg="orange")
fr1=tk.Frame(crwn,bg="blue")
l_title=tk.Message(crwn,text="UNITED
BANK",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor="c
enter")
l_title.config(font=("Courier","50","bold"))
l_title.pack(side="top")
l1=tk.Label(crwn,text="Enter Name:",relief="raised")
440
l1.pack(side="top")
e1=tk.Entry(crwn)
e1.pack(side="top")
l2=tk.Label(crwn,text="Enter opening credit:",relief="raised")
l2.pack(side="top")
e2=tk.Entry(crwn)
e2.pack(side="top")
l3=tk.Label(crwn,text="Enter desired PIN:",relief="raised")
l3.pack(side="top")
e3=tk.Entry(crwn,show="*")
e3.pack(side="top")
b=tk.Button(crwn,text="Submit",command=lambda:
write(crwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
b.pack(side="top")
crwn.bind("<Return>",lambda x:write(crwn,e1.get().strip(),e2.get().strip(),e3.get().strip()))
return
def Main_Menu():
rootwn=tk.Tk()
rootwn.geometry("1600x500")
rootwn.title("UNITED Bank")
rootwn.configure(background='orange')
fr1=tk.Frame(rootwn)
fr1.pack(side="top")
bg_image = tk.PhotoImage(file ="pile1.gif")
x = tk.Label (image = bg_image)
x.place(y=-400)
l_title=tk.Message(text="SIMPLE BANKING\n
SYSTEM",relief="raised",width=2000,padx=600,pady=0,fg="white",bg="black",justify="center",anchor
="center")
l_title.config(font=("Courier","50","bold"))
441
l_title.pack(side="top")
imgc1=tk.PhotoImage(file="new.gif")
imglo=tk.PhotoImage(file="login.gif")
imgc=imgc1.subsample(2,2)
imglog=imglo.subsample(2,2)
b1=tk.Button(image=imgc,command=Create)
b1.image=imgc
b2=tk.Button(image=imglog,command=lambda: log_in(rootwn))
b2.image=imglog
img6=tk.PhotoImage(file="quit.gif")
myimg6=img6.subsample(2,2)
b6=tk.Button(image=myimg6,command=rootwn.destroy)
b6.image=myimg6
b1.place(x=800,y=300)
b2.place(x=800,y=200)
b6.place(x=920,y=400)
rootwn.mainloop()
Main_Menu()
442
root=Tk() #Main window
f=Frame(root)
frame1=Frame(root)
frame2=Frame(root)
frame3=Frame(root)
root.title("Simple Employee Record System")
root.geometry("830x395")
root.configure(background="Black")
scrollbar=Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
def emp_dict(*args): #To add a new entry and check if entry already exist in excel sheet
#print("done")
workbook_name="sample.xlsx"
workbook=xlrd.open_workbook(workbook_name)
worksheet=workbook.sheet_by_index(0)
wb=load_workbook(workbook_name)
page=wb.active
p=0
443
for i in range(worksheet.nrows):
for j in range(worksheet.ncols):
cellvalue=worksheet.cell_value(i,j)
print(cellvalue)
sheet_data.append([])
sheet_data[p]=cellvalue
p+=1
print(sheet_data)
fl=firstname.get()
fsl=fl.lower()
ll=lastname.get()
lsl=ll.lower()
if (fsl and lsl) in sheet_data:
print("found")
messagebox.showerror("Error","This Employee already exist")
else:
print("not found")
for info in args:
page.append(info)
messagebox.showinfo("Done","Successfully added the employee record")
wb.save(filename=workbook_name)
def add_entries(): #to append all data and add entries on click the button
a=" "
f=firstname.get()
f1=f.lower()
l=lastname.get()
l1=l.lower()
d=dept.get()
d1=d.lower()
de=designation.get()
de1=de.lower()
list1=list(a)
444
list1.append(f1)
list1.append(l1)
list1.append(d1)
list1.append(de1)
emp_dict(list1)
445
frame1.configure(background="Red")
frame1.pack(pady=10)
446
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)
def search_emp(): #can implement search by 1st name,last name,emp id, designation
clear_all()
emp_first_name=Label(frame3,text="Enter first name of the employee",bg="red",fg="white") #to take
user input to seach
emp_first_name.grid(row=1,column=1,padx=10)
e8=Entry(frame3,textvariable=searchfirstname)
e8.grid(row=1,column=2,padx=10)
e8.focus()
emp_last_name=Label(frame3,text="Enter last name of the employee",bg="red",fg="white")
emp_last_name.grid(row=2,column=1,padx=10)
e9=Entry(frame3,textvariable=searchlastname)
e9.grid(row=2,column=2,padx=10)
search_button=Button(frame3,text="Click to search",command=search_entry)
search_button.grid(row=3,column=2,pady=10)
frame3.configure(background="Red")
frame3.pack(pady=10)
447
def search_entry():
sf=searchfirstname.get()
ssf1=sf.lower()
print(ssf1)
sl=searchlastname.get()
ssl1=sl.lower()
print(ssl1)
path="sample.xlsx"
wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(0)
448
label2.pack(side=LEFT,pady=10)
button1=Button(f,text="Add", background="Brown", fg="White", command=add_info, width=8)
button1.pack(side=LEFT,ipadx=20,pady=10)
button2=Button(f,text="Remove", background="Brown", fg="white", command=remove_emp, width=8)
button2.pack(side=LEFT,ipadx=20,pady=10)
button3=Button(f,text="Search", background="Brown", fg="White", command=search_emp, width=8)
button3.pack(side=LEFT,ipadx=20,pady=10)
button6=Button(f,text="Close", background="Brown", fg="White", width=8, command=root.destroy)
button6.pack(side=LEFT,ipadx=20,pady=10)
f.configure(background="Black")
f.pack()
root.mainloop()
449