0% found this document useful (0 votes)
10 views

Python lab manual

The document is a lab manual for the Python Lab course (CSL405) at Mahatma Gandhi Mission's College of Engineering and Technology for the academic year 2024-25. It outlines the objectives, outcomes, software requirements, and a comprehensive list of experiments that students will perform to learn Python programming, including basics, advanced data types, object-oriented programming, and web development. Each experiment includes aims, objectives, outcomes, and source code examples for various Python applications.

Uploaded by

pfake580
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python lab manual

The document is a lab manual for the Python Lab course (CSL405) at Mahatma Gandhi Mission's College of Engineering and Technology for the academic year 2024-25. It outlines the objectives, outcomes, software requirements, and a comprehensive list of experiments that students will perform to learn Python programming, including basics, advanced data types, object-oriented programming, and web development. Each experiment includes aims, objectives, outcomes, and source code examples for various Python applications.

Uploaded by

pfake580
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

LAB MANUAL

Programme (UG/PG): UG

Semester: IV

Course Code: CSL405

Course Title: Python Lab

Prepared By: Prof. Amruta Kothavade

Approved By: ----------------------------

LAB MANUAL [IV --- Python Lab] Page 1


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Objectives:

The main objective of the course is:

1. Basics of Python programming


2. Decision Making, Data structure and Functions in Python
3. Object Oriented Programming using Python
4. Web framework for developing

Outcomes :

At the end of the course the student should be able to:

1. To understand basic concepts in python.


2. To explore contents of files, directories and text processing with python.
3. To develop a program for data structure using built in functions in python.
4. To explore the django web framework for developing python-based web applications.
4. To understand Multithreading concepts using python.

Software Requirements: Python 3.6 and more, Notepad ++, Sqlite, Ms access, Ms SQL

LAB MANUAL [IV --- Python Lab] Page 2


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

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.

LAB MANUAL [IV --- Python Lab] Page 3


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Write python programs to understand File handling, GUI & database


programming.
i) WAP to find the most frequent words in a text read from a file.
6 2
ii) WAP to understand different file handling operations with pickle.
iv) WAP to design Graphical user interface (GUI) using built-in tools
in python (Tkinter, PyQt,Kivy etc.).
Program to demonstrate CRUD (create, read, update and delete)
7 4
operations on databases (SQLite/ MySQL) using python.
Creation of simple socket for basic information exchange between
8 4
server and client.
9 Programs on Threading using python. 5
Write python programs to understand Data visualization,analysis
10 i) WAP to implement different types of plots using Numpy and 4
Matplotlob
WAP to implement basic operations using pandas like series, data
11 4
frames, indexing, filtering, combining and merging data frames.
Write python programs to understand web programming using python.
12 4
Program to send email and read content of URL.

LAB MANUAL [IV --- Python Lab] Page 4


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No.
1

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write a program to understand the basics of Python.


Objectives:
∙ To study the basics of python programming.
Outcome: Students will be able to implement the basics of python programming.
i) WAP to check if a Number is Odd or Even.
Source Code:
num = int(input("ENTER A NUMBER: "))

if (num % 2) == 0:

print("IT IS A EVEN NUMBER!!")

else:

print("IT IS A ODD NUMBER!!")

Input and Output:

ii) WAP to develop a simple calculator.


Source Code:
print("Select operation:")

print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

LAB MANUAL [IV --- Python Lab] Page 5


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

choice = input("Enter your choice: ")

if choice in ('1', '2', '3', '4'):

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if choice == '1':

print(f"The result is: {num1 + num2}")

elif choice == '2':

print(f"The result is: {num1 - num2}")

elif choice == '3':

print(f"The result is: {num1 * num2}")

elif choice == '4':

if num2 != 0:

print(f"The result is: {num1 / num2}")

else:

print("Error! Division by zero.")

else:

print("Invalid input. Please select a valid operation.")

LAB MANUAL [IV --- Python Lab] Page 6


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

iii) WAP to find a given year is a leap or not.


Source Code:
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(f"{year} is a leap year.")

else:

print(f"{year} is not a leap year.")

Input and Output:

iv) WAP to find the factorial of the given number.

Source Code:
number = int(input("Enter a number: "))

factorial = 1

if number < 0:

print("Factorial is not defined for negative numbers.")

elif number == 0:

print("The factorial of 0 is 1.")

else:

for i in range(1, number + 1):

factorial *= i

print(f"The factorial of {number} is {factorial}.")

Input and Output:

LAB MANUAL [IV --- Python Lab] Page 7


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

v) WAP to evaluate the Fibonacci series for n terms.

Source Code:
n = int(input("Enter the number of terms: "))

a, b = 0, 1

print("Fibonacci series:")

for i in range(n):

print(a, end=" ")

a, b = b, a + b

Input and Output:

vi) WAP to determine whether a given number is Armstrong or not.

Source Code: number = int(input("Enter a number: "))


sum = 0

temp = number

dig = len(str(number))

while temp > 0:

digit = temp % 10

sum += digit ** dig

temp //= 10

if sum == number:

print(f"{number} is an Armstrong number.")

else:

print(f"{number} is not an Armstrong number.")

Input and Output:

Conclusion: Thus we implemented the basics of python program


LAB MANUAL [IV --- Python Lab] Page 8
Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 2

Name of Student

Roll No

DOP DOS Marks/Grade Signature

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:

ii) WAP to WAP to Check if an Item Exists in the Python Tuple

Source Code:

Input and Output:

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:

LAB MANUAL [IV --- Python Lab] Page 9


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

v) WAP to find the maximum from a list of numbers.


Source Code:
Input and Output:

vi) WAP to Perform basic string operations.


Source Code:

Input and Output:

vii) WAP to find Sum of N Numbers by importing array modules.


Source Code:
Input and Output:

viii) WAP to multiply two matrices.


Source Code:
Input and Output:

ix) WAP to swap Two Numbers using functions.


Source Code:
Input and Output:

Conclusion: Thus the Python programs to understand Advanced data types & Functions are
executed successfully and the output is verified.

LAB MANUAL [IV --- Python Lab] Page 10


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 3

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs to understand concepts of Object Oriented Programming.


Objective:
∙ Object Oriented Programming concepts in python.
Outcome: Students will be able to understand concepts of Object Oriented Programming in python.
i) WAP to understand Classes, objects, Static method and inner class.
Source Code:
Input and Output:

ii) WAP to understand Constructors.

Source Code:
Input and Output:

iii) WAP to understand Inheritance and Polymorphism with Method overloading and Method
Overriding.
Source Code:
Input and Output:

LAB MANUAL [IV --- Python Lab] Page 11


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 4

Name of Student

Roll No

DOP DOS Marks/Grade Signature

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:

iii) WAP to understand different types of Exceptions.


Source Code:
Input and Output:

iv) WAP to Create and Access a Python Package


Source Code:

Follow the below steps to create a package in Python

LAB MANUAL [IV --- Python Lab] Page 12


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

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.

Let's create a simple package that has the following structure.

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 __init__(self, student):


self.name = student['name']
self.gender = student['gender']
self.year = student['year']

def get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"

# faculty.py
class Faculty:

def __init__(self, faculty):


self.name = faculty['name']
self.subject = faculty['subject']

def get_faculty_details(self):
LAB MANUAL [IV --- Python Lab] Page 13
Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

return f"Name: {self.name}\nSubject: {self.subject}"

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

# creating dicts for student and faculty


student_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'}
faculty_dict = {'name': 'Emma', 'subject': 'Programming'}

# creating instances of the Student and Faculty classes


student = Student(student_dict)
faculty = Faculty(faculty_dict)

# getting and printing the student and faculty details


print(student.get_student_details())
print()
print(faculty.get_faculty_details())

Input and Output:

If you run the testing.py file, then you will get the following result.

Name: John
Gender: Male
Year: 3

Name: Emma
Subject: Programming

LAB MANUAL [IV --- Python Lab] Page 14


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Conclusion:
We have seen how to create and to access a package in Python.

LAB MANUAL [IV --- Python Lab] Page 15


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 5

Name of Student

Roll No

DOP DOS Marks/Grade Signature

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.

To implement a stack, therefore, we need two simple operations:

1. Push()- · adds an element to the top of the stack:


2. Pop()- · removes the element at the top of the stack:

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.

To implement a queue, therefore, we need two simple operations:

1. enqueue- adds an element to the end of the queue:

2. dequeue - removes the element at the beginning of the queue:

Source Code:

Conclusion:

LAB MANUAL [IV --- Python Lab] Page 16


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 6

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs to understand File handling and GUI.


Objective:
∙ To study File handling and GUI.
Outcome: Students will be able to write python programs on File handling and GUI.

i) WAP to find the most frequent words in a text read from a file.
Source Code:
Input and Output:

ii) WAP to understand different file handling operations with pickle.


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.

LAB MANUAL [IV --- Python Lab] Page 17


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 7

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs to understand database handling.


Objective:
∙ To study database handling.
Outcome: Students will be able to write python programs on database handling.

WAP to simulate Python MYSQL.

Input and Output:

Conclusion:

LAB MANUAL [IV --- Python Lab] Page 18


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 8

Name of Student

Roll No

DOP DOS Marks/Grade Signature

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.

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 models so that each can communicate with them.

LAB MANUAL [IV --- Python Lab] Page 19


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

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 the server program will respond accordingly to client requests.
4. Client program will terminate if the user enters a “bye” message. Server program
will also terminate when the client program terminates, this is optional and we can keep
the server program running indefinitely or terminate with some specific command in
client request.

Python Socket Server

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

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:

LAB MANUAL [IV --- Python Lab] Page 20


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

# 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 requests.
If you want the 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 requests.
Python Socket Client
We will save the 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 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.

LAB MANUAL [IV --- Python Lab] Page 21


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

pankaj$ 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! -> Byepankaj$

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:

LAB MANUAL [IV --- Python Lab] Page 22


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No.
9

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs on threading.


Objective:
∙ To study threading using python.
Outcome: Students will be able to understand threading using python.
Theory:

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.

Benefits of Multithreading in Python

Following are the benefits to create a multithreaded application in Python, as follows:


1. It ensures effective utilization of computer system resources.

2. Multithreaded applications are more responsive.

3. It shares resources and its state with sub-threads (child) which makes it more economical.

4. It makes the multiprocessor architecture more effective due to similarity.

5. It saves time by executing multiple threads at the same time.

6. The system does not require too much memory to store multiple threads.

LAB MANUAL [IV --- Python Lab] Page 23


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

When to use Multithreading in Python?


It is a very useful technique for time-saving and improving the performance of an
application. Multithreading allows the programmer to divide application tasks into
subtasks and simultaneously run them in a program. It allows threads to communicate
and share resources such as files, data, and memory to the same processor. Furthermore,
it increases the user's responsiveness to continue running a program even if a part of the
application is the length or blocked
How to achieve multithreading in Python?

There are two main modules of multithreading used to handle threads in Python

1. The thread module

2. The threading module

Thread modules

It is started with Python 3, designated as obsolete, and can only be accessed with _thread that
supports backward compatibility.

Syntax:

thread.start_new_thread ( function_name, args[, kwargs] )

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

start() A start() method is used to initiate the activity of a


thread. And it calls only once for each thread so that
the execution of the thread can begin.
run() A run() method is used to define a thread's activity
and can be overridden by a class that extends the
threads class.
join() A join() method is used to block the execution of
another code until the thread terminates.
LAB MANUAL [IV --- Python Lab] Page 24
Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

o Target: It defines the function name that is executed by the thread.

o Args: It defines the arguments that are passed to the target function name.

For example: import threading def print_hello(n):


print("Hello, how old are you ", n)
t1 = threading.Thread( target = print_hello, args =(18, ))

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

LAB MANUAL [IV --- Python Lab] Page 25


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

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:

LAB MANUAL [IV --- Python Lab] Page 26


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 10

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs to understand Data visualization


Objective:
∙ To study Data visualization using python.
Outcome: Students will be able to understand Data visualization.

i) WAP to implement different types of plots using Numpy and Matplotlob


Source Code:
Conclusion:

LAB MANUAL [IV --- Python Lab] Page 27


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 11

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs to understand Data analysis


Objective:
∙ To study Data analysis using python.
Outcome: Students will be able to understand Data analysis.

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:

LAB MANUAL [IV --- Python Lab] Page 28


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

Experiment No. 12

Name of Student

Roll No

DOP DOS Marks/Grade Signature

Aim: Write python programs to understand web programming using python.


Objective:
∙ To study web programming using python.
Outcome: Students will be able to understand web programming using python.

i) Program to send email and read content of URL.

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:

First of all, “smtplib” library needs to be imported.

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

LAB MANUAL [IV --- Python Lab] Page 29


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

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

# Python code to illustrate Sending


mail from # your Gmail account
import smtplib

# creates SMTP session

s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security

s.starttls()

# Authentication
s.login("sender_email_id", "sender_email_id_password")

# message to be sent

message = "Message_you_need_to_send"

# sending the mail

s.sendmail("sender_email_id", "receiver_email_id", message)


# terminating the session s.quit()

Sending same message to multiple people

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.

# Python code to illustrate Sending mail # to multiple users

# from your Gmail account import smtplib

# list of email_id to send the mail

LAB MANUAL [IV --- Python Lab] Page 30


Mahatma Gandhi Mission's College of Engineering and Technology

Department of Computer Science and Engineering (AIML &DS)

Academic Year 2024-25(Even Sem)

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:

LAB MANUAL [IV --- Python Lab] Page 31

You might also like