Advanced Python Programming Practical Manual
Advanced Python Programming Practical Manual
Advanced Python Programming Practical Manual
AJAY PASHANKAR
First you need to create a text file and keep it in same folder where you save your programs
Program:
fo=open("foo.txt","wb")
print("name of file:",fo.name)
print("closed or not:",fo.closed)
print("opening mode:",fo.mode)
print("softspace flag:",fo.softspace)
TEXT.
def main():
f=open("hello.txt","a+")
f.write("welcome to lottery of 200 marks ")
f.close()
main()
file_read_from_tail('README.txt',1)
www.profajaypashankar.com Page 2 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This tool
not only helps you in creating regular expressions, but it also helps you learn it.
Now you understand the basics of RegEx, let's discuss how to use RegEx in your Python code.
Python RegEx
Python has a module named re to work with regular expressions. To use it, we need to import the
module.
import re
The module defines several functions and constants to work with RegEx.
re.findall()
The re.findall() method returns a list of strings containing all matches.
Example 1: re.findall()
import re
www.profajaypashankar.com Page 3 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
#Output:
re.split()
The re.split method splits the string where there is a match and returns a list of strings where the
splits have occurred.
Example 2: re.split()
import re
# Output:
If the pattern is not found, re.split() returns a list containing the original string.
You can pass maxsplit argument to the re.split() method. It's the maximum number of splits that will
occur.
import re
string = 'Twelve:12 Eighty nine:89 Nine:9.'
pattern = '\d+'
# maxsplit = 1
# split only at the first occurrence
result = re.split(pattern, string, 1)
print(result)
# Output:
www.profajaypashankar.com Page 4 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
By the way, the default value of maxsplit is 0; meaning all possible splits.
re.sub()
The syntax of re.sub() is:
re.sub(pattern, replace, string)
The method returns a string where matched occurrences are replaced with the content
of replace variable.
Example 3: re.sub()
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# empty string
replace = ''
# Output:
You can pass count as a fourth parameter to the re.sub() method. If omited, it results to 0. This will
replace all occurrences.
import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# Output:
www.profajaypashankar.com Page 5 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
re.subn()
The re.subn() is similar to re.sub() except it returns a tuple of 2 items containing the new string and
the number of substitutions made.
Example 4: re.subn()
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# empty string
replace = ''
# Output:
re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the first
location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
match = re.search(pattern, str)
Example 5: re.search()
import re
if match:
print("pattern found inside the string")
else:
print("pattern not found")
# Output:
www.profajaypashankar.com Page 6 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Match object
You can get methods and attributes of a match object using dir() function.
Some of the commonly used methods and attributes of match objects are:
match.group()
The group() method returns the part of the string where there is a match.
Example 6: Match object
import re
if match:
print(match.group())
else:
print("pattern not found")
# Output:
>>> match.group(2)
'35'
>>> match.group(1, 2)
('801', '35')
>>> match.groups()
('801', '35')
www.profajaypashankar.com Page 7 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
>>> match.span()
(2, 8)
>>> match.string
'39801 356, 2102 1111'
import re
# Output:
-------------------------------------------------------------------------------------------------------------------
PROGRAM 3 Write a Program to demonstrate concept of threading and multitasking in
Python.
print(" Total time taken by threads is :", time.time() - t1) # print the total time
www.profajaypashankar.com Page 8 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
output:
===============================================================
In the above output we can see error regarding thread module in python 3.1 And above
version thread module is obsolete or discarded use threading instead.
===============================================================
a. Connecting to database
===========================================================
Before using any database with python program we need to install that
database connector for python here we have used mysql connector for
python for installation refer following link : https://youtu.be/uh3tub-zGDo
==================================================
import mysql.connector
db=mysql.connector.connect(user='root',passwd='12345',host='127.0.0.1',database
='nit')
#prepare a cursor object using cursor() method
cursor=db.cursor()
#drop table if it already exit using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# create table as per requirement
sql="""CREATE TABLE EMPLOYEE(FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR (20),
AGE INT,SEX CHAR(1),INCOME FLOAT)"""
cursor.execute(sql)
print("Table created Succesfully");
# disconnect from server
db.close()
www.profajaypashankar.com Page 9 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Design a database application to that allows the user to add the records
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
cursor=db.cursor()
sql="INSERT INTO EMPLOYEE(FIRST_NAME,\
LAST_NAME,AGE,SEX,INCOME)\
VALUES('%s','%s','%d','%c','%d')"%\
('Ajay','Moi',19,'M',22000)
try:
cursor.execute(sql)
print("Data Added Successfully")
db.commit()
except:
db.rollback()
db.close()
www.profajaypashankar.com Page 10 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
-----------------------------------------------------------------------------------------------
PROGRAM 5 Write a Python Program to demonstrate different types of exception handing.
import sys
randomList=['a',0,2]
for entry in randomList :
try:
print("the entry is ",entry)
r=1/int(entry)
break
except:
print("oops !",sys.exc_info()[0],"occured")
print("next entry")
print()
print("the reciprocal of",entry,"is",r)
www.profajaypashankar.com Page 11 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
-------------------------------------------------------------------------------------------------------------
window=Tk()
lbl.place(x=60, y=50)
window.title('Hello Python')
window.geometry("300x200+10+10")
window.mainloop()
www.profajaypashankar.com Page 12 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
window=Tk()
btn.place(x=80, y=100)
lbl.place(x=60, y=50)
txtfld.place(x=80, y=150)
window.title('Hello Python')
window.geometry("300x200+10+10")
window.mainloop()
www.profajaypashankar.com Page 13 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
import tkinter
root=Tk()
O=Canvas(root,bg="blue",width=500,height=500)
O.pack()
n=Label(root,text="hello World")
n.pack()
root.mainloop()
Pack layout
import tkinter as tk
root = tk.Tk()
w.pack()
www.profajaypashankar.com Page 14 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
w.pack()
w.pack()
tk.mainloop()
-------------------------------------------------------------------------------------------------------------------
Place Layout:
import tkinter as tk
import random
root = tk.Tk()
# width x height + x_offset + y_offset:
root.geometry("170x200+30+30")
languages = ['Python','Perl','C++','Java','Tcl/Tk']
labels = range(5)
for i in range(5):
ct = [random.randrange(256) for x in range(3)]
brightness = int(round(0.299*ct[0] + 0.587*ct[1] + 0.114*ct[2]))
ct_hex = "%02x%02x%02x" % tuple(ct)
bg_colour = '#' + "".join(ct_hex)
l = tk.Label(root,
text=languages[i],
fg='White' if brightness < 120 else 'Black',
bg=bg_colour)
l.place(x = 20, y = 30 + i*30, width=120, height=25)
root.mainloop()
www.profajaypashankar.com Page 15 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
-----------------------------------------------------------------------------------------------------------------
Grid Layout
import tkinter as tk
colours = ['red','green','orange','white','yellow','blue']
r=0
for c in colours:
r=r+1
tk.mainloop()
-------------------------------------------------------------------------------------------------------------------
c. Event Handling
class MyWindow:
www.profajaypashankar.com Page 16 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
self.lbl3=Label(win, text='Result')
self.t1=Entry(bd=3)
self.t2=Entry()
self.t3=Entry()
self.btn2=Button(win, text='Subtract')
self.lbl1.place(x=100, y=50)
self.t1.place(x=200, y=50)
self.lbl2.place(x=100, y=100)
self.t2.place(x=200, y=100)
self.b2=Button(win, text='Subtract')
self.b2.bind('<Button-1>', self.sub)
self.b1.place(x=100, y=150)
self.b2.place(x=200, y=150)
self.lbl3.place(x=100, y=200)
self.t3.place(x=200, y=200)
def add(self):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1+num2
self.t3.insert(END, str(result))
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1-num2
self.t3.insert(END, str(result))
window=Tk()
mywin=MyWindow(window)
window.title('Hello Python')
www.profajaypashankar.com Page 17 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
window.geometry("400x300+10+10")
window.mainloop()
-------------------------------------------------------------------------------------------------------------------
7 Write Python Program to create application which uses date and time in Python.
root = Tk()
root.title('Clock')
import datetime as dt
def time():
www.profajaypashankar.com Page 18 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
lbl.config(text=string)
lbl.after(1000, time)
lbl.pack(anchor='center')
time()
mainloop()
def date():
win = Tk()
win.geometry("700x350")
date = dt.datetime.now()
label.pack(pady=20)
date()
mainloop()
www.profajaypashankar.com Page 19 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
-------------------------------------------------------------------------------------------------------------------
#socket_server.py
import socket
def server_program():
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
if __name__ == '__main__':
server_program()
------------------------------------------------------------------------------------------------------------
#socket_client.py
import socket
def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
www.profajaypashankar.com Page 20 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
if __name__ == '__main__':
client_program()
===============================================================
IMP NOTE:
1. Create 2 files namely socket_server.py and socket_client.py separately.
2. After successful compilation.
3. Open two different shell
4. First run socket_server.py
5. Then run socket_client.py
6. Now type something in socket_client.py
7. Then again write reply from server program.
8. At last, write bye from client program to terminate both program.
Socket_server.py shell
Socket_client.py shell
-------------------------------------------------------------------------------------------------------------------
9 Write a program to Python program to implement concepts of OOP such as
a. Types of Methods
class Dog:
# class attribute
attr1 = "mammal"
www.profajaypashankar.com Page 21 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
# Instance attribute
def __init__(self, name):
self.name = name
def speak(self):
print("My name is {}".format(self.name))
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
b. Inheritance
# parent class
class Person(object):
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
# its instance
a.display()
a.details()
Output:
c. Polymorphism
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
OUTPUT:
------------------------------------------------------------------------------------------------------------------
www.profajaypashankar.com Page 23 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
class Pentagon(Polygon):
class Hexagon(Polygon):
class Quadrilateral(Polygon):
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
Code 2
# Python program showing
www.profajaypashankar.com Page 24 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")
c=Animal()
b. Interfaces
An interface acts as a template for designing classes. Interfaces also define methods the same as
classes, but abstract methods, whereas class contains nonabstract methods. Abstract methods are
those methods without implementation or which are without the body. So the interface just defines the
abstract method without implementation. The implementation of these abstract methods is defined by
classes that implement an interface. In this topic, we are going to learn about Interface in Python.
Python interface design is different from other programming languages like C++, Java, C# and Go;
one difference is that all these languages use the keyword “interface”, whereas Python does not use it.
Another difference is Python does not require that a class which is implements an interface to provide
the definition for all the abstract methods of an interface.
There are two ways in python to create and implement the interface, which are –
Informal Interfaces
Formal Interfaces
1. Informal Interfaces
python informal interface is also a class that defines methods that can be overridden but without force
enforcement. An informal interface also called Protocols or Duck Typing. The duck typing is actually we
execute a method on the object as we expected an object to have, instead of checking the type of an
object. If its beaver is the same as we expected, then we will be fine and go farther, else if it does not,
things might get wrong, and for safety, we use a try..except block or hasattr to handle the exceptions
to check the object have the particular method or not.
www.profajaypashankar.com Page 25 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
An informal interface in python is termed as a protocol because it is informal and cannot be formally
enforced. It is mostly defined by templates or demonstrates in the documentations. Consider some of
the methods we usually used – __len__, __iter__, __contains__ and all, which are used to perform
some operation or set of protocols.
Example
Let see an example of python code to implements the – __len__, __iter__, __contains__ methods to
apply on user define class instance or object, as in the below-given code –
Code:
class Fruits :
self.__ele = ele
print(len(Fruits_list))
print("Apple" in Fruits_list)
print("Mango" in Fruits_list)
Output:
As in the above example code, class Fruits implement the __len__, and __contains__ methods, so on
the instance of the Fruits class, we can directly use the len function to get the size and can check the
membership by using the in operator. As in the above code, the __iter__ method (iterable protocol) is
not implemented, so we would not iterate over the instance of the Fruits. Therefore an informal
interface cannot be enforced formally.
2. Formal Interfaces
A formal Interface is an interface which enforced formally. In some situations, the protocols or duck
typing creates confusion, like consider the example we have two classes FourWheelVehicle and
TwoWheelVehicle both have a method SpeedUp( ), so the object of both class can speedup, but both
objects are not the same even if both classes implement the same interface. So to resolve this
confusion, we can use the formal interface. To create a formal interface, we need to use ABCs
(Abstract Base Classes).
www.profajaypashankar.com Page 26 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
An ABC is simple as an interface or base classes define as an abstract class in nature and the abstract
class contains some methods as abstract. Next, if any classes or objects implement or drive from these
base classes, then these bases classes forced to implements all those methods. Note that the interface
cannot be instantiated, which means that we cannot create the object of the interface. So we use a
base class to create an object, and we can say that the object implements an interface. And we will
use the type function to confirm that the object implements a particular interface or not.
Example
Let see an example of python code to understand the formal interface with the general example where
we are trying to create an object of the abstract class, as in the below-given code –
Code:
import abc
@abc.abstractclassmethod
def disp():
pass
pass
o1 = Myclass( )
Output:
In the above code, the Myclass class inherits abstract class Myinterface but not provided the disp()
abstract method’s implementation. The class Myclass also becomes an abstract class and hence cannot
be instantiated.
Example #1
Code:
import abc
@abc.abstractclassmethod
def disp( ):
pass
class Myclass(Myinterface):
www.profajaypashankar.com Page 27 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
def disp( ):
pass
o1=Myclass()
Example #2
Example of python code for the derived class which defines an abstract method with the proper
definition –
Code:
import abc
@abc.abstractclassmethod
def disp( ):
pass
class Myclass(Myinterface):
def disp(s):
o1=Myclass()
o1.disp()
Output:
Example #3
Code:
import abc
@abc.abstractmethod
pass
class Car(FourWheelVehicle) :
def SpeedUp(self):
s = Car()
Output:
Example #4
Code:
import abc
@abc.abstractmethod
pass
class Car(FourWheelVehicle) :
def SpeedUp(self):
@abc.abstractmethod
def SpeedUp(self):
pass
class Bike(TwoWheelVehicle) :
def SpeedUp(self) :
a = Bike ()
s = Car()
Output:
www.profajaypashankar.com Page 29 of 29