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

Python File

This document outlines a programming lab for a Python programming course. It provides details on the course objectives, outcomes, and their mapping to program outcomes. It also includes a practical record sheet for students to log their experiments and results.

Uploaded by

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

Python File

This document outlines a programming lab for a Python programming course. It provides details on the course objectives, outcomes, and their mapping to program outcomes. It also includes a practical record sheet for students to log their experiments and results.

Uploaded by

27adityajha27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

PROGRAMMING IN PYTHON LAB

(CIE – 332P)

Faculty name: Dr. Deepika Bansal Student Name: Shashwat Shukla


Designation: Assistant Professor Roll No. : 13814803121
Department: IT Department Semester : 6th
Group : AIML-IV-C

Maharaja Agrasen Institute of Technology, PSP Area,


Sector – 22, Rohini, New Delhi – 110085
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

VISION

To attain global excellence through education, innovation, research, and work ethics with the
commitment to serve humanity.

MISSION

M1. To promote diversification by adopting advancement in science, technology,


management, and allied discipline through continuous learning

M2. To foster moral values in students and equip them for developing sustainable solutions to
serve both national and global needs in society and industry.

M3. To digitize educational resources and process for enhanced teaching and effective
learning.

M4. To cultivate an environment supporting incubation, product development, technology


transfer, capacity building and entrepreneurship.

M5. To encourage faculty-student networking with alumni, industry, institutions, and


other stakeholders for collective engagement.
Department of Information Technology

VISION

To establish a center of excellence promoting Information Technology related education and


research for preparing technocrats and entrepreneurs with ethical values.

MISSION

M1: To excel in the field by imparting quality education and skills for software development
and applications.

M2: To establish a conducive environment that promotes intellectual growth and research.

M3: To facilitate students to acquire entrepreneurial skills for innovation and product
development.

M4: To encourage students to participate in competitive events and industry interaction with a
focus on continuous learning.
Programming Python Lab CO’s and its mapping with
PO’s and PSO’s
Program Specific Outcomes (PSOs)

PSO1: Students are equipped with programming technologies applied in the industry.
PSO2: Students are able to provide efficient solutions for emerging challenges in the
computation domain such as Artificial Intelligence, Data Science, Web Technologies.
PSO3: Students are able to apply domain knowledge and expertise in the field of Information
Technology for enhancing research capability to transform innovative ideas into reality.

Program Outcomes (POs)


Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change
CO-PO Mapping

Course Objectives :
1. Learn the syntax and semantics of Python Programming Language.
2. Write Python functions to facilitate code reuse and manipulate strings.
3. Illustrate the process of structuring the data using lists, tuples and dictionaries.
4. Demonstrate the use of built-in functions to navigate the file system.
Course Outcomes (CO)
CO 1 Demonstrate the concepts of control structures in Python.
CO 2 Implement Python programs using functions and strings.
CO 3 Implement methods to create and manipulate lists, tuples and dictionaries
CO 4 Apply the concepts of file handling and regExusing packages.
Course Outcomes (CO) to Programme Outcomes (PO) mapping (scale 1: low, 2: Medium, 3: High)
PO01 PO02 PO03 PO04 PO05 PO06 PO07 PO08 PO09 PO10 PO11 PO12
CO 1 3 2 2 2 3 - - - 3 2 2 3
CO 2 3 2 2 2 3 - - - 3 2 2 3
CO 3 3 2 2 2 3 - - - 3 2 2 3
CO 4 3 2 2 2 3 - - - 3 2 2 3

CO-PSO Mapping

PSO01 PSO02 PSO03


CO 1 3 2 2
CO 2 3 2 2
CO 3 3 2 2
CO 4 3 2 2
Rubrics Evaluation
PROGRAMMING IN PYTHON LAB

PRACTICAL RECORD

PAPER CODE : CIE-332P

Name of the student : Shashwat Shukla

University Roll No. : 13814803121

Branch : Information Technology

Section/ Group : AIML-IV-C

PRACTICAL DETAILS

a) Experiments according to the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Mar
ks
(15)
R1 R2 R3 R4 R5
1. Basic data types and
29-01-24 operators: Create a program
that prompts the user for
their name and age and prints
a personalized message.
2. Conditional statements:
29-01-24 Create a program that
prompts the user for their age
and tells them if they can
vote in the next election.
3. Loops: Create a program that
29-01-24 calculates the factorial of a
number entered by the user
using a loop.
4. Lists and arrays: Create a
05-02-24 program that prompts the
user for a list of numbers and
then sorts them in ascending
order.
5. Strings and string
05-02-24 manipulation: Create a
program that prompts the
user for a string and then
prints out the string reversed.
6. Functions: Create a program
05-02-24 that defines a function to
calculate the area of a circle
based on the radius entered
by the user.
7. Classes and objects: Create a
12-02-24 program that defines a class
to represent a car and then
creates an object of that class
with specific attributes.
8. File input/output: Create a
12-02-24 program that reads data
from a file and writes it to
another file in a different
format.
9. Regularexpressions:
12-02-24 Create a program that uses
regular expressions to find
all instances of a specific
pattern in a text file.

10. Exception handling: Create


19-02-24 a program that prompts the
user for two numbers and
then divides them, handling
any exception that may arise.
11. GUI programming: Create a
19-02-24 program that uses a graphical
user interface (GUI) to allow
the user to perform simple
calculations.
12. Web scraping: Create a
19-02-24 program that uses a web
scraping library to extract
data from a website and then
stores it in a database.
13. Data visualization: Create a
program that reads data from
26-02-24 a file and then creates a
visualization of that data
using a data visualization
library.
14. Machine learning: Create a
26-02-24 program that uses a machine
learning library to classify
images based on their
content.
15. Networking: Create a
program that uses a
26-02-24 networking library to
communicate with a server
and retrieve data from it.

b) Experiments Additional the list provided by GGSIPU

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Marks
(15)
R1 R2 R3 R4 R5
16. Write a python script to
04-03-24 print the current date in
the following format
“Sun May 2902:26:23
IST 2017
17. Write a program to
04-03-24 create, append and
remove lists in python.

18. Write a program to


04-03-24 demonstrate working
with tuples in python.

19. Write a program to


11-03-24 demonstrate working
with dictionaries in
python.
20. Write a Python program
11-03-24 to convert temperatures
to and from Celsius,
Fahrenheit
21. Write a program that
accepts the lengths of
three sides of a triangle
as inputs. The program
11-03-24
output should indicate
whether or not the
triangle is a right
triangle.
22. Write a python program
to define a module and
18-03-24 import a specific function
in that module to another
program.
23. Write a Python class to
18-03-24 convert an integer to a
roman numeral.
24. Write a Python class to
18-03-24 reverse a string word by
word.

25. Write a Python program


15-04-24 to implement linear
search.

26. Write a Python program


15-04-24 to implement binary
search.

27. Write a Python program


15-04-24 to implement insertion
sort.

28. Write a Python program


22-04-24 to implement selection
sort.

29. Write a Python program


22-04-24 to implement tower of
Hanoi.

30. Write a Python program


22-04-24 to implement matrix
multiplication.
Experiment – 1

AIM: Basic data types and operators: Create a program that prompts the user for their
name and age and prints a personalized message.

THEORY: For this experiment, we'll be working with basic data types (strings and integers)
and operators (input, print):

Data Types:

1. String: A sequence of characters enclosed within either single quotes (' ') or double quotes
(" "). In Python, strings are immutable, meaning they cannot be changed once created. They
are used to represent text data.
2. Integer: A whole number without any decimal points. Integers can be positive, negative, or
zero. They are used to represent numeric data.

Operators:

1.Input Operator: In Python, the input() function is used to take input from the user. It
prompts the user for input and returns a string containing the data entered by the user.
2. Print Operator: The print() function is used to display output to the user. It takes one or
more arguments and prints them as a single string.

CODE:

# Aditya Singla - 04514803121


age = input("Enter age: ")
name = input("Enter name: ")
print("Hi, my name is " + name + ", and I am " + age + " years old.")
Experiment – 2

AIM: Conditional statements: Create a program that prompts the user for their age
and tells them if they can vote in the next election.

THEORY: Conditional statements are used to execute different blocks of code based on
whether a certain condition is true or false. In Python, the if, elif (short for "else if"), and else
keywords are used to create conditional statements.

In this program:

int(input("Enter your age: ")) prompts the user to enter their age, converts the input to an
integer, and stores it in the variable age.

if age >= 18: checks if the user's age is greater than or equal to 18. If it is, the program prints
"You are eligible to vote in the next election.".

If the condition age >= 18 is not true, the else block is executed, and the program prints "You
are not eligible to vote in the next election.".

CODE:

# Aditya Singla - 04514803121


age=int(input("enter your age :"))
if(age>=18):
print("you are eligible to vote")
else:
print("you are not eligible to vote")
Experiment – 3

AIM: Loops: Create a program that calculates the factorial of a number entered by the
user using a loop.

THEORY: Loops are used to execute a block of code repeatedly as long as a certain
condition is true. In Python, two common types of loops are for loops and while loops.
for loops are used when you know the number of iterations in advance, such as iterating over
elements in a list or a range of numbers. While loops are used when you want to loop until a
specific condition is no longer true.

Factorial is a mathematical operation that multiplies a number by every integer smaller than
itself down to 1. It is denoted by the symbol '!', and it's used to find the product of all positive
integers up to a given positive integer.

For example, the factorial of 5, denoted as 5!, is calculated as follows: 5!=5×4×3×2×1=120.

CODE:

# Aditya Singla - 04514803121


num = int(input("enter the number you want to calculate factorial for"));
fact=1
for i in range(2,num+1):
fact *= i
print("factorial of",num,"is",fact)
Experiment – 4

AIM: Lists and arrays: Create a program that prompts the user for a list of numbers
and then sorts them in ascending order.

THEORY:

Lists: Lists in Python are a collection of items that are ordered and mutable (modifiable).
Lists can contain elements of different data types, including numbers, strings, or even other
lists. Elements in a list are indexed, with the first element having an index of 0, the second
element having an index of 1, and so on.

Sorting:
Sorting is the process of arranging items in a specific order, such as ascending or descending
order. Python provides built-in functions like sorted() and methods like sort() to sort lists.

CODE:

# Aditya Singla - 04514803121


arr = eval(input("Enter a list of numbers"))

def sort():
for i in range(0,len(arr)):
for j in range(i+1,len(arr)):
if(arr[i]>arr[j]):
temp=arr[i]
arr[i]=arr[j]
arr[j]=temp
sort()

for i in range(0,len(arr)):
print(arr[i],end=' ')
Experiment – 5

AIM: Strings and string manipulation: Create a program that prompts the user for a
string and then prints out the string reversed.

THEORY:

1. Strings in Python are sequences of characters, enclosed within either single quotes (' ') or
double quotes (" ").
2. Strings are immutable, meaning they cannot be changed after they are created. However,
you can create new strings based on existing strings.
3. Strings support various operations and methods for manipulation, such as concatenation,
slicing, and reversing.

CODE:

# Aditya Singla - 04514803121


str=input("enter a string -> ")
ans=""
for i in range(len(str)-1,-1,-1):
ans+=str[i]
print(ans)
Experiment – 6

AIM: Functions: Create a program that defines a function to calculate the area of a
circle based on the radius entered by the user.

THEORY:

1. Functions in Python are reusable blocks of code that perform a specific task.
2. Functions can take input arguments (parameters), perform some computation, and
optionally return a result.
3. Defining a function involves using the def keyword followed by the function name, input
parameters (if any), and a block of code.
4. Functions can be called (invoked) multiple times from different parts of the program.

CODE:

# Aditya Singla - 04514803121


def area_of_circle(r):
pi=3.147
area= pi*r*r
return area

radius=float(input("Enter Radius: "))


print("Area: ",area_of_circle(radius))
Experiment – 7

AIM: Classes and objects: Create a program that defines a class to represent a car and
then creates an object of that class with specific attributes.

THEORY:

1. A class is a blueprint for creating objects. It defines the properties (attributes) and
behaviors (methods) that objects of the class will have.
2. An object is an instance of a class. It represents a specific instance of the class and has its
own unique set of attributes.
3. Attributes are variables that hold data associated with a class or an object.
Methods are functions defined within a class that perform operations on the class's data.
.

CODE:

# Aditya Singla - 04514803121


class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def print_info(self):
print(f"This car is a {self.year} {self.make} {self.model}.")

# Create an object of the Car class


my_car = Car("Ford", "Mustang", 2023)

# Print information about the car


my_car.print_info()
Experiment – 8

AIM: File input/output: Create a program that reads data from a file and writes it to
another file in a different format.

THEORY:

1. File I/O operations in Python allow you to work with files on your computer's storage.
open() function is used to open a file.
2. It takes two arguments: the filename and the mode (e.g., 'r' for reading, 'w' for writing, 'a'
for appending).
3. read() and readlines() methods are used to read data from a file.
4. write() method is used to write data to a file.
5. close() method is used to close the file after performing file operations.
.

CODE:

# Aditya Singla - 04514803121


# Open the input file in read mode
with open('input.txt', 'r') as input_file:
# Read all lines from the input file
lines = input_file.readlines()

# Open the output file in write mode


with open('output.txt', 'w') as output_file:
# Write each line to the output file in a different format
for line in lines:
# Here, you can modify the format as per your requirement
# For example, you can split the line, manipulate the data, and then write it to the output
file
# In this example, let's just write the line as is, but in uppercase
output_file.write(line.upper())

# input.txt content
# This is line 1.
# This is line 2.
# This is line 3.
Experiment – 9

AIM: Regular expressions: Create a program that uses regular expressions to find all
instances of a specific pattern in a text file.

THEORY:

Regular Expressions: Regular expressions (regex) are sequences of characters that define a
search pattern. They are powerful tools for searching and manipulating strings. Python
provides the re module for working with regular expressions. Common regex operations
include searching for patterns, matching patterns, and replacing patterns in strings.

File Input/Output (I/O):


File I/O operations in Python allow you to read from and write to files on your computer's
storage.
.

CODE:

# Aditya Singla - 04514803121


import re

def find_pattern_in_file(file_path, pattern):


with open(file_path, 'r') as file:
text = file.read()
matches = re.findall(pattern, text)
return matches

def main():
file_path = 'sample_text.txt' # Update with your file path
pattern = r'\b\w+@\w+\.\w+\b' # Example pattern for finding email addresses

matches = find_pattern_in_file(file_path, pattern)


print("Matches found:")
for match in matches:
print(match)

if __name__ == "__main__":
main()

# text file content


[email protected] or [email protected].
Experiment – 10

AIM: Exception handling: Create a program that prompts the user for two numbers
and then divides them, handling any exceptions that may arise

THEORY:

1. Exception handling in Python allows you to gracefully handle errors and unexpected
situations that occur during program execution.
2. Python provides a try statement, which allows you to wrap code that might raise
exceptions.
3. The except clause is used to catch and handle specific exceptions that occur within the try
block.
4. You can also use the finally clause to execute cleanup code, regardless of whether an
exception occurred or not..

CODE:

# Aditya Singla - 04514803121


try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
Experiment – 11

AIM: GUI programming: Create a program that uses a graphical user interface (GUI)
to allow the user to perform simple calculations.

THEORY:

GUI programming stands for Graphical User Interface programming. It involves creating
applications that have graphical elements such as windows, buttons, menus, and other visual
components that users can interact with. GUI programming allows developers to build user-
friendly applications with intuitive interfaces, making it easier for users to interact with the
software.

Tkinter is a standard GUI (Graphical User Interface) library for Python. It is included with
most Python installations, so you don't need to install any additional packages to use it.
Tkinter provides a set of tools and widgets to create graphical user interfaces in Python
applications. Here's a brief overview of some key concepts related to Tkinter:

1. Widgets: Widgets are the building blocks of a Tkinter GUI. They are visual elements such
as buttons, labels, entry fields, checkboxes, radio buttons, etc. Tkinter provides a variety of
pre-built widgets that you can use to create your GUI.

2. Main Window: The main window is the primary window of a Tkinter application. It serves
as the container for all other widgets. You create the main window using the Tk() constructor
from the tkinter module.

3. Layout Management: Tkinter provides different layout managers to arrange widgets within
the main window. The most commonly used layout managers are pack(), grid(), and place().
pack() arranges widgets in a block or line, grid() arranges widgets in a table-like structure,
and place() allows you to specify the exact position of a widget.

4. Event-Driven Programming: Tkinter follows an event-driven programming paradigm. It


means that Tkinter applications respond to user actions or events such as button clicks, mouse
movements, etc.
You can bind functions or methods to events using the bind() method or by specifying a
command callback for widgets like buttons.

CODE:

# Aditya Singla - 04514803121


from tkinter import *
expression = ""
def press(num):
global expression
expression = expression + str(num)
equation.set(expression)
# Function to evaluate the final expression
def equalpress():
try: global expression
total = str(eval(expression))
equation.set(total)
expression = ""
except:
equation.set(" error ")
expression = ""
def clear():
global expression
expression = ""
equation.set("")
if __name__ == "__main__":
gui = Tk()
gui.configure(background="light green")
gui.title("Simple Calculator")
gui.geometry("270x150")
equation = StringVar()
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)

button2 = Button(gui, text=' 2 ', fg='black', bg='red',


command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)

button3 = Button(gui, text=' 3 ', fg='black', bg='red',


command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)

button4 = Button(gui, text=' 4 ', fg='black', bg='red',


command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)

button5 = Button(gui, text=' 5 ', fg='black', bg='red',


command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)

button6 = Button(gui, text=' 6 ', fg='black', bg='red',


command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)

button7 = Button(gui, text=' 7 ', fg='black', bg='red',


command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)

button8 = Button(gui, text=' 8 ', fg='black', bg='red',


command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='red',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)

button0 = Button(gui, text=' 0 ', fg='black', bg='red',


command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)

plus = Button(gui, text=' + ', fg='black', bg='red',


command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)

minus = Button(gui, text=' - ', fg='black', bg='red',


command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)

multiply = Button(gui, text=' * ', fg='black', bg='red',


command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)

divide = Button(gui, text=' / ', fg='black', bg='red',


command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)

equal = Button(gui, text=' = ', fg='black', bg='red',


command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)

clear = Button(gui, text='Clear', fg='black', bg='red',


command=clear, height=1, width=7)
clear.grid(row=5, column='1')

Decimal= Button(gui, text='.', fg='black', bg='red',


command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()
Experiment – 12

AIM: Web scraping: Create a program that uses a web scraping library to extract data
from a website and then stores it in a database.

THEORY: Web scraping is the process of extracting data from websites. It involves
retrieving web pages, parsing the HTML or XML content of those pages, and extracting the
desired information. Web scraping can be used to gather a wide range of data, including text,
images, links, and structured data like tables.

1. HTTP Requests: Web scraping begins with sending HTTP requests to a web server to
retrieve web pages. Python provides several libraries for making HTTP requests, such as
requests and urllib.
2. HTML Parsing: Once the web page is retrieved, its HTML content needs to be parsed to
extract the desired data. HTML parsing involves analyzing the structure of the HTML
document and identifying the elements containing the target data.
Python offers libraries like Beautiful Soup and lxml for parsing HTML and XML documents.
3. Data Extraction: After parsing the HTML content, you can use techniques like CSS
selectors or XPath expressions to locate specific elements in the HTML document and extract
data from them. Commonly extracted data include text, links, images, tables, and other
structured information.
4. Database Storage: Once the data is extracted, you may want to store it in a database for
further analysis or retrieval. Databases provide a structured and efficient way to organize and
manage large volumes of data. Python offers various database libraries such as sqlite3,
MySQLdb, psycopg2 (for PostgreSQL), and pymongo (for MongoDB) for interacting with
different types of databases.

CODE:

# Aditya Singla - 04514803121


import requests
from bs4 import BeautifulSoup
import sqlite3
url = "https://www.google.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS data (
id INTEGER PRIMARY KEY,
title TEXT,
content TEXT
)
''')
title = "Sample Title"
content = "Sample Content"
cursor.execute('INSERT INTO data (title, content) VALUES (?, ?)', (title, content))
conn.commit()
Experiment – 13

AIM: Data visualization: Create a program that reads data from a file and then creates
a visualization of that data using a data visualization library.

THEORY:

Data visualization is the graphical representation of data to provide insights and aid in
understanding patterns, trends, and relationships within the data. Python offers several
powerful libraries for data visualization, including Matplotlib, Seaborn, Plotly, and Bokeh.
These libraries allow you to create a wide range of visualizations, including line plots, scatter
plots, bar charts, histograms, and more.

1. Data Reading: Before you can visualize data, you need to read it from a file or another data
source. Python provides various tools and libraries for reading data from different file
formats, such as CSV, Excel, JSON, and databases.
2. Data Structures: Data is typically stored in data structures such as lists, arrays, pandas
DataFrames, or NumPy arrays. These data structures provide a convenient way to organize
and manipulate the data before visualization.
3. Data Visualization Libraries: Python offers several data visualization libraries, each with
its own strengths and capabilities. Some popular libraries include:

Matplotlib: A versatile plotting library that provides a MATLAB-like interface for creating
static, interactive, and animated visualizations.

Seaborn: Built on top of Matplotlib, Seaborn provides a high-level interface for creating
attractive statistical graphics.

CODE:

# Aditya Singla - 04514803121


import matplotlib.pyplot as plt

# initializing the data


x = [10, 20, 30, 40]
y = [20, 25, 35, 55]

# plotting the data


plt.plot(x, y)

plt.show()
Experiment – 14

AIM: Machine learning: Create a program that uses a machine learning library to
classify images based on their content.

THEORY:

Image Classification: Image classification is the task of assigning a label or category to an


input image based on its visual content. It is a fundamental problem in computer vision and
has numerous applications, including object detection, face recognition, medical image
analysis, and more. In image classification, a model learns to recognize patterns and features
in images that distinguish one class from another.

Machine Learning: Machine learning is a subfield of artificial intelligence (AI) that focuses
on developing algorithms and models that enable computers to learn from data and make
predictions or decisions without being explicitly programmed. Supervised learning is a
common approach in machine learning, where the model learns from labeled training data. In
image classification, each image in the training dataset is associated with a label or class.
Deep learning, a subset of machine learning, has revolutionized image classification with the
introduction of deep neural networks, particularly convolutional neural networks (CNNs),
which have shown remarkable performance in various computer vision tasks.

CODE:

# Aditya Singla - 04514803121


import tensorflow as tf
from tensorflow.keras import layers, models
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
predictions = model.predict(test_images)
Experiment – 15

AIM: Networking: Create a program that uses a networking library to communicate


with a server and retrieve data from it.

THEORY:

Networking: Networking involves the exchange of data between multiple devices over a
network, such as the internet. Communication between a client (your program) and a server
typically occurs using a client-server architecture, where the client sends requests to the
server, and the server responds to those requests.

HTTP Requests: HTTP (Hypertext Transfer Protocol) is the protocol used for communication
between web clients (such as browsers or Python programs) and web servers.
HTTP requests are messages sent by a client to request resources or perform actions on a
server. Common types of HTTP requests include GET (retrieve data), POST (submit data),
PUT (update data), and DELETE (remove data).

Networking Libraries: Python provides several libraries for making HTTP requests and
interacting with web servers, including requests, urllib, and http.client. These libraries allow
you to send HTTP requests, handle responses, and perform various networking tasks such as
authentication, cookies, and sessions.

CODE:

# Aditya Singla - 04514803121


import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))

# default port for socket


port = 80
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:

# this means could not resolve the host


print ("there was an error resolving the host")
sys.exit()

# connecting to the server


s.connect((host_ip, port))

print ("the socket has successfully connected to google")


Experiment – 16

AIM: Write a python script to print the current date in the following format “Sun May
2902:26:23 IST 2017”

THEORY:

datetime Module:
The datetime module in Python provides classes for working with dates, times, and their
combinations. The datetime class represents a point in time, and the datetime.now() method
returns the current date and time.

Formatting Dates:
Python provides the strftime() method (string format time) to format dates and times into
human-readable strings. The strftime() method takes a format string as an argument, which
contains format codes representing various components of the date and time, such as year,
month, day, hour, minute, second, etc.

CODE:

# Aditya Singla - 04514803121


import datetime
def get_formatted_date():
now = datetime.datetime.now()
day_name = now.strftime("%a") # Abbreviated weekday (Sun, Mon, ...)
month_name = now.strftime("%b") # Abbreviated month name (Jan, Feb, ...)
day = now.strftime("%d") # Day of the month (01-31)
hour = now.strftime("%H") # Hour in 24-hour format (00-23)
minute = now.strftime("%M") # Minutes (00-59)
second = now.strftime("%S") # Seconds (00-59)
time_zone = now.strftime("%Z") # Time zone name (IST in this case)
year = now.strftime("%Y") # Year with century

# Assemble the formatted date string


formatted_date = f"{day_name} {month_name} {day} {hour}:{minute}:{second}
{time_zone} {year}"
return formatted_date
# Print the formatted date
print(get_formatted_date())
Experiment – 17

AIM: Write a program to create, append, and remove lists in python

THEORY: Lists are one of the built-in data types in Python used to store collections of
items. They are ordered, mutable (modifiable), and can contain elements of different data
types. Lists are defined by enclosing comma-separated elements within square brackets [ ].

1. Creating Lists: You can create an empty list by simply using empty square brackets [].
To create a list with initial elements, enclose the elements within square brackets [ ] and
separate them by commas. Example: my_list = [1, 2, 3, 4, 5].

2. Appending Elements: The append() method is used to add elements to the end of a list.
Syntax: list.append(element) Example: my_list.append(6) adds the element 6 to the end of the
list my_list.

3. Removing Elements by Value:


The remove() method is used to remove the first occurrence of a specified value from the list.
Syntax: list.remove(value) Example: my_list.remove(3) removes the first occurrence of the
value 3 from the list my_list.

CODE:

# Aditya Singla - 04514803121


# Create a list
my_list = ["apple", "banana", "cherry"]
print("Original list:", my_list)

# Append an element to the list


my_list.append("orange")
print("List after appending:", my_list)

# Remove an element by index


del my_list[1] # Remove the element at index 1 (banana)
print("List after removing by index:", my_list)

# Remove an element by value


my_list.remove("cherry") # Remove the first occurrence of "cherry"
print("List after removing by value:", my_list)
Experiment – 18

AIM: Write a program to demonstrate working with tuples in python.

THEORY:

Definition: A tuple is an ordered collection of elements, similar to a list. Tuples are


immutable, meaning their elements cannot be changed after creation. Once a tuple is created,
you cannot modify, add, or remove its elements.

Creation: Tuples are created by enclosing comma-separated elements within parentheses ().
Example: my_tuple = (1, 2, 3, 4, 5).

Accessing Elements: Elements of a tuple can be accessed using indexing and slicing, similar
to lists. Indexing starts from 0, and negative indexing starts from -1.
Example: first_element = my_tuple[0], last_element = my_tuple[-1].

CODE:

# Aditya Singla - 04514803121


# Create a tuple
my_tuple = ("apple", "banana", "cherry")
print("Original tuple:", my_tuple)
# Tuples are immutable, so you cannot directly modify elements
# This will result in a TypeError
# my_tuple[1] = "orange"
# You can create a new tuple with the desired changes
modified_tuple = my_tuple + ("orange",)
print("Modified tuple:", modified_tuple)
# Access elements by index
first_fruit = my_tuple[0]
print("First fruit:", first_fruit)
# Tuples can be used in loops
for fruit in my_tuple:
print(fruit)
# Check if an element exists in the tuple
if "banana" in my_tuple:
print("Banana is in the tuple.")
Experiment – 19

AIM: Write a program to demonstrate working with dictionaries in python.

THEORY:

A dictionary in Python is a collection of key-value pairs. Each key is unique within the
dictionary, and it is used to access its corresponding value. Dictionaries are mutable, meaning
you can modify them after they've been created. They are unordered collections, meaning that
the order in which the key-value pairs are added to the dictionary may not be preserved.

Python dictionaries are very flexible and can store a wide variety of data types as values,
including integers, floats, strings, lists, tuples, other dictionaries, and more.

CODE:

# Aditya Singla - 04514803121


my_dict = {
"fruit": "apple",
"vegetable": "carrot",
"color": "blue"
}
print("Original dictionary:", my_dict)
# Access elements by key
fruit_name = my_dict["fruit"]
print("Fruit:", fruit_name)

# Check if a key exists


if "color" in my_dict:
print("The 'color' key exists in the dictionary.")

# Add a new key-value pair


my_dict["number"] = 42
print("Dictionary after adding a new key:", my_dict)

# Update an existing value


my_dict["fruit"] = "banana"
print("Dictionary after updating a value:", my_dict)

# Remove a key-value pair


del my_dict["vegetable"]
print("Dictionary after removing a key:", my_dict)

# Loop through key-value pairs


for key, value in my_dict.items():
print(f"{key}: {value}")
Experiment – 20

AIM: Write a Python program to convert temperatures to and from Celsius,


Fahrenheit.

THEORY:

Celsius (°C): Named after Swedish astronomer Anders Celsius, this scale sets the freezing
point of water at 0°C and the boiling point at 100°C under standard atmospheric pressure.

Fahrenheit (°F): Named after German physicist Daniel Gabriel Fahrenheit, this scale sets the
freezing point of water at 32°F and the boiling point at 212°F under standard atmospheric
pressure.

Conversion Formulas:

Celsius to Fahrenheit: 𝐹 = 9/5 𝐶 + 32


Fahrenheit to Celsius: 𝐶 = 5/9 ( 𝐹 – 32 )

CODE:

# Aditya Singla - 04514803121


def convert_temp(temperature, unit_in, unit_out):
if unit_in.upper() == "C" and unit_out.upper() == "F":
# Convert from Celsius to Fahrenheit
return (temperature * 9/5) + 32
elif unit_in.upper() == "F" and unit_out.upper() == "C":
# Convert from Fahrenheit to Celsius
return (temperature - 32) * 5/9
else:
print("Invalid input or output unit. Please use 'C' or 'F'.")
return None

# Get user input


while True:
try:
temperature = float(input("Enter temperature value: "))
unit_in = input("Enter input unit (C or F): ").upper()
unit_out = input("Enter output unit (C or F): ").upper()
break
except ValueError:
print("Invalid input. Please enter a numerical temperature value.")

# Convert temperature and print result


converted_temp = convert_temp(temperature, unit_in, unit_out)
if converted_temp is not None:
print(f"{temperature:.2f} {unit_in} is equal to {converted_temp:.2f} {unit_out}.")
Experiment – 21

AIM: Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is a right triangle

THEORY:

According to the Pythagorean theorem, in a right triangle, the square of the length of the
hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths
of the other two sides.

Conditions for a Right Triangle:


To determine if a triangle is a right triangle, we can check whether the given side lengths
satisfy the Pythagorean theorem. If the sum of the squares of the lengths of the two shorter
sides is equal to the square of the length of the longest side, then the triangle is a right
triangle.

CODE:

# Aditya Singla - 04514803121


def is_right_triangle(a, b, c):
# Sort the sides in ascending order
sides = sorted([a, b, c])
# Check if the Pythagorean theorem holds for the largest side
return sides[0]**2 + sides[1]**2 == sides[2]**2
# Get user input
while True:
try:
side_a = float(input("Enter the length of side a: "))
side_b = float(input("Enter the length of side b: "))
side_c = float(input("Enter the length of side c: "))
# Check for non-positive side lengths
if side_a <= 0 or side_b <= 0 or side_c <= 0:
print("Triangle side lengths cannot be non-positive. Please enter valid values.")
continue
break
except ValueError:
print("Invalid input. Please enter numerical values for side lengths.")
# Check if it's a right triangle
if is_right_triangle(side_a, side_b, side_c):
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")
Experiment – 22

AIM: Write a python program to define a module and import a specific function in that
module to another program.

THEORY:

Modules in Python: A module in Python is a file containing Python definitions, statements,


and functions. It serves as a reusable piece of code that can be imported and used in other
Python programs. Modules help in organizing code into logical units, improving code
reusability, and making code maintenance easier.

Defining a Module: To define a module in Python, you simply create a .py file and write
Python code inside it. The filename becomes the module name, and you can access its
contents using the import statement in other Python programs.

Importing Functions from a Module: When importing functions from a module, you can
either import the entire module or import specific functions from the module.
Importing specific functions can make your code more readable and reduce namespace
clutter.

CODE:

# Aditya Singla - 04514803121


def greet(name):
print("Hello, {}!".format(name))
from my_module import greet
def main():
name = input("Enter your name: ")
greet(name)
if __name__ == "__main__":
main()
Experiment – 23

AIM: Write a Python class to convert an integer to a roman numeral.

THEORY: Roman Numerals: Roman numerals are a numeral system originating from
ancient Rome. They are represented by combinations of letters from the Latin alphabet.
The basic Roman numerals and their corresponding decimal values are:
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
Roman numerals follow specific rules for representation, including additive and subtractive
notations.

CODE:

# Aditya Singla - 04514803121


class IntegerToRoman:
def __init__(self):
self.numeral_map = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}
def int_to_roman(self, num):
if num <= 0:
return "Invalid number"
result = ''
for value, numeral in sorted(self.numeral_map.items(), reverse=True):
while num >= value:
result += numeral
num -= value
return result

# Example usage:
converter = IntegerToRoman()
print(converter.int_to_roman(354)) # Output: CCCLIV
Experiment – 24

AIM: Write a Python class to reverse a string word by word.

THEORY:

Reversing a String Word by Word: To reverse a string word by word means to reverse the
order of words while keeping each word unchanged.
For example, if we have the string "Hello World", the reversed string would be "World
Hello".

Approach:
One approach to reverse a string word by word is to split the string into words, reverse the
order of the words, and then join them back together into a single string.
We can achieve this using Python's string manipulation methods such as split() and join().
Another approach is to iterate through the string character by character, building each word,
and then reversing the order of the words.

CODE:

# Aditya Singla - 04514803121


class ReverseWords:
def reverse_words(self, sentence):

# Reverse the entire string


reversed_sentence = sentence[::-1]

# Reverse individual words within the reversed string


words = reversed_sentence.split()
return " ".join(words[::-1])

# Example usage
reverser = ReverseWords()
reversed_string = reverser.reverse_words("Hello world, how are you?")
print(reversed_string)
Experiment – 25

AIM: Write a Python program to implement linear search

THEORY: Linear search, also known as sequential search, is a simple searching algorithm
that searches for a target value in a list or array by sequentially checking each element from
the beginning until the target is found or the end of the list is reached.
Linear search works well for small-sized lists or unsorted arrays where the elements are not
arranged in any particular order.

Algorithm:

1. The linear search algorithm traverses the list or array linearly, comparing each element
with the target value until a match is found or the end of the list is reached.
2. If the target value is found, the algorithm returns the index of the element where the match
occurred.
3. If the target value is not found, the algorithm returns a special value (e.g., -1) to indicate
that the target is not present in the list.

Time Complexity:
In the worst-case scenario, linear search has a time complexity of O(n), where n is the
number of elements in the list or array.
This means that the time taken to search for a target value increases linearly with the size of
the list.

CODE:

# Aditya Singla - 04514803121


def linear_search(data, target):
for i, element in enumerate(data):
if element == target:
return i
return -1

# Example usage
data = [10, 20, 30, 40, 50]
target = 30
index = linear_search(data, target)

if index != -1:
print(f"Target {target} found at index {index}")
else:
print(f"Target {target} not found in the list")
Experiment – 26

AIM: Write a Python program to implement binary search

THEORY: Binary search is an efficient searching algorithm that works on sorted arrays. It
repeatedly divides the search interval in half until the target element is found or the interval is
empty.

Algorithm:
1. Compare the target value with the middle element of the array.
2. If the target value matches the middle element, return its index.
3. If the target value is greater than the middle element, then the target must be in the right
half of the array; repeat the search in the right half.
4. If the target value is smaller than the middle element, then the target must be in the left half
of the array; repeat the search in the left half.
5. Continue this process until the target value is found or the search interval is empty.

Time Complexity:
Binary search has a time complexity of O(log n) in the worst-case scenario, where n is the
number of elements in the array.
This efficiency makes binary search particularly suitable for large datasets

CODE:

# Aditya Singla - 04514803121


def binary_search(data, target, low=0, high=None):
if high is None:
high = len(data) - 1
if low > high:
return -1
mid = (low + high) // 2
if data[mid] == target:
return mid
elif data[mid] < target:
return binary_search(data, target, mid + 1, high)
else:
return binary_search(data, target, low, mid - 1)
data = [10, 20, 30, 40, 50]
target = 30
index = binary_search(data, target)
if index != -1:
print(f"Target {target} found at index {index}")
else:
print(f"Target {target} not found")
Experiment – 27

AIM: Write a Python program to implement insertion sort

THEORY:

Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a
time. It works by iterating through the array, removing one element at a time and inserting it
into its correct position in the sorted part of the array. The key idea is to maintain a sorted
sublist in the lower positions of the array, shifting larger elements up as necessary to make
room for the inserted element.

Algorithm:
1. Start with the second element of the array and assume it is the first element of the sorted
sublist.
2. Compare this element with the elements in the sorted sublist, moving from right to left.
3. Insert the element into its correct position in the sorted sublist by shifting larger elements
to the right.
4. Repeat this process for each element in the array until the entire array is sorted.

Time Complexity:
In the worst-case scenario, insertion sort has a time complexity of O(n^2), where n is the
number of elements in the array.
It performs well for small datasets or nearly sorted arrays but becomes inefficient for large
datasets compared to more advanced sorting algorithms like merge sort or quicksort.

CODE:

# Aditya Singla - 04514803121


def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr

# Example usage:
arr = [12, 11, 13, 5, 6]
print("Original array:", arr)
sorted_arr = insertion_sort(arr)
print("Sorted array:", sorted_arr)
Experiment – 28

AIM: Write a Python program to implement selection sort

THEORY:

Selection sort is a simple sorting algorithm that divides the input list into two parts: the sorted
sublist and the unsorted sublist. It repeatedly finds the minimum element from the unsorted
sublist and swaps it with the first unsorted element. After each iteration, the sorted sublist
grows, and the unsorted sublist shrinks until the entire list is sorted.

Algorithm:
1. Start with the entire list considered as the unsorted sublist.
2. Find the minimum element in the unsorted sublist.
3. Swap the minimum element with the first element of the unsorted sublist.
4. Repeat this process for the remaining unsorted sublist until the entire list is sorted.

Time Complexity:
Selection sort has a time complexity of O(n^2) in all cases, where n is the number of
elements in the list.
It performs the same number of comparisons and swaps regardless of the initial order of the
elements.

CODE:

# Aditya Singla - 04514803121


def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr

# Example usage:
arr = [64, 25, 12, 22, 11]
print("Original array:", arr)
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)
Experiment – 29

AIM: Write a Python program to implement tower of Hanoi.

THEORY:

The Tower of Hanoi is a classic problem in computer science and mathematics. It consists of
three rods and a number of disks of different sizes that can slide onto any rod. The objective
is to move the entire stack of disks from one rod to another, obeying the following rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the top disk from one stack and placing it on top of another
stack.
3. No disk may be placed on top of a smaller disk.

Recursive Approach: The Tower of Hanoi problem can be solved using a recursive approach.
To solve the problem for n disks, we can follow these steps:
1. Move the top n - 1 disks from the source rod to an auxiliary rod, using the destination rod
as a helper.
2. Move the nth disk from the source rod to the destination rod.
3. Move the n - 1 disks from the auxiliary rod to the destination rod, using the source rod as a
helper.
4. This process is repeated recursively until all disks are moved to the destination rod.

Time Complexity:
The time complexity of the Tower of Hanoi problem is O(2^n), where n is the number of
disks. This exponential time complexity arises from the recursive nature of the problem.

CODE:

# Aditya Singla - 04514803121


def tower_of_hanoi(n, source, destination, auxiliary):
if n == 1:
print("Move disk 1 from", source, "to", destination)
return
tower_of_hanoi(n - 1, source, auxiliary, destination)
print("Move disk", n, "from", source, "to", destination)
tower_of_hanoi(n - 1, auxiliary, destination, source)

# Example usage:
n=3
tower_of_hanoi(n, 'A', 'C', 'B')
Experiment – 30

AIM: Write a Python program to implement matrix multiplication.

THEORY:

Algorithm: To perform matrix multiplication of matrices A and 𝐵:


1. Iterate over each row i of matrix A.
2. For each row i of matrix 𝐴, iterate over each column j of matrix B.
3. Calculate the dot product of the ith row of matrix A and the jth column of matrix B to
compute the element cij of matrix C.
4. Store the result in the corresponding position in matrix C.

Time Complexity:
The time complexity of matrix multiplication is O(n^3), where n is the size of the matrices.
This arises from the three nested loops used to iterate over the rows and columns of the
matrices.

CODE:

# Aditya Singla - 04514803121


def matrix_multiply(X, Y):
result = [[0] * len(Y[0]) for _ in range(len(X))]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
return result
# Example usage:
X = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]
Y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]]
result = matrix_multiply(X, Y)
for row in result:
print(row)

You might also like