Adv Python
Adv Python
REDDY
ADVANCE PYTHON
Object Oriented Programming (OOP’s) :
1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance
Encapsulation:
1
MOHAN S.REDDY
Abstraction:
Polymorphism:
Inheritance:
2
MOHAN S.REDDY
Types of Inheritance:
1. Single :
It is the process of creating new class from single base
class
2. Multi-level :
It is the process of creating new class from already
derived class
3. Hierarchical :
It is the process of creating multiple child classes from
single base class
4. Multiple :
It is the process of creating new class from two or more
base classes
5. Hybrid :
It is the combination of multilevel, multiple, hierarchical
inheritance.
Ex: s = Student( )
3
MOHAN S.REDDY
class Student:
'''This is student class for display
student details'''
#help(Student)
s=Student()
print(s.__doc__)
class Student:
def __init__(self):
self.sid=123
self.sname="sai"
self.saddress="hyderabad"
def display(self):
print("Student id is:",self.sid)
print("Student name is:",self.sname)
print("Student address
is:",self.saddress)
s1=Student()
s2=Student()
s1.display()
s2.display()
Constructor:
4
MOHAN S.REDDY
Method:
class Student:
def __init__(self,x,y,z):
self.sid=x
self.sname=y
self.saddress=z
def display(self):
print("Student id is:",self.sid)
print("Student name is:",self.sname)
print("Student address
is:",self.saddress)
s1=Student(101,"sai","hyderabad")
s2=Student(102,"mohan","sr nagar")
s1.display()
s2.display()
class Student:
def getdata(self):
self.sid=int(input("Enter sid:"))
self.sname=input("Enter sname:")
self.saddress=input("Enter saddress:")
5
MOHAN S.REDDY
def display(self):
print("Student id is:",self.sid)
print("Student name is:",self.sname)
print("Student address
is:",self.saddress)
s1=Student()
s1.getdata()
s1.display()
class Student:
def __init__(self,x,y,z):
self.sid=x
self.sname=y
self.saddress=z
s1=Student(101,"sai","hyderabad")
s2=Student(102,"mohan","sr nagar")
print(s1.__dict__)
print(s2.__dict__)
Types of variables:
6
MOHAN S.REDDY
class Test:
def __init__(self):
self.a=10
def m1(self):
self.b=20
t=Test()
t.m1()
t.c=30
print(t.__dict__)
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
print("within the class")
print(self.a)
print(self.b)
t=Test()
t.m1()
print("outside of the class")
print(t.a)
print(t.b)
7
MOHAN S.REDDY
Note: We can create any no of object to the class , for every object a
separate copy of instance variables will be create ,if we change or delete
one copy of instance variables then other copy of instance variables will not
effect.
class Test:
def __init__(self):
self.a=10
self.b=20
self.c=30
def m1(self):
del self.a
t1=Test()
t2=Test()
print(t1.__dict__)
print(t2.__dict__)
t1.m1()
del t2.b
t1.c=44
print(t1.__dict__)
print(t2.__dict__)
Static variables:
8
MOHAN S.REDDY
class Test:
a=10 #static variable
def __init__(self):
self.b=20 #instance variable
t1=Test()
t2=Test()
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
Test.a=99
t1.b=45
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
Local variables:
o The variables which are declare inside the particular method and
that variables are available for only that method is called local
variables.
o Local variables cannot access outside of the methods.
o Local variables can only be access within the same method where
we declare it.
o Local variables are also called as temporary variables.
o Once method execution starts these variables will be create
o Once method execution completes these will be destroyed
o Local variables can be declared inside the method without using
self.
9
MOHAN S.REDDY
class Test:
def m1(self):
a=10
print(a)
#print(b)#NameError: name 'b' is not
defined
def m2(self):
b=20
print(b)
#print(a)#NameError: name 'a' is not
defined
t=Test()
t.m1()
t.m2()
Types of methods:
Instance methods:
10
MOHAN S.REDDY
Class methods:
Static methods:
Ex:
class Student:
inst="durgasoft" #static variable
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
#self.avg()
@classmethod
11
MOHAN S.REDDY
def m1(cls):
print(cls.inst)
@staticmethod
def add(a,b):
print("sum is:",a+b)
@staticmethod
def f1():
print("Hello")
s1=Student(78,87,69)
s2=Student(90,86,94)
#print(s1.avg())
#print(s2.avg())
s1.avg()
s2.avg()
Student.m1()
s1.add(10,20)
s1.f1()
Ex:
class Test:
a=10 #static variable
def __init__(self):
print("Inside the constructor")
print(self.a)
print(Test.a)
12
MOHAN S.REDDY
def m1(self):
print("Inside the instance method")
print(self.a)
print(Test.a)
@classmethod
def m2(cls):
print("Inside the class method")
print(cls.a)
print(Test.a)
@staticmethod
def m3():
print("Inside the static method")
print(Test.a)
t=Test()
t.m1()
t.m2()
t.m3()
print("Outside of the class")
print(Test.a)
print(t.a)
Inner class:
Class College:
Code….
class Outer:
def __init__(self):
print("Outer class constructor")
def f1(self):
print("outer class method")
class Inner:
def __init__(self):
print("Inner class constructor")
def m1(self):
print("Inner class method")
'''o=Outer()
i=o.Inner()
i.m1()'''
'''i=Outer().Inner()
i.m1()'''
#Outer().Inner().m1()
o=Outer()
o.f1()
i=o.Inner()
i.m1()
GC (Garbage Collector):
14
MOHAN S.REDDY
Because of his neglect, total memory can be filled with useless objects
which create memory problems and total application will be down
with Out of memory error.
But in Python, We have some assistant which is always running in the
background to destroy useless objects, because this assistant the
chance of failing Python program with memory problems is very less.
This assistant is nothing but Garbage Collector.
Hence the main objective of Garbage Collector is to destroy useless
objects.
If an object does not have any reference variable then that object
eligible for Garbage Collection.
By default Garbage collector is enabled, but we can disable based on
our requirement. In this context we can use the following functions of
gc module.
gc .isenabled()
o Returns True if GC enabled
gc.disable()
o To disable GC explicitly
gc.enable()
o To enable GC explicitly
Ex:
import gc
print(gc.isenabled())
gc.disable()
print(gc.isenabled())
gc.enable()
print(gc.isenabled())
Destructors:
15
MOHAN S.REDDY
Ex:
import time
class Test:
def __init__(self):
print("Constructor execution")
def __del__(self):
print("Destructor execution")
t=Test()
time.sleep(5)
print("End of the program")
Ex:
import sys
class Test:
pass
t1 = Test()
t2 = t1
t3 = t1
t4 = t1
print(sys.getrefcount(t1))
16
MOHAN S.REDDY
Encapsulation:
Ex:
class Test:
x=10 #public
_y=20 #protected
__z=30 #private
def __init__(self):
print("within the class")
print(self.x)
print(self._y)
print(self.__z)
t=Test()
print("outside of the class")
print(t.x)
print(t._y)
17
MOHAN S.REDDY
Ex:
class Parent:
x=10 #public
_y=20#protected
__z=30 #private
class Child(Parent):
print(Parent.x)
print(Parent._y)
#print(Parent.__z) #AttributeError: type
object 'Parent' has no attribute '_Child__z'
c=Child()
Ex:
class Car:
def __init__(self):
self.__updatesoftware()
c=Car()
#c.__updatesoftware() #AttributeError: 'Car'
object has no attribute '__updatesoftware'
Ex:
class Car:
__name=""
__maxspeed=0
18
MOHAN S.REDDY
def __init__(self):
self.__name="verna"
self.__maxspeed=100
print(self.__name)
print(self.__maxspeed)
def drive(self):
self.__maxspeed=200
print("Driving")
print(self.__name)
print(self.__maxspeed)
c=Car()
#c.__maxspeed=200 #maxspeed will not change
c.drive()
Inheritance:
class Branch:
def getbranchdata(self):
self.bcode=int(input("Enter branch
19
MOHAN S.REDDY
code:"))
self.bname=input("Enter branch name:")
self.baddress=input("Enter branch
address:")
def displaybranchdata(self):
print("Branch code is:",self.bcode)
print("Branch name is:",self.bname)
print("Branch address
is:",self.baddress)
class Employee(Branch):
def getempdata(self):
self.eid=int(input("Ente eid:"))
self.ename=input("Enter ename:")
self.eaddress=input("Enter eaddress:")
def displayempdata(self):
print("Empid is:",self.eid)
print("Ename is:",self.ename)
print("Eaddress is:",self.eaddress)
class Salary(Employee):
def getsal(self):
self.basic=int(input("Enter basic
salary:"))
def calculate(self):
self.DA=self.basic*0.06
self.HRA=self.basic*0.4
self.Gross=self.basic+self.DA+self.HRA
def displaysal(self):
print("Basic is:",self.basic)
print("DA is:",self.DA)
print("HRA is:",self.HRA)
print("Gross is:",self.Gross)
s=Salary()
20
MOHAN S.REDDY
s.getbranchdata()
s.getempdata()
s.getsal()
s.calculate()
s.displaybranchdata()
s.displayempdata()
s.displaysal()
class Parent:
def f1(self):
print("Parent class method")
class Child1(Parent):
def f2(self):
print("Child1 class method")
class Child2(Parent):
def f3(self):
print("Child2 class method")
c1=Child1()
c2=Child2()
c1.f1()
c1.f2()
c2.f1()
c2.f3()
isinstance():
It is used to check whether the object is an instance of
particular class or not
issubclass():
It is used to check whether the class is a subclass of particular
class or not
Ex:
class Parent:
def f1(self):
21
MOHAN S.REDDY
class Child1(Parent):
def f2(self):
print("Child1 clas method")
class Child2(Parent):
def f3(self):
print("child2 class method")
c1=Child1()
c2=Child2()
print(isinstance(c1,Child1)) #true
print(isinstance(c2,Child2)) #true
print(isinstance(c1,Child2)) #false
print(isinstance(c2,Child1)) #false
print(isinstance(c1,Parent))# true
print(isinstance(c2,Parent))# true
print(issubclass(Child1,Parent)) #true
print(issubclass(Child2,Parent)) #true
print(issubclass(Child1,Child2)) #false
print(issubclass(Child2,Child1)) #false
class A:
def f1(self):
print("F1 function of class A")
class B:
def f2(self):
22
MOHAN S.REDDY
class C(A,B):
def f3(self):
print("F3 function of class C")
c=C()
c.f1()
c.f2()
c.f3()
Ex :
class A:
def f1(self):
print("F1 function of class A")
class B:
def f1(self):
print("F1 function of class B")
class C(A,B):
def f3(self):
B.f1(self)
print("F3 function of class C")
c=C()
c.f1()
c.f3()
class A:
def f1(self):
print("F1 function of class A")
class B:
def f1(self):
print("F1 function of class B")
23
MOHAN S.REDDY
class C(A,B):
def f3(self):
B.f1(self)
print("F3 function of class C")
class D(C):
def f4(self):
print("F4 function of class D")
class E(C):
def f5(self):
print("F5 function of class E")
e=E()
e.f1()
e.f3()
e.f5()
d=D()
d.f1()
d.f3()
d.f4()
Polymorphism:
o Constructor overloading
Overriding :
o Method overriding
o Constructor overriding
Operator overloading:
class Book:
def __init__(self,pages):
self.pages=pages
b1=Book(10)
b2=Book(20)
print(b1+b2) #TypeError: unsupported operand
type(s) for +: 'Book' and 'Book'
25
MOHAN S.REDDY
Ex :
class Book:
def __init__(self,pages):
self.pages=pages
b1=Book(10)
b2=Book(20)
print(b1+b2)
print(b1*b2)
Ex :
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class TimeSheet:
def __init__(self, name, days):
self.name = name
self.days = days
e = Employee('Durga', 500)
t = TimeSheet('Durga', 25)
print('This Month Salary:', e * t)
26
MOHAN S.REDDY
Method overloading:
Ex:
class Test:
def m1(self):
print("no arg method")
def m1(self,a):
print("one arg method")
def m1(self,a,b):
print("two arg method")
t=Test()
#t.m1()
#t.m1(10)
t.m1(10,20)
Constructor overloading:
27
MOHAN S.REDDY
Ex:
class Test:
def __init__(self):
print("no arg constructor")
def __init__(self,a):
print("one arg constructor")
def __init__(self,a,b):
print("two arg constructor")
#t =Test()
#t =Test(10)
t=Test(10,20)
Ex:
class Parent:
def property(self):
print("Cash+Gold+Lands")
def car(self):
print("Alto car")
class Child(Parent):
def car(self):
super().car()
print("Benz car")
28
MOHAN S.REDDY
c=Child()
c.property()
c.car()
Ex :
class Parent:
def __init__(self):
print("Parent class constructor")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child class constructor")
c=Child()
Abstract method:
29
MOHAN S.REDDY
Abstract class:
Ex :
class Vehicle(ABC):
@abstractmethod
def wheels(self):
pass
def engine(self):
print("Bs6 engine")
@abstractmethod
def color(self):
pass
30
MOHAN S.REDDY
class Car(Vehicle):
def wheels(self):
print("Car:4 wheels")
def color(self):
print("Car:color is red")
class Bike(Vehicle):
def wheels(self):
print("Bike:2 wheels")
def color(self):
print("Bike:color is black")
c=Car()
c.wheels()
c.engine()
c.color()
b=Bike()
b.wheels()
b.engine()
b.color()
Exception Handling:
Runtime errors:
31
MOHAN S.REDDY
1. Logical implementation
2. Try except implementation
1. Name error
2. Value error
3. Type error
4. Zero division error
5. File not found error
6. File exist error etc.
32
MOHAN S.REDDY
a=10
print(A) #NameError: name 'A' is not defined
a=int(input("Enter Num1:"))
b=int(input("Enter Num2:"))
print("result is:",a/b)
Note: In the above example when user give second number as zero then
we will get ZeroDivisionError, we can handle this by using logical
statements as follows.
33
MOHAN S.REDDY
Ex:
a=int(input("Enter Num1:"))
b=int(input("Enter Num2:"))
if b==0:
print("second num cant be zero")
else:
print("result is:",a/b)
Note: All the exceptions may not possible to handle using logical
statements in that case we use try except implementation.
Syntax:
try:
Statements
except:
Statements
In general inside the try block we include risky statements and inside
except block we include handling statements.
If no exception occurs inside the try block then try block statements
will execute and except block will ignore.
If any exception occurs inside the try block then try block will ignore
and except block will execute.
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except :
print("something went wrong")
In the above example, any type of exception raised then we will get
same message that is something went wrong.
34
MOHAN S.REDDY
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except ZeroDivisionError as msg:
print(msg)
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except ZeroDivisionError as msg:
print(msg)
except ValueError as msg:
print(msg)
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except(ZeroDivisionError,ValueError)as msg:
print(msg)
35
MOHAN S.REDDY
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except Exception as msg:
print(msg)
Note: While working with specific except block and default except
block make sure that default except block should be last otherwise
we will get syntax error.
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except:
print("something went wrong")
except ZeroDivisionError as msg:
print(msg)
#SyntaxError: default 'except:' must be last
Ex:
try:
a = int(input("Enter Num1:"))
b = int(input("Enter Num2:"))
print("result is:", a / b)
except ZeroDivisionError as msg:
print(msg)
except:
print("something went wrong")
36
MOHAN S.REDDY
try:
statement1
statement2
statement3
except:
statement4
statement5
Ex:
try:
print("statement-1")
#print("statement-2")
print(10/0)
print("statement-3")
except :
print(10/0)
#print("statement-4")
print("statement-5")
37
MOHAN S.REDDY
Ex:
try:
#print(10/0)
print("try block")
except:
print("except block")
finally:
print("finally block")
There is only one situation where finally block won't be executed i.e.
whenever we are using os._exit (0) function.
Whenever we are using os._exit(0) function then Python Virtual
Machine itself will be shutdown. In this particular case finally won't
be executed.
Here 0 represents status code and it indicates normal termination
Ex:
import os
try:
#print(10/0)
print("try block")
#os._exit(0)
except:
print("Except block")
os._exit(0)
finally:
print("finally block")
38
MOHAN S.REDDY
Ex:
try:
#print(10/0)
print("Outer try")
try:
print(10/0)
print("Inner try")
except ValueError:
print("Inner except")
finally:
print("Inner finally")
except:
print("Outer except")
finally:
print("Outer finally")
If the control entered into try block then compulsory finally block
will be executed. If the control not entered into try block then finally
block won't be executed.
Whenever we are writing try block, compulsory we should write
except or finally block.i.e without except or finally block we cannot
write try block.
Whenever we are writing except block, compulsory we should write
try block. i.e. except without try is always invalid.
Whenever we are writing finally block, compulsory we should write
try block. i.e. finally without try is always invalid.
39
MOHAN S.REDDY
We can write multiple except blocks for the same try, but we cannot
write multiple finally blocks for the same try
Types of exceptions:
1. Predefined exceptions
2. User defined exceptions
Syntax:
class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
Ex:
class Too_oldException(Exception):
def __init__(self,arg):
self.msg=arg
class Too_youngException(Exception):
def __init__(self,arg):
self.msg=arg
Ex:
class Too_oldException(Exception):
def __init__(self,arg):
self.msg=arg
class Too_youngException(Exception):
def __init__(self,arg):
self.msg=arg
try:
age = int(input("Enter your age:"))
if age > 60:
raise Too_oldException("Age should not
exceed 60")
elif age < 16:
raise Too_youngException("Age should
not be under 16")
else:
print("You are eligible to take
policy")
#except
(Too_youngException,Too_oldException,ValueErro
r) as msg:
except Exception as msg:
print(msg)
File Handling:
Types of Files:
There are 2 types of files
41
MOHAN S.REDDY
1. Text Files:
o Usually we can use text files to store character data
Ex: abc.txt
2. Binary Files:
o Usually we can use binary files to store binary data like images,
video files, audio files etc...
Opening a File:
File Modes:
r ------- Open an existing file for read operation. The file pointer is
positioned at the beginning of the file. If the specified file does not
exist then we will get FileNotFoundError.This is default mode.
w ------ Open an existing file for write operation. If the file already
contains some data then it will be overridden. If the specified file is
not already available then this mode will create that file.
r+ ------- To read and write data into the file. The previous data in the
file will not be deleted. The file pointer is placed at the beginning of
the file.
a+ ------- To append and read data from the file. It won’t override
existing data.
42
MOHAN S.REDDY
Note: All the above modes are applicable for text files. If the above
modes suffixed with 'b' then these represents for binary files.
Ex: rb, wb, ab, r+b, w+b, a+b, xb
Closing a File:
Once we open a file and we got file object, we can get various details
related to that file by using its properties.
name --- Name of opened file
mode ---Mode in which the file is opened
closed ---Returns boolean value indicates that file is closed or not
readable()--- Returns boolean value indicates that whether file is
readable or not
writable()--- Returns boolean value indicates that whether file is
writable or not.
Ex:
f=open("sample.txt","w")
print("file name is:",f.name)
print("file mode is:",f.mode)
print("is file readable?",f.readable())
print("is file writable?",f.writable())
print("is file closed?",f.closed)
f.close()
print("is file closed?",f.closed)
We can write character data to the text files by using the following 2
methods.
write(str)
writelines(list of lines)
43
MOHAN S.REDDY
Ex:
f=open("abc.txt",'w')
f.write("Hello\n")
f.write("Durgasoft\n")
f.write("Hyderabad\n")
print("Data written to the file")
f.close()
Ex:
f=open("sample.txt",'w')
l=["sai\n","ram\n","mohan\n","durga\n"]
f.writelines(l)
print("List data written to the file")
f.close()
Ex:
f=open("xyz.txt",'a')
f.write("Hello durgasoft\n")
print("data written to the file")
f.close()
We can read character data from text file by using the following read
methods.
44
MOHAN S.REDDY
Ex:
try:
f = open("sample.txt", 'r')
#data = f.read()
#data=f.read(5)
#data=f.readline()
data=f.readlines()
print(data)
f.close()
except FileNotFoundError as msg:
print(msg)
Ex:
with open("abcd.txt","w") as f:
f.write("Hello\n")
f.write("Hyderabad\n")
print("is file closed?",f.closed)
print("is file closed?",f.closed)
Ex:
f=open("abc.txt",'r')
print(f.tell())
print(f.read(3))
print(f.tell())
45
MOHAN S.REDDY
f.seek(11)
print(f.tell())
data="hello hyderabad"
f=open("rrr.txt",'w')
f.write(data)
with open("rrr.txt","r+") as f:
print("current cursor position:",f.tell())
text=f.read()
print(text)
print("current cursor position:",
f.tell())
f.seek(6)
print("current cursor position:",
f.tell())
f.write("Durgasoft")
print("current cusor position:",f.tell())
f.seek(0)
text=f.read()
print("Data after modification")
print(text)
Ex:
import os
if os.path.isfile(fname):
print("file is exist:",fname)
f=open(fname,'r')
else:
46
MOHAN S.REDDY
import os
fname=input("Enter file name to cehck:")
if os.path.isfile(fname):
print("file is exist:",fname)
f=open(fname,'r')
else:
print("file does not exist:",fname)
os._exit(0)
lcount=ccount=wcount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split(" ")
wcount=wcount+len(words)
print("No of lines:",lcount)
print("No of characters:",ccount)
print("No of words:",wcount)
47
MOHAN S.REDDY
We have to create ZipFile class object with name of the zip file, mode
and constant ZIP_DEFLATED. This constant represents we are
creating zip file.
Ex : f = ZipFile("files.zip","w","ZIP_DEFLATED")
Ex:
f=ZipFile("files.zip","w",ZIP_DEFLATED)
f.write("xyz.txt")
f.write("abc.txt")
f.write("rrr.txt")
print("Zip file created")
f.close()
48
MOHAN S.REDDY
Ex:
f=ZipFile("files.zip",'r',ZIP_STORED)
names=f.namelist()
print(names)
print(type(names))
import csv
with open("emp.csv","w",newline='')as f:
w=csv.writer(f)
w.writerow(["Eno","Ename","Esal","Eaddr"])
n=int(input("Enter no of employees:"))
for i in range(n):
eno=input("Enter emp no:")
ename=input("Enter emp name:")
esal=input("Enter emp sal:")
eaddr=input("Enter emp address:")
49
MOHAN S.REDDY
w.writerow([eno,ename,esal,eaddr])
print("Employee data written to csv file")
import csv
f=open("emp.csv","r")
r=csv.reader(f)
data=list(r)
import pickle
class Employee:
def __init__(self,eid,ename,eaddress):
self.eid=eid
self.ename=ename
self.eaddress=eaddress
def display(self):
print(self.eid,self.ename,self.eaddress)
with open("emp.dat","wb") as f:
e=Employee(101,"sai","hyderabad")
pickle.dump(e,f)
50
MOHAN S.REDDY
with open("emp.dat","rb") as f:
obj=pickle.load(f)
print("Display emp information after
unpickling")
obj.display()
A DAT file is a data file that contains specific information about the
program used to create it.
This file always has the . dat file extension, which is a generic format
that can contain any information – video, audio, PDF, and virtually
any other type of file.
Regular Expressions:
Function of re module:
1. compile()
2. finditer()
3. match()
4. fullmatch()
5. search()
51
MOHAN S.REDDY
6. findall()
7. sub()
8. subn()
9. split()
Ex:
import re
count=0
pattern=re.compile("ab")
match=pattern.finditer("abaababa")
for m in match:
count+=1
print(m.start(),"...",m.end(),"...",m.group())
print("The number of occurrences: ",count)
Character classes:
[abc]===>Either a or b or c
[^abc] ===>Except a and b and c
[a-z]==>Any Lower case alphabet symbol
[A-Z]===>Any upper case alphabet symbol
[a-zA-Z]==>Any alphabet symbol
[0-9]==> Any digit from 0 to 9
[a-zA-Z0-9]==>Any alphanumeric character
[^a-zA-Z0-9]==>Except alphanumeric characters(Special
Characters)
52
MOHAN S.REDDY
Ex:
import re
match=re.finditer("[abc]","a7Sb@k9#Az")
#match=re.finditer("[^abc]","a7Sb@k9#Az")
#match=re.finditer("[a-z]","a7Sb@k9#Az")
#match=re.finditer("[A-Z]","a7Sb@k9#Az")
#match=re.finditer("[0-9]","a7Sb@k9#Az")
#match=re.finditer("[a-zA-Z]","a7Sb@k9#Az")
#match=re.finditer("[a-zA-Z0-9]","a7Sb@k9#Az")
#match=re.finditer("[^a-zA-Z0-
9]","a7Sb@k9#Az")
for m in match:
print(m.start(),"......",m.group())
\s Space character
\S Any character except space character
\d Any digit from 0 to 9
\D Any character except digit
\w Any word character [a-zA-Z0-9]
\W Any character except word character (Special Characters)
. Any character including special characters
Ex:
import re
match=re.finditer("\s","a7Sb @k 9#Az")
#match=re.finditer("\S","a7Sb @k 9#Az")
#match=re.finditer("\d","a7Sb @k 9#Az")
#match=re.finditer("\D","a7Sb @k 9#Az")
#match=re.finditer("\w","a7Sb @k 9#Az")
#match=re.finditer("\W","a7Sb @k 9#Az")
#match=re.finditer(".","a7Sb @k 9#Az")
for m in match:
print(m.start(),"......",m.group())
53
MOHAN S.REDDY
Quantifiers:
Ex:
import re
match=re.finditer("a","abaabaaab")
#match=re.finditer("a+","abaabaaab")
#match=re.finditer("a*","abaabaaab")
#match=re.finditer("a?","abaabaaab")
#match=re.finditer("a{2}","abaabaaab")
#match=re.finditer("a{2,3}","abaabaaab")
for m in match:
print(m.start(),"......",m.group())
match ():
Ex:
import re
p=input("Enter pattern to check:")
m=re.match(p,"hyderabad")
if m!= None:
print("Match is available at the beginning
of the String")
print("Start Index:",m.start(), "and End
54
MOHAN S.REDDY
Index:",m.end())
else:
print("Match is not available at the
beginning of the String")
print(m)
fullmatch ():
Ex:
import re
p=input("Enter pattern to check: ")
m=re.fullmatch(p,"hyderabad")
if m!= None:
print("Full String Matched")
else:
print("Full String not Matched")
print(m)
search ():
Ex:
import re
p=input("Enter pattern to check: ")
m=re.search(p,"hyderabad")
if m!= None:
print("Match is available")
print("First Occurrence of match with
55
MOHAN S.REDDY
findall ():
Ex:
import re
l=re.findall("[0-9]","a7b9c5kz")
print(l)
sub ():
Ex:
import re
s=re.sub("[a-z]","#","a7b9c5k8z")
print(s)
subn ():
Ex:
import re
t=re.subn("[a-z]","#","a7b9c5k8z")
56
MOHAN S.REDDY
print(t)
print("The Result String:",t[0])
print("The number of replacements:",t[1])
split ():
Ex:
import re
l = re.split(",",
"shashi,nandan,shanvi,mohan,sruthi")
print(l)
for t in l:
print(t)
Ex:
import re
l = re.split("\.", "www.durgasoft.com")
print(l)
for t in l:
print(t)
^ Symbol:
We can use ^ symbol to check whether the given target string starts
with our provided pattern or not.
Ex:
import re
s="Learning Python is Very Easy"
m=re.search("^Learn",s)
if m != None:
print("Target String starts with Learn")
else:
57
MOHAN S.REDDY
$ Symbol:
We can use $ symbol to check whether the given target string ends
with our provided pattern or not.
Ex:
import re
s="Learning Python is Very Easy"
m=re.search("Easy$",s)
if m != None:
print("Target String Ends with Easy")
else:
print("Target String Not Ends with Easy")
Ex:
import re
s="Learning Python is Very Easy"
m=re.search("EASY$",s,re.IGNORECASE)
if m != None:
print("Target String Ends with Easy")
else:
print("Target String Not Ends with Easy")
Rules:
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
Or
[7-9][0-9]{9}
58
MOHAN S.REDDY
Or
[7-9]\d{9}
Or
\d{10}--- to represent 10 digit mobile numbers
Ex:
import re
n=input("Enter mobile number:")
m=re.fullmatch("[7-9]\d{9}",n)
if m!= None:
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")
Ex:
import re
mailid=input("Enter Mail id:")
m=re.fullmatch("\w[a-zA-Z0-
9_.]*@gmail[.]com",mailid)
if m!=None:
print("Valid Mail Id");
else:
print("Invalid Mail id")
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Ex:
import re
mailid=input("Enter Mail id:")
m=re.fullmatch("\w+([-+.']\w+)*@\w+([-
.]\w+)*\.\w+([-.]\w+)*",mailid)
59
MOHAN S.REDDY
if m!=None:
print("Valid Mail Id");
else:
print("Invalid Mail id")
These are the Memory Areas where Data will be stored temporarily.
Ex: Python objects like List, Tuple, and Dictionary.
Once Python program completes its execution then these objects will
be destroyed automatically and data will be lost.
Databases:
60
MOHAN S.REDDY
import pyodbc
def read(con):
print("Reading data from Database")
cursor=con.cursor()
cursor.execute("select*From emp")
for row in cursor:
print(row)
print()
def create(con):
print("Inserting data into Database")
cursor=con.cursor()
cursor.execute("insert into
emp(id,name,address,salary)
values(?,?,?,?);",(3,"mohan","hyd",5000))
con.commit()
read(con)
def update(con):
print("Updating data into Database")
cursor=con.cursor()
cursor.execute("update emp set
name=?,address=?,salary=? where
id=?;",("manoj","hyd",23000,1))
con.commit()
read(con)
61
MOHAN S.REDDY
def delete(con):
print("Deleting data from Database")
cursor=con.cursor()
cursor.execute("delete from emp where id=2")
con.commit()
read(con)
con=pyodbc.connect("Driver={SQL
Server};server=.;database=python@8am")
read(con)
create(con)
update(con)
delete(con)
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
#host='localhost',
#port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
62
MOHAN S.REDDY
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur.close()
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
63
MOHAN S.REDDY
cur.close()
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur.close()
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
64
MOHAN S.REDDY
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur.close()
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
con.commit()
cur.close()
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
cur.close()
con.close()
import mysql.connector
try:
con=mysql.connector.connect(
user='root',
password='Shanvi@123',
66
MOHAN S.REDDY
host='localhost',
database='mydb',
port=3306
)
if con.is_connected():
print("Connected successfully")
except:
print("unable to connect")
sql='select*from emp'
cur=con.cursor()
cur.execute(sql)
emp_details=cur.fetchall()
#print(emp_details)
for e in emp_details:
#print(e)
print("Id:",e[0])
print("Name:",e[1])
print("Address:",e[2])
cur.close()
con.close()
import mysql.connector
cursor=''
con=''
try:
con=mysql.connector.connect(host='localhost',d
atabase='python_11am',user='root',password='Sh
anvi@123')
cursor=con.cursor()
cursor.execute("create table student(sid
int(5) primary key,sname varchar(10),saddress
varchar(10))")
67
MOHAN S.REDDY
print("Table is created")
sql="insert into
student(sid,sname,saddress) values(%s,%s,%s)"
records=[(101,"sai","hyd"),(102,"manoj","hyd")
]
cursor.executemany(sql,records)
con.commit()
print("records inserted successfully")
cursor.execute("select*from student")
data=cursor.fetchall()
for row in data:
print("Student id:",row[0])
print("Student name:", row[1])
print("Student address:", row[2])
print()
except Exception as e:
if con==True:
con.rollback()
print("There is a problem with
sql:",e)
else:
print("connection failed",e)
finally:
if cursor:
print("finally block")
cursor.close()
if con:
con.close()
Decorator Functions:
68
MOHAN S.REDDY
Ex:
def wish(name):
print("hello",name,"good morning")
wish("mohan")
wish("durga")
The above function can display always same output for any name
But we want to modify this function to provide different message if
name is "raj"
We can do this without touching wish () function by using decorator.
Ex:
def decor(wish):
def inner(name):
if name=="raj":
print("hello raj good evening")
else:
wish(name)
return inner
@decor
def wish(name):
print("hello",name,"good morning")
wish("mohan")
69
MOHAN S.REDDY
wish("durga")
wish("raj")
Ex:
def mydiv(div):
def inner(a,b):
if a<b:
a,b=b,a
return div(a,b)
return inner
@mydiv
def div(a,b):
print(a/b)
div(2,4)
Note: we can call same function with decorator and without decorator.
Ex:
def decor(wish):
def inner(name):
if name=="raj":
print("hello raj good evening")
else:
wish(name)
return inner
def wish(name):
print("hello",name,"good morning")
d = decor(wish)
70
MOHAN S.REDDY
Generator Functions:
Normal collection:
Ex:
l = [x for x in
range(100000000000000000000000)]
for i in l:
print(i)
Note: we will get memory error in this case, because all these values
are required to store in the memory.
Generators:
Ex:
g = (x for x in
range(100000000000000000000000))
for i in g:
print(i)
71
MOHAN S.REDDY
Note: we will not get memory error in this case, because all these
values are not stored at the beginning.
Note: generators are best suitable for reading data from large files.
Ex:
def f1():
yield 123
yield "sai"
yield "hyd"
yield 30000
g = f1()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
Ex:
def f1():
yield 123
yield "sai"
yield "hyd"
yield 30000
for i in f1():
print(i)
Yield keyword:
72
MOHAN S.REDDY
Assertions:
The assert keyword lets you test if a condition in your code returns
True, if not, the program will raise an Assertion Error. You can write
a message to be written if the code returns False.
But the problem with the print function is after fixing the bug,
compulsory we have to delete extra added print statements
,otherwise these statements will be execute at runtime performance
problems and disturb the console output window.
The main advantage of assert statement over the print is after fixing
the bug we are not required to delete assert statements.
By seeing assertion error, programmer can analyse the code and fix
the problem.
73
MOHAN S.REDDY
Ex:
def square(x):
return x*x
print(square(3))
print(square(4))
print(square(5))
Ex:
def square(x):
return x*x
print(square(3))
print(square(4))
print(square(5))
74
MOHAN S.REDDY
Logging in python:
Logs provide developers with an extra set of eyes that are constantly
looking at the flow that an application is going through. They can
store information.
The main advantages of logging are we can use log files while
performing debugging.
Logging levels:
75
MOHAN S.REDDY
Ex:
import logging
logging.basicConfig(filename='log.txt',
level=logging.WARNING)
print("Logging Module Demo")
logging.debug("This is debug message")
logging.info("This is info message")
logging.warning("This is warning message")
logging.error("This is error message")
logging.critical("This is critical message")
Note: In the above program only WARNING and higher level messages will
be written to log file.
If we set level as DEBUG then all messages will be written to log file.
Ex:
import logging
logging.basicConfig(filename='log.txt',
level=logging.DEBUG)
76
MOHAN S.REDDY
import logging
logging.basicConfig(filename='mylog.txt',level=log
ging.INFO)
logging.info("A New request Came:")
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError as msg:
print("cannot divide with zero")
logging.exception(msg)
except ValueError as msg:
print("Enter only int values")
logging.exception(msg)
logging.info("Request Processing Completed")
Packages in python:
For example, we keep all our games in a Games folder and we can
even subcategorize according to the genre of the game or something
like this. The same analogy is followed by the Python package.
77
MOHAN S.REDDY
Syntax:
Import sys
78
MOHAN S.REDDY
module1.py:
def display():
print("display function from module1")
module2.py:
def show():
print("show function from module2")
mainprogram.py:
import sys
sys.path.append("F:/pythonProject@8am/package1
")
#option1
import module1
import module2
module1.display()
module2.show()
#option2
from module1 import *
from module2 import *
79
MOHAN S.REDDY
display()
show()
80
MOHAN S.REDDY
module1.py:
def display():
print("display function from module1-
package1")
module2.py:
def show():
print("show function from module2-
subpackage-package1")
mainprogram.py:
import sys
sys.path.append("F:/pythonProject@8am/package1"
)
from module1 import *
display()
sys.path.append("F:/pythonProject@8am/package1/
subpackage")
from module2 import *
show()
81
MOHAN S.REDDY
module1.py:
class Employee:
def __init__(self,eid,ename,eaddress):
self.eid=eid
self.ename=ename
self.eaddress=eaddress
def displayemp(self):
print(self.eid,self.ename,self.eaddress)
82
MOHAN S.REDDY
module2.py:
class Student:
def __init__(self,sid,sname,saddress):
self.sid=sid
self.sname=sname
self.saddress=saddress
def displaystu(self):
print(self.sid,self.sname,self.saddress)
mainprogram.py:
import sys
sys.path.append("F:\pythonProject@8am\package1
")
sys.path.append("F:\pythonProject@8am\package2
")
from module2 import Student
s=Student(1234,"raj","sr nagar")
s.displaystu()
Multi-Threading in python:
Multi-tasking:
83
MOHAN S.REDDY
84
MOHAN S.REDDY
Ex:
import threading
print("Current Executing
Thread:",threading.current_thread().getName())
threading.current_thread().setName("MohanThrea
d")
print("Current Executing
Thread:",threading.current_thread().getName())
Ex:
import warnings
warnings.filterwarnings("ignore",
category=DeprecationWarning)
from threading import *
print("Current Executing
Thread:",current_thread().getName())
current_thread().setName("MohanThread")
print("Current Executing
Thread:",current_thread().getName())
import time
def square(numbers):
for n in numbers:
85
MOHAN S.REDDY
time.sleep(1)
print("square is:",n*n)
def cube(numbers):
for n in numbers:
time.sleep(1)
print("cube is:",n*n*n)
numbers=[2,3,4,5,6]
t=time.time()
square(numbers)
cube(numbers)
print("Done in:",time.time()-t)
#Done in: 10.334125518798828
import time
import threading
def square(numbers):
for n in numbers:
time.sleep(1)
print("square is:",n*n)
def cube(numbers):
for n in numbers:
time.sleep(1)
print("cube is:",n*n*n)
numbers=[2,3,4,5,6]
t=time.time()
t1=threading.Thread(target=square,args=(number
s,))
t2=threading.Thread(target=cube,args=(numbers,
))
t1.start()
t2.start()
86
MOHAN S.REDDY
t1.join()
t2.join()
print("Done in:",time.time()-t)
#Done in: 5.050450086593628
Ex :
def display():
for i in range(10):
print("Child Thread")
t=Thread(target=display)
t.start()
87
MOHAN S.REDDY
We have to create child class for Thread class, in that child class
we have to override run() method with our required job
class Test(Thread):
def run(self):
for i in range(10):
print("Child Thread")
t=Test()
t.start()
Ex :
class Test:
def display(self):
for i in range(10):
print("Child Thread")
t=Test()
t1=Thread(target=t.display)
t1.start()
88
MOHAN S.REDDY
Ex :
def f1():
print("Child Thread")
t=Thread(target=f1)
t.start()
print("Main Thread Identification
number:",current_thread().ident)
print("Child Thread Identification
number:",t.ident)
active_count ():
Ex :
def f1():
print(current_thread().getName(),"...started"
)
time.sleep(3)
print(current_thread().getName(),"...ended")
print("The no of active
threads:",active_count())
t1=Thread(target=f1,name="childthread1")
t2=Thread(target=f1,name="childthread2")
t3=Thread(target=f1,name="childthread3")
t1.start()
t2.start()
t3.start()
89
MOHAN S.REDDY
print("The no of active
threads:",active_count())
time.sleep(5)
print("The no of active
threads:",active_count())
is_alive ():
Ex :
def f1():
print(current_thread().getName(),"..started")
time.sleep(3)
print(current_thread().getName(),"...ended")
t1=Thread(target=f1,name="childthread1")
t2=Thread(target=f1,name="childthread2")
t1.start()
t2.start()
print(t1.name,"is Alive:",t1.is_alive())
print(t2.name,"is Alive:",t2.is_alive())
time.sleep(5)
print(t1.name,"is Alive:",t1.is_alive())
print(t2.name,"is Alive:",t2.is_alive())
Join ():
90
MOHAN S.REDDY
Ex :
def f1():
for i in range(10):
print("childthread")
time.sleep(1)
t=Thread(target=f1)
t.start()
Thread Synchronization:
Ex :
def f1(name):
for i in range(10):
print("Good morning:",end="")
time.sleep(2)
print(name)
91
MOHAN S.REDDY
t1=Thread(target=f1,args=("mohan",))
t2=Thread(target=f1,args=("sai",))
t1.start()
t2.start()
92
MOHAN S.REDDY
Ex :
l=Lock()
def f1(name):
l.acquire()
for i in range(10):
print("Good morning:",end="")
time.sleep(2)
print(name)
l.release()
t1=Thread(target=f1,args=("mohan",))
t2=Thread(target=f1,args=("sai",))
t1.start()
t2.start()
Ex:
from threading import *
l=RLock()
def factorial(n):
l.acquire()
93
MOHAN S.REDDY
if n==0:
result=1
else:
result=n*factorial(n-1)
l.release()
return result
def res(n):
print("The factorial
of",n,"is:",factorial(n))
t1=Thread(target=res,args=(4,))
t2=Thread(target=res,args=(5,))
t1.start()
t2.start()
Ex:
s=Semaphore(2)
def f1(name):
s.acquire()
94
MOHAN S.REDDY
for i in range(10):
print("Good morning:",end="")
time.sleep(2)
print(name)
s.release()
t1=Thread(target=f1,args=("sai",))
t2=Thread(target=f1,args=("mohan",))
t3=Thread(target=f1,args=("kiran",))
t4=Thread(target=f1,args=("raj",))
t1.start()
t2.start()
t3.start()
t4.start()
Bounded semaphore:
Ex:
95
MOHAN S.REDDY
Ex:
Series:
96
MOHAN S.REDDY
Data Frame:
Data Frame is defined as a standard way to store data and has two
different indexes, i.e., row index and column index.
Ex:
import pandas
s=pandas.Series()
print(s)
Ex:
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print(s)
Ex:
import pandas as pd
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print(s)
Ex:
import pandas as pd
s = pd.Series(5, index=[0, 1, 2, 3])
print(s)
Ex:
import pandas as pd
s = pd.Series([1,2,3,4,5],index =
['a','b','c','d','e'])
97
MOHAN S.REDDY
print(s)
print(s['a'])
print (s[:3])
Ex:
import pandas as pd
df = pd.DataFrame()
print(df)
Ex:
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)
Ex:
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df =
pd.DataFrame(data,columns=['Name','Age'],dtype
=float)
print(df)
Ex:
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve',
'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df)
#df.tail(2)
df.head(1)
Ex:
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve',
'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data,
98
MOHAN S.REDDY
index=['rank1','rank2','rank3','rank4'])
print(df)
Ex:
import pandas as pd
df1 = pd.DataFrame([[1, 2], [3, 4]], columns =
['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns =
['a','b'])
df1 = df1.append(df2)
print(df1)
Ex:
import pandas as pd
df1 = pd.DataFrame({'name': ['John',
'Smith','Paul'],
'Age': ['25', '30',
'50']},
index=[0, 1, 2])
df2 = pd.DataFrame({'name': ['Adam', 'Smith'
],
'Age': ['26', '11']},
index=[3, 4])
df_concat = pd.concat([df1,df2])
print(df_concat)
Ex:
99
MOHAN S.REDDY
Ex:
# x-axis values
x = [5, 2, 1, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x,y,marker='o')
# function to show the plot
plt.show()
Ex:
Ex:
x=[5,8,10]
y=[12,16,6]
x2=[6,9,11]
y2=[6,15,7]
plt.plot(x,y,'g',label="line one",linewidth=3)
plt.plot(x2,y2,'r',label="line
100
MOHAN S.REDDY
two",linewidth=5)
plt.title("Simple Graph")
plt.ylabel("Y axis")
plt.xlabel("X axis")
plt.legend()
plt.grid(True,color='b')
plt.show()
Ex:
plt.bar([1,3,5,7,9],[5,2,7,8,2],label="Bar
one",color='y')
plt.bar([2,4,6,8,10],[8,6,2,5,6],label="Bar
two",color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title("Bar Graph")
plt.show()
Ex:
Ex:
days=[1,2,3,4,5]
sleeping=[7,8,6,11,7]
eating=[2,3,4,3,2]
working=[7,8,7,2,2]
101
MOHAN S.REDDY
playing=[8,5,7,8,13]
plt.plot([],[],color='m',label='sleeping',line
width=5)
plt.plot([],[],color='c',label='eating',linewi
dth=5)
plt.plot([],[],color='r',label='working',linew
idth=5)
plt.plot([],[],color='k',label='playing',linew
idth=5)
plt.stackplot(days,sleeping,eating,working,pla
ying,colors=['m','c','r','k'])
plt.xlabel('X')
plt.ylabel('Y')
plt.title("Stack plot")
plt.legend()
plt.show()
Ex:
102