Advancrd Python Practical SEM II PDF
Advancrd Python Practical SEM II PDF
Advancrd Python Practical SEM II PDF
Practical no.1
Write a program to Python program to implement various file operations.
Here is the complete list of methods in text mode with a brief description:
Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
Reads at most n characters from the file. Reads till end of file if it is
read( n )
negative or None .
Reads and returns one line from the file. Reads in at most n bytes if
readline( n =-1)
specified.
Reads and returns a list of lines from the file. Reads in at most n
readlines( n =-1)
bytes/characters if specified.
Changes the file position to offset bytes, in reference to from (start, current,
seek( offset , from = SEEK_SET )
end).
tell() Returns an integer that represents the current position of the file's object.
Resizes the file stream to size bytes. If size is not specified, resizes to
truncate( size = None )
current location.
write( s ) Writes the string s to the file and returns the number of characters written.
When we want to read from or write to a file, we need to open it first. When we are done, it needs
to be closed so that the resources that are tied with the file are freed.
1. Open a file
Here, we have created a file object named file1 . This object can be used to work with files and
directories.
By default, the files are open in read mode (cannot be modified). The code above is equivalent to
Here, we have explicitly specified the mode by passing the "r" argument which means file is opened
for reading.
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Output
In the above example, we have read the test.txt file that is available in our current directory. Notice
the code,
read_content = file1.read
Here, file1.read() reads the test.txt file and is stored in the read_content variable.
Closing a file will free up the resources that were tied with the file. It is done using
the close() method in Python. For example,
# open a file
file1 = open("test.txt", "r")
Output
try:
file1 = open("test.txt", "r")
read_content = file1.read()
print(read_content)
finally:
# close the file
file1.close()
Here, we have closed the file in the finally block as finally always executes, and the file will be closed
even if an exception occurs.
If a file already exists, its content is erased, and new content is added to the file.
Here, a new test2.txt file is created and this file will have contents specified inside the write() method.
Writing
to Python Files
Practical no.2
Write a program to Python program to demonstrate use of regular expression for
suitable application.
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For
example,
^a...s$
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and
ending with s .
A pattern defined using RegEx can be used to match against a string.
abs No match
alias Match
Alias No match
An abacus No match
Python has a module named re to work with RegEx. Here's an example:
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Run Code
Here, we used re.match() function to search pattern within the test_string . The method returns a match
object if the search is successful. If not, it returns None .
There are other several functions defined in the re module to work with RegEx. Before we explore
that, let's learn about regular expressions themselves.
If you already know the basics of RegEx, jump to Python RegEx.
MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list
of metacharacters:
[] . ^ $ * + ? {} () \ |
[] - Square brackets
Square brackets specifies a set of characters you wish to match.
a 1 match
ac 2 matches
[abc]
Hey Jude No match
abc de ca 5 matches
Here, [abc] will match if the string you are trying to match contains any of the a , b or c .
You can also specify a range of characters using - inside square brackets.
[a-e] is the same as [abcde] .
You can complement (invert) the character set by using caret ^ symbol at the start of a square-
bracket.
[^abc] means any character except a or b or c .
[^0-9] means any non-digit character.
. - Period
A period matches any single character (except newline '\n' ).
a No match
.. ac 1 match
acd 1 match
Expression String Matched?
^ - Caret
The caret symbol ^ is used to check if a string starts with a certain character.
Expression String Matched?
a 1 match
^a abc 1 match
bac No match
abc 1 match
^ab
acb No match (starts with a but not followed by b )
$ - Dollar
The dollar symbol $ is used to check if a string ends with a certain character.
Expression String Matched?
a 1 match
a$ formula 1 match
cab No match
* - Star
The star symbol * matches zero or more occurrences of the pattern left to it.
Expression String Matched?
mn 1 match
man 1 match
woman 1 match
+ - Plus
The plus symbol + matches one or more occurrences of the pattern left to it.
Expression String Matched?
man 1 match
woman 1 match
? - Question Mark
The question mark symbol ? matches zero or one occurrence of the pattern left to it.
Expression String Matched?
ma?n mn 1 match
Expression String Matched?
man 1 match
woman 1 match
{} - Braces
Consider this code: {n,m} . This means at least n , and at most m repetitions of the pattern left to it.
Expression String Matched?
Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits but not more than 4
digits
Expression String Matched?
1 and 2 No match
| - Alternation
Vertical bar | is used for alternation ( or operator).
Expression String Matched?
cde No match
() - Group
Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that matches
either a or b or c followed by xz
Expression String Matched?
ab xz No match
\ - Backslash
Backlash \ is used to escape various characters including all metacharacters. For example,
\$a match if a string contains $ followed by a . Here, $ is not interpreted by a RegEx engine in a
special way.
If you are unsure if a character has special meaning or not, you can put \ in front of it. This makes
sure the character is not treated in a special way.
Special Sequences
Special sequences make commonly used patterns easier to write. Here's a list of special sequences:
football Match
afootball No match
\B - Opposite of \b . Matches if the specified characters are not at the beginning or end of a word.
Expression String Matched?
football No match
afootball Match
Expression String Matched?
ab 2 matches (at a b )
\S
No match
\w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-zA-Z0-9_] . By the
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()
# Program to extract numbers from a string
import re
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
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
# maxsplit = 1
# split only at the first occurrence
result = re.split(pattern, string, 1)
print(result)
By the way, the default value of maxsplit is 0; meaning all possible splits.
re.sub()
The syntax of re.sub() is:
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: abc12de23f456
Run Code
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:
# abc12de 23
# f45 6
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: ('abc12de23f456', 4)
Run Code
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 .
import re
if match:
print("pattern found inside the string")
else:
print("pattern not found")
Practical 3
Write a Program to demonstrate concept of threading and
multitasking in Python.
Multithreading in Python 3
A thread is the smallest unit of a program or process executed independently or scheduled by the Operating
System. In the computer system, an Operating System achieves multitasking by dividing the process into threads.
A thread is a lightweight process that ensures the execution of the process separately on the system. In Python 3,
when multiple processors are running on a program, each processor runs simultaneously to execute its tasks
separately.
Python Multithreading
Multithreading is a threading technique in Python programming to run multiple threads concurrently by rapidly
switching between threads with a CPU help (called context switching). Besides, it allows sharing of its data space
with the main threads inside a process that share information and communication with other threads easier than
individual processes. Multithreading aims to perform multiple tasks simultaneously, which increases
performance, speed and improves the rendering of the application.
def print_cube(num):
# function to print cube of given num
print("Cube: {}" .format(num * num * num))
def print_square(num):
# function to print square of given num
print("Square: {}" .format(num * num))
if __name__ =="__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
Square: 100
Cube: 1000
Done!
Multithreading
import Queue
import threading
import time
exitFlag = 0
Practical no.4
Write a Python Program to work with databases in Python to perform operations
such as
a. Connecting to database
b. Creating and dropping tables
c. Inserting and updating into table
import MySQLdb
import MySQLdb
cursor.execute(sql)
import MySQLdb
Practical no. 5
Write a Python Program to demonstrate different types of exception handing.
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the try block. Every try block
is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used without
the try block.
Example: Exception Handling Using try...except
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try block. Now
when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Run Code
Output
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
Practical no.6
Write a GUI Program in Python to design application that demonstrates
a. Different fonts and colors
b. Different Layout Managers
c. Event Handling.
Python provides the standard library Tkinter for creating the graphical user interface for desktop based
applications.
Developing desktop based applications with python Tkinter is not a complex task. An empty Tkinter top-level
window can be created by using the following steps.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. top.mainloop()
Output
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build the python GUI
applications.
SN Widget Description
1 Button The Button is used to add various kinds of buttons to the python application.
2 Canvas The canvas widget is used to draw the canvas on the window.
4 Entry The entry widget is used to display the single-line text field to the user. It is commonly used to
5 Frame It can be defined as a container to which, another widget can be added and organized.
6 Label A label is a text used to display some message or information about the other widgets.
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is provided with various opt
among them.
13 Scrollbar It provides the scrollbar to the user so that the user can scroll the window up and down.
14 Text It is different from Entry because it provides a multi-line text field to the user so that the user c
18 MessageBox This module is used to display the message-box in the desktop based applications.
However, the controls are less and widgets are generally added in the less organized manner.
syntax
1. widget.pack(options)
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. redbutton = Button(parent, text = "Red", fg = "red")
5. redbutton.pack( side = LEFT)
6. greenbutton = Button(parent, text = "Black", fg = "black")
7. greenbutton.pack( side = RIGHT )
8. bluebutton = Button(parent, text = "Blue", fg = "blue")
9. bluebutton.pack( side = TOP )
10. blackbutton = Button(parent, text = "Green", fg = "red")
11. blackbutton.pack( side = BOTTOM)
12. parent.mainloop()
Output:
1. # !/usr/bin/python3
2. from tkinter import *
3. top = Tk()
4. top.geometry("400x250")
5. name = Label(top, text = "Name").place(x = 30,y = 50)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
7. password = Label(top, text = "Password").place(x = 30, y = 130)
8. e1 = Entry(top).place(x = 80, y = 50)
9. e2 = Entry(top).place(x = 80, y = 90)
10. e3 = Entry(top).place(x = 95, y = 130)
11. top.mainloop()
Output:
Practical no.7
Write Python Program to create application which uses date and time in
Python.
Get Current Date and Time
import datetime
print(now)
Run Code
Output
2022-12-27 08:26:49.219717
Python datetime.time Class
Time object to represent time
from datetime import time
Output
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566
Once we create the time object, we can easily print its attributes such as hour , minute etc. For
example,
from datetime import time
Output
Hour = 11
Minute = 34
Second = 56
Microsecond = 0
Practical no.8
Write a Python program to create server-client and exchange basic
information.
1. Python socket server program executes at first and wait for any request
2. Python socket client program will initiate the conversation at first.
3. Then server program will response accordingly to client requests.
4. Client program will terminate if user enters “bye” message. Server program will also terminate when
client program terminates, this is optional and we can keep server program running indefinitely or
terminate with some specific command in client request.
Python Socket Server
We will save python socket server program as socket_server.py. To use python socket connection, we need to
import socket module. Then, sequentially we need to perform some task to establish connection between server
and client. We can obtain host address by using socket.gethostname() function. It is recommended to user port
address above 1024 because port number lesser than 1024 are reserved for standard internet protocol. See the
below python socket server example code, the comments will help you to understand the code.
import socket
def server_program():
host = socket.gethostname()
server_socket.listen(2)
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
if __name__ == '__main__':
server_program()
So our python socket server is running on port 5000 and it will wait for client request. If you want server to not
quit when client connection is closed, just remove the if condition and break statement. Python while loop is
used to run the server program indefinitely and keep waiting for client request.
import socket
def client_program():
if __name__ == '__main__':
client_program()
-> Hello
-> Good
pankaj$
-> Hi
-> Awesome!
-> Bye
pankaj
Practical 9
Write a program to Python program to implement concepts of OOP such
as
a. Types of Methods
b. Inheritance
c. Polymorphism.
Python is a versatile programming language that supports various programming styles, including
object-oriented programming (OOP) through the use of objects and classes.
An object is any entity that has attributes and behaviors. For example, a parrot is an object. It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.
class Parrot:
# class attribute
name = ""
age = 0
# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10
# create another object parrot2
parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15
# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Run Code
Output
Python Inheritance
Inheritance is a way of creating a new class for using details of an existing class without modifying
it.
The newly formed class is a derived class (or child class). Similarly, the existing class is a base
class (or parent class).
def eat(self):
print( "I can eat!")
def sleep(self):
print("I can sleep!")
# derived class
class Dog(Animal):
def bark(self):
print("I can bark! Woof woof!!")
Output
I can eat!
I can sleep!
I can bark! Woof woof!!
Polymorphism
Polymorphism is another important concept of object-oriented programming. It simply means more
than one form.
That is, the same entity (method or operator or object) can perform different operations in different
scenarios.
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")
class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
Output
Rendering Square...
Rendering Circle...
Practical no.10
Write a program to Python program to implement concepts of OOP such
as
a. Abstract methods and classes
b. Interfaces.
Python Methods
We can also define a function inside a Python class. A Python Function defined inside a class is
called a method.
Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
Output
Area of Room = 1309.0
Method: calculate_area()
Interface in python
In object-oriented languages like Python, the interface is a collection of method signatures that
should be provided by the implementing class. Implementing an interface is a way of writing an
organized code and achieve abstraction.
The package zope.interface provides an implementation of “object interfaces” for Python. It is
maintained by the Zope Toolkit project. The package exports two objects, ‘Interface’ and ‘Attribute’
directly. It also exports several helper methods. It aims to provide stricter semantics and better error
messages than Python’s built-in abc module.
Declaring interface
In python, interface is defined using python class statements and is a subclass
of interface.Interface which is the parent interface for all interfaces.
Syntax :
class IMyInterface(zope.interface.Interface):
# methods and attributes
Example
import zope.interface
class MyInterface(zope.interface.Interface):
x = zope.interface.Attribute("foo")
def method1(self, x):
pass
def method2(self):
pass
print(type(MyInterface))
print(MyInterface.__module__)
print(MyInterface.__name__)
# get attribute
x = MyInterface['x']
print(x)
print(type(x))
Output :
<class zope.interface.interface.InterfaceClass>
__main__
MyInterface
<zope.interface.interface.Attribute object at 0x00000270A8C74358>
<class 'zope.interface.interface.Attribute'>
Implementing interface
Interface acts as a blueprint for designing classes, so interfaces are implemented
using implementer decorator on class. If a class implements an interface, then the instances of the
class provide the interface. Objects can provide interfaces directly, in addition to what their classes
implement.
Syntax :
@zope.interface.implementer(*interfaces)
class Class_name:
# methods
import zope.interface
class BaseI(zope.interface.Interface):
def m1(self, x):
pass
def m2(self):
pass
class DerivedI(BaseI):
def m3(self, x, y):
pass
@zope.interface.implementer(DerivedI)
class cls:
def m1(self, z):
return z**3
def m2(self):
return 'foo'
def m3(self, x, y):
return x ^ y
Output :
(<InterfaceClass __main__.BaseI>, )
False
True
False