Advancrd Python Practical SEM II PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

USCSP202 Advanced Python Programming – Practical

Practical no.1
Write a program to Python program to implement various file operations.

Python File Methods


There are various methods available with the file object. Some of them have been used in the above
examples.

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.

fileno() Returns an integer number (file descriptor) of the file.

flush() Flushes the write buffer of the file stream.

isatty() Returns True if the file stream is interactive.

Reads at most n characters from the file. Reads till end of file if it is
read( n )
negative or None .

readable() Returns True if the file stream can be read from.

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).

seekable() Returns True if the file stream supports random access.

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.

writable() Returns True if the file stream can be written to.

write( s ) Writes the string s to the file and returns the number of characters written.

writelines( lines ) Writes a list of lines to the file.

A file is a container in computer storage devices used for storing data.

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.

Hence, in Python, a file operation takes place in the following order:

1. Open a file

2. Read or write (perform operation)

3. Close the file

Opening Files in Python


In Python, we use the open() method to open files.
To demonstrate how we open files in Python, let's suppose we have a file named test.txt with the
following content.
Opening
Files in Python
Now, let's try to open data from this file using the open() function.

# open file in current directory


file1 = open("test.txt")

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

file1 = open("test.txt", "r")

Here, we have explicitly specified the mode by passing the "r" argument which means file is opened
for reading.

Here's few simple examples of how to open a file in different modes,

file1 = open("test.txt") # equivalent to 'r' or 'rt'


file1 = open("test.txt",'w') # write in text mode
file1 = open("img.bmp",'r+b') # read and write in binary mode

Reading Files in Python


After we open a file, we use the read() method to read its contents. For example,

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)

Output

This is a test file.


Hello from the test file.

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 Files in Python


When we are done with performing operations on the file, we need to properly close the file.

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")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()

Output

This is a test file.


Hello from the test file.

Here, we have used the close() method to close the file.


After we perform file operation, we should always close the file; it's a good programming practice.

Exception Handling in Files


If an exception occurs when we are performing some operation with the file, the code exits without
closing the file. A safer way is to use a try...finally block.
Let's see an example,

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.

Use of with...open Syntax


In Python, we can use the with...open syntax to automatically close the file. For example,

with open("test.txt", "r") as file1:


read_content = file1.read()
print(read_content)
Note: Since we don't have to worry about closing the file, make a habit of using
the with...open syntax.

Writing to Files in Python


There are two things we need to remember while writing to a file.

 If we try to open a file that doesn't exist, a new file is created.

 If a file already exists, its content is erased, and new content is added to the file.

In order to write into a file in Python, we need to open it in write mode by


passing "w" inside open() as a second argument.
Suppose, we don't have a file named test2.txt. Let's see what happens if we write contents to
the test2.txt file.

with open(test2.txt', 'w') as file2:

# write contents to the test2.txt file


file2.write('Programming is Fun.')
fil2.write('Programiz for beginners')

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.

Expression String Matched?

abs No match

alias Match

^a...s$ abyss 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.

Specify Pattern Using RegEx


To specify regular expressions, metacharacters are used. In the above example, ^ and $ are
metacharacters.

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.

Expression String Matched?

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] .

 [1-4] is the same as [1234] .

 [0-39] is the same as [01239] .

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' ).

Expression String Matched?

a No match

.. ac 1 match

acd 1 match
Expression String Matched?

acde 2 matches (contains 4 characters)

^ - 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

ma*n maaan 1 match

main No match ( a is not followed by n )

woman 1 match

+ - Plus
The plus symbol + matches one or more occurrences of the pattern left to it.
Expression String Matched?

mn No match (no a character)

man 1 match

ma+n maaan 1 match

main No match (a is not followed by n)

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

maaan No match (more than one a character)

main No match (a is not followed by n)

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?

abc dat No match

abc daat 1 match (at daat )


a{2,3}
aabc daaat 2 matches (at aabc and daaat )

aabc daaaat 2 matches (at aabc and daaaat )

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?

ab123csde 1 match (match at ab123csde )

[0-9]{2,4} 12 and 345673 3 matches ( 12 , 3456 , 73 )

1 and 2 No match

| - Alternation
Vertical bar | is used for alternation ( or operator).
Expression String Matched?

cde No match

a|b ade 1 match (match at ade )

acdbea 3 matches (at acdbea )

Here, a|b match any string that contains either a or b

() - 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

(a|b|c)xz abxz 1 match (match at abxz )

axz cabxz 2 matches (at axzbc cabxz )

\ - 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:

\A - Matches if the specified characters are at the start of a string.


Expression String Matched?

the sun Match


\Athe
In the sun No match

\b - Matches if the specified characters are at the beginning or end of a word.


Expression String Matched?

football Match

\bfoo a football Match

afootball No match

the foo Match

foo\b the afoo test Match

the afootest 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

\Bfoo a football No match

afootball Match
Expression String Matched?

the foo No match

foo\B the afoo test No match

the afootest Match

\d - Matches any decimal digit. Equivalent to [0-9]

Expression String Matched?

12abc3 3 matches (at 12abc3 )


\d
Python No match

\D - Matches any non-decimal digit. Equivalent to [^0-9]

Expression String Matched?

1ab34"50 3 matches (at 1ab34"50 )


\D
1345 No match

\s - Matches where a string contains any whitespace character. Equivalent to [ \t\n\r\f\v] .

Expression String Matched?

Python RegEx 1 match


\s
PythonRegEx No match
\S - Matches where a string contains any non-whitespace character. Equivalent to [^ \t\n\r\f\v] .

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

way, underscore _ is also considered an alphanumeric character.


Expression String Matched?

12&": ;c 3 matches (at 12&": ;c )


\w
%"> ! No match

\W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_]

Expression String Matched?

1a2%c 1 match (at 1a2%c )


\W
Python No match

\Z - Matches if the specified characters are at the end of a string.


Expression String Matched?

I like Python 1 match

Python\Z I like Python Programming No match

Python is fun. No match

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

string = 'hello 12 hi 89. Howdy 34'


pattern = '\d+'

result = re.findall(pattern, string)


print(result)

# Output: ['12', '89', '34']

If the pattern is not found, re.findall() returns an empty list.

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

string = 'Twelve:12 Eighty nine:89.'


pattern = '\d+'

result = re.split(pattern, string)


print(result)

# Output: ['Twelve:', ' Eighty nine:', '.']


Run Code

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: ['Twelve:', ' Eighty nine:89 Nine:9.']


Run Code

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()

# Program to remove all whitespaces


import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'

# empty string
replace = ''

new_string = re.sub(pattern, replace, string)


print(new_string)

# Output: abc12de23f456
Run Code

If the pattern is not found, re.sub() returns the original string.

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'

# matches all whitespace characters


pattern = '\s+'
replace = ''

new_string = re.sub(r'\s+', replace, string, 1)


print(new_string)

# 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()

# Program to remove all whitespaces


import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'

# empty string
replace = ''

new_string = re.subn(pattern, replace, string)


print(new_string)

# 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 .

match = re.search(pattern, str)


Example 5: re.search()

import re

string = "Python is fun"

# check if 'Python' is at the beginning


match = re.search('\APython', string)

if match:
print("pattern found inside the string")
else:
print("pattern not found")

# Output: pattern found inside the string

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.

Python program to illustrate the concept


# of threading
# importing the threading module
import threading

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()

# wait until thread 1 is completely executed


t1.join()
# wait until thread 2 is completely executed
t2.join()

# both threads completely executed


print("Done!")

Square: 100
Cube: 1000
Done!

Multithreading

import Queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):


def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name

def process_data(threadName, q):


while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]


nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1

# Create new threads


for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1

# Fill the queue


queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()

# Wait for queue to empty


while not workQueue.empty():
pass

# Notify threads it's time to exit


exitFlag = 1

# Wait for all threads to complete


for t in threads:
t.join()
print "Exiting Main Thread"
When the above code is executed, it produces the following result −
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread

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

Following is the example of connecting with MySQL database "TESTDB"


#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = cursor.fetchone()
print "Database version : %s " % data

# disconnect from server


db.close()

Creating Database Table


Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
Example
Let us create Database table EMPLOYEE −
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist 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)

# disconnect from server


db.close()
NSERT Operation
It is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record into EMPLOYEE table −
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

Practical no. 5
Write a Python Program to demonstrate different types of exception handing.

Python try...except Block


The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block:

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.")

# Output: Error: Denominator cannot be 0.


Run Code

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.

Catching Specific Exceptions in Python


For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle
each exception differently.
The argument type of each except block indicates the type of exception that can be handled by it. For
example,
try:

even_numbers = [2,4,6,8]
print(even_numbers[5])

except ZeroDivisionError:
print("Denominator cannot be 0.")

except IndexError:
print("Index Out of Bound.")

# Output: Index Out of Bound


Run Code

Python try with else clause


In some situations, we might want to run a certain block of code if the code block inside try runs
without any errors.
For these cases, you can use the optional else keyword with the try statement.
Let's look at an example:

# program to print the reciprocal of even numbers

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 GUI – tkinter

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.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer screen.

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.

3 Checkbutton The Checkbutton is used to display the CheckButton 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.

9 Menu It is used to add menu items to the user.


10 Message The Message widget is used to display the message-box to the user.

11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is provided with various opt
among them.

12 Scale It is used to provide the slider to the user.

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

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindow It is like a container widget that contains horizontal or vertical panes.

17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the desktop based applications.

Python Tkinter Geometry


The Tkinter geometry specifies the method by using which, the widgets are represented on display. The python
Tkinter provides the following geometry methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method


The pack() widget is used to organize widget in the block. The positions widgets added to the python application
using the pack() method can be controlled by using the various options specified in the method call.

However, the controls are less and widgets are generally added in the less organized manner.

The syntax to use the pack() is given below.

syntax

1. widget.pack(options)

A list of possible options that can be passed in pack() is given below.


o expand: If the expand is set to true, the widget expands to fill any space.
o Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine whether the widget
contains any extra space.
o size: it represents the side of the parent to which the widget is to be placed on the window.

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

# get the current date and time


now = datetime.datetime.now()

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

# time(hour = 0, minute = 0, second = 0)


a = time()
print(a)

# time(hour, minute and second)


b = time(11, 34, 56)
print(b)

# time(hour, minute and second)


c = time(hour = 11, minute = 34, second = 56)
print(c)

# time(hour, minute, second, microsecond)


d = time(11, 34, 56, 234566)
print(d)
Run Code

Output

a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566

Example : Print hour, minute, second and microsecond

Once we create the time object, we can easily print its attributes such as hour , minute etc. For
example,
from datetime import time

a = time(11, 34, 56)

print("Hour =", a.hour)


print("Minute =", a.minute)
print("Second =", a.second)
print("Microsecond =", a.microsecond)
Run Code

Output

Hour = 11
Minute = 34
Second = 56
Microsecond = 0

Practical no.8
Write a Python program to create server-client and exchange basic
information.

Python Socket Programming


To understand python socket programming, we need to know about three interesting topics - Socket
Server, Socket Client and Socket. So, what is a server? Well, a server is a software that waits for client
requests and serves or processes them accordingly. On the other hand, a client is requester of this service. A
client program request for some resources to the server and server responds to that request. Socket is the
endpoint of a bidirectional communications channel between server and client. Sockets may communicate
within a process, between processes on the same machine, or between processes on different machines. For any
communication with a remote program, we have to connect through a socket port. The main objective of this
socket programming tutorial is to get introduce you how socket server and client communicate with each other.
You will also learn how to write python socket server program.

Python Socket Example


We have said earlier that a socket client requests for some resources to the socket server and the server responds
to that request. So we will design both server and client model so that each can communicate with them. The
steps can be considered like this.

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():

# get the hostname

host = socket.gethostname()

port = 5000 # initiate port no above 1024

server_socket = socket.socket() # get instance

# look closely. The bind() function takes tuple as argument

server_socket.bind((host, port)) # bind host address and port together

# configure how many client the server can listen simultaneously

server_socket.listen(2)

conn, address = server_socket.accept() # accept new connection

print("Connection from: " + str(address))

while True:

# receive data stream. it won't accept data packet greater than 1024 bytes

data = conn.recv(1024).decode()

if not data:

# if data is not received break


break

print("from connected user: " + str(data))

data = input(' -> ')

conn.send(data.encode()) # send data to the client

conn.close() # close the connection

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.

Python Socket Client


We will save python socket client program as socket_client.py. This program is similar to the server program,
except binding. The main difference between server and client program is, in server program, it needs to bind
host address and port address together. See the below python socket client example code, the comment will help
you to understand the code.

import socket

def client_program():

host = socket.gethostname() # as both code is running on same pc

port = 5000 # socket server port number

client_socket = socket.socket() # instantiate

client_socket.connect((host, port)) # connect to the server


message = input(" -> ") # take input

while message.lower().strip() != 'bye':

client_socket.send(message.encode()) # send message

data = client_socket.recv(1024).decode() # receive response

print('Received from server: ' + data) # show in terminal

message = input(" -> ") # again take input

client_socket.close() # close the connection

if __name__ == '__main__':

client_program()

Python Socket Programming Output


To see the output, first run the socket server program. Then run the socket client program. After that, write
something from client program. Then again write reply from server program. At last, write bye from client
program to terminate both program.

ankaj$ python3.6 socket_server.py

Connection from: ('127.0.0.1', 57822)

from connected user: Hi

-> Hello

from connected user: How are you?

-> Good

from connected user: Awesome!


-> Ok then, bye!

pankaj$

pankaj$ python3.6 socket_client.py

-> Hi

Received from server: Hello

-> How are you?

Received from server: Good

-> Awesome!

Received from server: Ok then, bye!

-> 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

 Blu is 10 years old


 Woo is 15 years old

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).

Example 2: Use of Inheritance in Python


# base class
class Animal:

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!!")

# Create object of the Dog class


dog1 = Dog()

# Calling members of the base class


dog1.eat()
dog1.sleep()

# Calling member of the derived class


dog1.bark();
Run Code

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.

Let's see an example,

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...")

# create an object of Square


s1 = Square()
s1.render()

# create an object of Circle


c1 = Circle()
c1.render()
Run Code

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

# method to calculate area


def calculate_area(self):
print("Area of Room =", self.length * self.breadth)

# create object of Room class


study_room = Room()

# assign values to all the attributes


study_room.length = 42.5
study_room.breadth = 30.8

# access method inside class


study_room.calculate_area()
Run Code

Output
Area of Room = 1309.0

In the above example, we have created a class named Room with:


 Attributes: length and breadth

 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

# Get base interfaces


print(DerivedI.__bases__)

# Ask whether baseI extends


# DerivedI
print(BaseI.extends(DerivedI))

# Ask whether baseI is equal to


# or is extended by DerivedI
print(BaseI.isEqualOrExtendedBy(DerivedI))

# Ask whether baseI is equal to


# or extends DerivedI
print(BaseI.isOrExtends(DerivedI))

# Ask whether DerivedI is equal


# to or extends BaseI
print(DerivedI.isOrExtends(DerivedI))

Output :
(<InterfaceClass __main__.BaseI>, )
False
True
False

You might also like