Python lab manual
Python lab manual
LAB MANUAL
Programme (UG/PG): UG
Semester: IV
Objectives:
Outcomes :
Software Requirements: Python 3.6 and more, Notepad ++, Sqlite, Ms access, Ms SQL
List of Experiments
Exp.
Name of Experiment Mapped CO
No
WAP to understand the basics of Python.
i) WAP to check if a Number is Odd or Even.
ii) WAP to develop a simple calculator.
1 iii) WAP to find a given year is a leap or not. 1
iv) WAP to find the factorial of the given number.
v) WAP to evaluate the Fibonacci series for n terms.
vi) WAP to determine whether a given number is Armstrong or not.
Write python programs to understand Advanced data types &
Functions
i) WAP to find circulating „n‟ values using List.
ii) WAP to Check whether an Item Exists in the Python Tuple or not.
iii) WAP to generate and print a dictionary that contains a number
(between 1 and n) in the form (x, x*x)
2 iv) WAP to perform mathematical set operations like union, 1
intersection, subtraction, and symmetric difference.
v) WAP to find the maximum from a list of numbers.
vi) WAP to Perform basic string operations.
vii) WAP to find Sum of N Numbers by importing array modules.
viii) WAP to multiply two matrices.
ix) WAP to swap Two Numbers using functions.
Write python programs to understand concepts of Object Oriented
Programming.
i) WAP to understand Classes, objects, Static method and inner class.
3 1
ii) WAP to understand Constructors.
iii) WAP to understand Inheritance and Polymorphism with Method
overloading and Method Overriding.
Write python programs to understand the concept of modules,
packages and exception handling.
i) WAP to find the distance between two points by importing a math
module.
4 2
ii) WAP to understand Lambda, map, reduce, filter and range
functions.
iii) WAP to understand different types of Exceptions.
iv) WAP to Create and Access a Python Package
Menu driven program for data structure using built in function for link
5 3
list, stack and queue.
Experiment No.
1
Name of Student
Roll No
if (num % 2) == 0:
else:
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
if choice == '1':
if num2 != 0:
else:
else:
else:
Source Code:
number = int(input("Enter a number: "))
factorial = 1
if number < 0:
elif number == 0:
else:
factorial *= i
Source Code:
n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci series:")
for i in range(n):
a, b = b, a + b
temp = number
dig = len(str(number))
digit = temp % 10
temp //= 10
if sum == number:
else:
Experiment No. 2
Name of Student
Roll No
Aim: Write python programs to understand Advanced data types & Functions.
Objective:
∙ To study concepts of Advanced data types & Functions in python programming.
Outcome: Students will be able to understand Advanced data types & Functions.
i) WAP to find circulating „n‟ values using List.
Source Code:
Input and Output:
Source Code:
iii) WAP to generate and print a dictionary that contains a number (between 1 and n) in the
form (x, x*x)
Source Code:
Input and Output:
iv) WAP to perform mathematical set operations like union, intersection, subtraction, and
symmetric difference.
Source Code:
Input and Output:
Conclusion: Thus the Python programs to understand Advanced data types & Functions are
executed successfully and the output is verified.
Experiment No. 3
Name of Student
Roll No
Source Code:
Input and Output:
iii) WAP to understand Inheritance and Polymorphism with Method overloading and Method
Overriding.
Source Code:
Input and Output:
Experiment No. 4
Name of Student
Roll No
Aim: Write python programs to understand the concept of modules, packages, multithreading and
exception handling.
Objective:
∙ To understand concepts of modules, packages, multithreading and exception handling.
Outcome: Students will be able to understand concepts of modules, packages, multithreading and
exception handling
i) WAP to find the Distance between Two Points by importing math module
Source Code:
Input and Output:
ii) WAP to understand Lambda, map, reduce, filter and range functions.
Source Code:
Input and Output:
Source Code:
Create a directory and include a __init__.py file in it to tell Python that the current directory is a
package.
Include other sub-packages or files you want.
Next, access them with the valid import statements.
Package (university)
__init__.py
student.py
faculty.py
Go to any directory in your laptop or desktop and create the above folder structure. After creating
the above folder structure include the following code in respective files.
Example
# student.py
class Student:
def get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"
# faculty.py
class Faculty:
def get_faculty_details(self):
LAB MANUAL [IV --- Python Lab] Page 13
Mahatma Gandhi Mission's College of Engineering and Technology
We have the above in the student.py and faculty.py files. Let's create another file to access those
classed inside it. Now, inside the package directory create a file named testing.py and include the
following code.
Example
# testing.py
# importing the Student and Faculty classes from respective files
from student import Student
from faculty import Faculty
If you run the testing.py file, then you will get the following result.
Name: John
Gender: Male
Year: 3
Name: Emma
Subject: Programming
Conclusion:
We have seen how to create and to access a package in Python.
Experiment No. 5
Name of Student
Roll No
Aim: Menu driven program for data structure using built in function for link list, stack and queue.
Objective:
∙ To understand concepts of data structure using built in functions for link
list, stack and queue.
Outcome: Students will be able to understand concepts of data structure using built in function for
link list, stack and queue.
Theory:
Stack
Stacks, like the name suggests, follow the Last-in-First-Out (LIFO) principle. As if stacking coins
one on top of the other, the last coin we put on the top is the one that is the first to be removed from
the stack later.
Queue
Queues, like the name suggests, follow the First-in-First-Out (FIFO) principle. As if
waiting in a queue for the movie tickets, the first one to stand in line is the first one to
buy a ticket and enjoy the movie.
Source Code:
Conclusion:
Experiment No. 6
Name of Student
Roll No
i) WAP to find the most frequent words in a text read from a file.
Source Code:
Input and Output:
iii) WAP to design Graphical user interface (GUI) using built-in tools in python (Tkinter,
PyQt,Kivy etc.).
Source Code:
Conclusion:
We successfully implement basic python programs to demonstrate File handling and GUI using
Tkinter.
Experiment No. 7
Name of Student
Roll No
Conclusion:
Experiment No. 8
Name of Student
Roll No
Aim: Write python programs to create a simple socket for basic information exchange between
server and client.
Objective:
∙ To study socket programming using python.
Outcome: Students will be able to create a simple socket for basic information exchange between
server and client.
Python Socket Programming
To understand python socket programming, we need to know about three interesting topics –
1. Socket Server
2. Socket Client
3. 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 a requester of this service. A client programs a request for
some resources to the server and the 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 introduce you to how
socket server and client communicate with each other. You will also learn how to write
a python socket server program.
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 models so that each can communicate with them.
We will save the python socket server program as socket_server.py. To use python
socket connection, we need to import the socket module.Then, sequentially we need to
perform some task to establish connection between server and client.
We can obtain a host address by using the socket.gethostname() function. It is
recommended to use a port address above 1024 because port numbers 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
host = socket.gethostname()
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
def client_program():
host = socket.gethostname() # as both code is running on same
pc port = 5000 # socket server port number
To see the output, first run the socket server program. Then run the socket client
program. After that, write something from a client program. Then again write a reply
from the server program. At last, write bye from client program to terminate both
programs. Below the short video will show how it worked on my test run of socket
server and client example programs.
Notice that the socket server is running on port 5000 but the client also requires a socket
port to connect to the server. This port is assigned randomly by client connect call. In
this case, it’s 57822.
So, that’s all for Python socket programming, python socket server and socket client
example programs.
Conclusion:
Experiment No.
9
Name of Student
Roll No
Python Multithreading
3. It shares resources and its state with sub-threads (child) which makes it more economical.
6. The system does not require too much memory to store multiple threads.
There are two main modules of multithreading used to handle threads in Python
Thread modules
It is started with Python 3, designated as obsolete, and can only be accessed with _thread that
supports backward compatibility.
Syntax:
To implement the thread module in Python, we need to import a thread module and then define a
function that performs some action by setting the target with a variable.
Threading Modules
The threading module is a high-level implementation of multithreading used to deploy an
application in Python
To use multithreading, we need to import the threading module in the Python Program.
Methods Description
o Args: It defines the arguments that are passed to the target function name.
In the above code, we invoked the print_hello() function as the target parameter. The print_hello()
contains one parameter n, which passed to the args parameter.
3. Start a new thread: To start a thread in Python multithreading, call the thread class's object.
The start() method can be called once for each thread object; otherwise, it throws an exception
error.
Syntax:
t1.start() t2.start()
4. Join method: It is a join() method used in the thread class to halt the main thread's
execution and waits till the complete execution of the thread object. When the thread
object is completed, it starts the execution of the main thread in Python.
Joinmethod.py
import threading
def print_hello(n):
Print("Hello, how old are you? ", n)
T1 = threading.Thread( target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")
Output:
Hello, how old are you? 20 Thank you
When the above program is executed, the join() method halts the execution of the main
thread and waits until the thread t1 is completely executed. Once the t1 is successfully
executed, the main thread starts its execution.
Note: If we do not use the join() method, the interpreter can execute any
print statement
inside the Python program. Generally, it executes the first print statement
because the
interpreter executes the lines of codes from the
program's start.
1. Synchronizing Threads in Python
It is a thread synchronization mechanism that ensures no two threads can simultaneously execute a
particular segment inside the program to access the shared resources. The situation may be termed as
critical sections. We use a race condition to avoid the critical section condition, in which two threads
do not access resources at the same time.
Conclusion:
Experiment No. 10
Name of Student
Roll No
Experiment No. 11
Name of Student
Roll No
i) WAP to implement basic operations using pandas like series, data frames, indexing,
filtering, combining and merging data frames.
Source Code:
Input and Output:
Conclusion:
Experiment No. 12
Name of Student
Roll No
Theory:
Here, we are going to learn how to send simple basic mail using Python code.
Python, being a powerful language, doesn't need any external library to import and offers
a native library to send emails- “SMTP lib”.
“smtplib” creates a Simple Mail Transfer Protocol client session object which is
used to send emails to any valid email id on the internet. Different websites use different
port numbers.
Here, we are using a Gmail account to send mail. Port number used here is ‘587’. And if
you want to send mail using a website other than Gmail, you need to get the
corresponding information.
Steps to send mail from Gmail account:
After that, to create a session, we will be using its SMTP instance to encapsulate an
SMTP connection.
s = smtplib.SMTP('smtp.gmail.com', 587)
In this, you need to pass the first parameter of the server location and the second
parameter of the port to use. For Gmail, we use port number 587.
For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer
Security) encrypts all the SMTP commands. After that, for security and authentication, you need to
pass your Gmail account credentials in the login instance.The compiler will show an authentication
error if you enter invalid email id or password.
Store the message you need to send in a variable, say, message. Using the sendmail()
instance, send your message. sendmail() uses three parameters: sender_email_id,
receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
This will send the email from your account. After you have completed your task,
terminate the SMTP session by using quit().
s.starttls()
# Authentication
s.login("sender_email_id", "sender_email_id_password")
# message to be sent
message = "Message_you_need_to_send"
If you need to send the same message to different people. You can use for loop for that.
For example, you have a list of email ids to which you need to send the same mail. To do
so, insert a “for” loop between the initialization and termination of the SMTP session.
Loop will initialize turn by turn and after sending the email, SMTP session will be
terminated.
li = ["[email protected]", "[email protected]"]
for dest in li:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("sender_email_id", "sender_email_id_password")
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", dest, message)
s.quit()
Important Points:
Ø This code can send simple mail which doesn’t have any attachment or any subject.
Ø One of the most amazing things about this code is that we can send any number of
emails using this and Gmail mostly put your mail in the primary section. Sent mails
would not be detected as Spam generally.
Ø File handling can also be used to fetch email id from a file and further used for
sending the emails.
Conclusion: