Python Lab Manual
Python Lab Manual
Semester-II
SUBJECT TEACHER
PROF. NIKITA KHURPADE
Term work:
PYTHON
Experiments List
1. Task List Manager*: Develop a Python program to manage a task list using lists and tuples,
including adding, removing, updating, and sorting tasks.
2. Student Enrollment Manager *: Create a Python code to demonstrate the use of sets and
perform set operations (union, intersection, difference) to manage student enrollments in
multiple courses / appearing for multiple entrance exams like CET, JEE, NEET etc.
3. Student Record Keeper *: Write a Python program to create, update, and manipulate a
dictionary of student records, including their grades and attendance.
2
3 Objective: To enable students to transition their understanding of control statements and
loops from C to Python, emphasizing the adoption of Python syntax while reinforcing logical
structures already learned.
1. Triangle Pattern Generator Using Loops: Write a Python program to print a triangle
pattern (give any), emphasizing the transition from C to Python syntax.
2. Number Type Identifier*: Develop a Python program that takes a numerical input and
identifies whether it is even or odd, utilizing conditional statements and loops.
3. Character Type Identifier: Create a Python program to check whether the given input
is a digit, lowercase character, uppercase character, or a special character using an 'if
else-if' ladder.
4. Multiplication Table Generator: Write a Python program to take a numerical input from
the user and generate its multiplication table using loops.
5. Fibonacci Sequence Generator: Develop a Python program to print the Fibonacci
sequence using a while loop.
6. Factorial Generator*: Design a Python program to compute the factorial of a given
integer N.
7. Prime Number Analyzer*: Using function, write a Python program to analyze the input
number is prime or not.
8. Simple Calculator Using Functions*: Implement a simple Python calculator that takes
user input and performs basic arithmetic operations (addition, subtraction, multiplication,
division) using functions.
9. Interactive Guessing Game: Develop a number guessing game where the program
generates a random number, and the user has to guess it. Implement loops and conditional
statements for user interaction.
Objective: To enable learners to proficiently handle file operations, manage exceptions, and
create Python packages and executable files.
1. Extracting Words from Text File *: Develop a Python program that reads a text file and
prints words of specified lengths (e.g., three, four, five, etc.) found within the file.
2. Finding Closest Points in 3D Coordinates from CSV: Write a python code to take a
csv file as input with coordinates of points in three dimensions. Find out the two closest
points.
3. Sorting City Names from File: Write a python code to take a file which contains city
names on each line. Alphabetically sort the city names and write it in another file.
4. Building an Executable File*: Create a executable file for any program developed in
earlier practical.
4
Objective: To enable learners to proficiently handle errors and exceptions in Python
programs, ensuring robust and fault-tolerant code. Learners will also develop debugging skills
to identify, diagnose, and fix issues efficiently using scientific debugging methods.
1. Basic Exception Handling*: Write a Python program that takes two numbers as input
and performs division. Implement exception handling to manage division by zero and
invalid input errors gracefully.
2. Custom Exceptions: Develop a Python program that simulates a banking system with a
function to withdraw money. Raise custom exceptions for scenarios such as insufficient
funds and invalid account numbers
3. Logging for Debugging: Enhance a Python program by adding logging statements to
record the flow of execution and error messages. Use the logging module to configure
different logging levels (INFO, DEBUG, ERROR).
4. Using a Debugger*: Demonstrate the use of a Python debugger (e.g., pdb or an IDE
with debugging capabilities) on a sample program with intentional errors. Guide students
on setting breakpoints, stepping through code, and examining variable values.
5. Scientific Debugging Techniques: Provide a Python program with multiple logic and
runtime errors. Instruct students to apply scientific debugging techniques, such as binary
search debugging, to identify and resolve the issues methodically
5
6 Objective: To apply object-oriented programming (OOP) principles in Python to model real
world scenarios and systems, fostering the development of modular, reusable, and efficient
solutions. Fostering the ability to design and implement solutions for real-world problems.
Choose any one real world scenario. Ask student to apply OOP principles such as
encapsulation, inheritance, and polymorphism in practical scenarios. The sample real world
scenarios are as follows.
1. Event Management System: Implement an event management system using OOP
concepts to organize and manage various aspects of college festivals or events. Design
classes for events, organizers, participants, and activities. Include methods for event
registration, scheduling, participant management, and activity coordination.
2. Online Shopping System: Develop classes for products, customers, and shopping carts.
Include methods for adding items to the cart, calculating total costs, processing orders,
and managing inventory.
3. Vehicle Rental System: Design a system using classes for vehicles, rental agencies, and
rental transactions. Implement methods to handle vehicle availability, rental periods,
pricing, and customer bookings.
Objective: To provide learners with the knowledge and skills necessary to effectively use the
Pandas library for data manipulation and the Matplotlib library for data visualization. Learners
will engage in tasks that involve analyzing real-world datasets, creating meaningful
visualizations, and drawing insights from data.
Task1- Loading and Inspecting Data: Load a CSV file containing information on global
COVID-19 cases into a DataFrame. Display the first few rows, check the data types, and
summarize basic statistics.
Task 2- Data Cleaning: Identify and handle missing values in the dataset. Remove any
duplicate rows and ensure data consistency.
Task 3-Data Aggregation: Perform aggregation operations to summarize data.
Task 4- Plotting graphs: Generate a line plot showing the trend / bar plot to compare data/
histogram to show distribution/ scatter plot to examine relationships between variables.
Instructors can choose other datasets relevant to the course objectives. Sample datasets and
task list are as follows.
1. Using the Iris Data (https://www.kaggle.com/datasets/saurabh00007/iriscsv), perform
the following tasks:
i.Read the first 8 rows of the dataset.
ii.Display the column names of the Iris dataset.
iii.Fill any missing data with the mean value of the respective column.
iv.Remove rows that contain any missing values.
v.Group the data by the species of the flower.
vi.Calculate and display the mean, minimum, and maximum values of the Sepal length column.
2.Using the Cars Data (https://www.kaggle.com/datasets/nameeerafatima/toyotacsv)
perform the following tasks:
i.Create a scatter plot between the Age and Price of the cars to illustrate how the price
decreases as the age of the car increases.
ii.Generate a histogram to show the frequency distribution of kilometers driven by the
cars.
iii.Produce a bar plot to display the distribution of cars by fuel type.
iv.Create a pie chart to represent the percentage distribution of cars based on fuel types.
v.Draw a box plot to visualize the distribution of car prices across different fuel types.
10
EXPERIMENT NO: 1
To write a Python program that generates a personalized greeting based on the user's input.
Theory:
A personalized greeting generator is a simple Python program designed to take user input, such as a name
or a specific message, and generate a customized greeting. This program is beneficial for applications like
chatbots, user interfaces, or any interactive system that requires personalized messages.
In Python, we use the input() function to take user input from the console. By using formatted strings
(f-strings) or concatenation, we can combine the static greeting text with the user's input to display a
personalized message.
Key Concepts:
Algorithm:
Code –
-----------------------
2. Calculating Areas of Geometric Figures
if shape == "circle":
else:
print("Invalid shape!")
---------------
3. Developing Conversion Utilities
if conversion_type == "rupees_to_dollars":
dollars = rupees / 75
feet = inches / 12
else:
----------------------------------
ta = 0.30 * basic_salary
----------------------------
--------------------------
Conclusion:
The experiment successfully demonstrated how to create a personalized greeting using Python. The
program effectively takes user input and displays a customized message, enhancing the user experience
through simple interaction.
EXPERIMENT NO: 2
Aim:
To develop a Python program that calculates the areas of different geometric figures, such as circles,
rectangles, and triangles.
Theory:
Geometric area calculation involves using mathematical formulas to compute the space occupied by a
two-dimensional shape. Different shapes have different formulas to calculate the area:
1. Circle:
oFormula: Area=π×radius2Area = \pi \times radius^2Area=π×radius2
oThe area of a circle is calculated using the value of π (Pi ≈ 3.14159) multiplied by the
square of the radius.
2. Rectangle:
o Formula: Area=length×widthArea = length \times widthArea=length×width
o The area of a rectangle is the product of its length and width.
3. Triangle:
o Formula: Area=12×base×heightArea = \frac{1}{2} \times base \times heightArea=21
×base×height
o The area of a triangle is half the product of its base and height.
Implementation Details:
The program uses the Tkinter library for a graphical user interface (GUI).
The user selects the shape from a dropdown menu.
Input fields are provided for entering dimensions.
A button triggers the calculation, and the result is displayed on the screen.
Algorithm:
Code-
1. Task List Manager*: Develop a Python program to manage a task list using lists and tuples,
2. Student Enrollment Manager *: Create a Python code to demonstrate the use of sets and
perform set operations (union, intersection, difference) to manage student enrollments in
multiple courses / appearing for multiple entrance exams like CET, JEE, NEET etc.
3. Student Record Keeper *: Write a Python program to create, update, and manipulate a
-----------------------------------------
class TaskManager:
def __init__(self):
self.tasks = []
self.tasks.append(task)
if task in self.tasks:
self.tasks.remove(task)
else:
if old_task in self.tasks:
index = self.tasks.index(old_task)
self.tasks[index] = new_task
else:
def show_tasks(self):
if self.tasks:
print("Task List:")
print(f"{i}. {task}")
else:
# Example usage
manager = TaskManager()
manager.show_tasks()
------------------------------------
class StudentEnrollment:
def __init__(self):
self.courses = {
"CET": set(),
"JEE": set(),
"NEET": set()
if exam in self.courses:
self.courses[exam].add(name)
else:
if exam in self.courses:
else:
common = self.courses[exam1].intersection(self.courses[exam2])
else:
def show_all_students(self):
# Example usage
manager = StudentEnrollment()
manager.enroll_student("Alice", "CET")
manager.enroll_student("Bob", "JEE")
manager.enroll_student("Charlie", "CET")
manager.enroll_student("Alice", "JEE")
manager.show_students("CET")
manager.show_common_students("CET", "JEE")
manager.show_all_students()
------------------------------------
class StudentRecord:
def __init__(self):
self.records = {}
if name in self.records:
self.records[name]["Grades"] = new_grades
else:
if name in self.records:
self.records[name]["Attendance"] = new_attendance
print(f"Updated attendance for {name}.")
else:
if name in self.records:
else:
def show_all_students(self):
if self.records:
else:
# Example usage
record = StudentRecord()
record.show_all_students()
record.update_attendance("Bob", 92)
record.show_student("Alice")
Conclusion:
The experiment successfully demonstrated how to calculate the areas of different geometric shapes using
Python and a graphical user interface. The program accurately computes areas based on user input,
enhancing usability and interaction.
.
EXPERIMENT NO: 3
Experiment 3: Developing Conversion Utilities
Aim:
To develop a Python program that performs unit conversions, such as converting Rupees to
Dollars, temperature from Celsius to Fahrenheit, or length from inches to feet.
Theory:
Conversion utilities are essential in various applications, ranging from financial software to
scientific calculators. These utilities automate the process of converting one unit of measurement
to another, ensuring accuracy and efficiency.
Key Concepts:
Feet=Inches12\text{Feet} = \frac{\text{Inches}}{12}
Algorithm:
Code –
```python
print("*" * i)
```
---
```python
if num % 2 == 0:
print("Even")
else:
print("Odd")
```
---
```python
if char.isdigit():
print("Digit")
elif char.islower():
print("Lowercase letter")
elif char.isupper():
print("Uppercase letter")
else:
print("Special character")
```
---
### 4. Multiplication Table Generator
```python
```
---
```python
a, b = 0, 1
count = 0
a, b = b, a + b
count += 1
```
---
```python
factorial = 1
factorial *= i
```
---
```python
def is_prime(n):
if n < 2:
return False
if n % i == 0:
return False
return True
if is_prime(num):
print("Prime Number")
else:
```
---
```python
return x + y
def subtract(x, y):
return x - y
return x * y
if operation == '+':
else:
print("Invalid operation")
```
---
```python
import random
attempts = 0
while True:
attempts += 1
else:
break
```
Conclusion:
The experiment successfully demonstrated how to develop a Python program for various unit
conversions. The program takes user input, performs the required calculations, and presents the
result. This utility is practical for real-world applications requiring quick and accurate
conversions.
EXPERIMENT NO: 4
To write a Python program to calculate the gross salary of an employee based on the basic salary
(BS), dearness allowance (DA), travel allowance (TA), and house rent allowance (HRA).
Theory:
The gross salary of an employee is the total earnings before deductions. It includes the basic
salary along with various allowances such as DA, TA, and HRA.
Allowance Calculations:
Steps Involved:
Code-
import re
if __name__ == "__main__":
file_name = 'input.txt'
desired_lengths = [3, 4, 5]
extract_words_by_length(file_name, desired_lengths)
1. The output should display words of the specified lengths (3, 4, or 5 letters).
This program reads a CSV file containing 3D coordinates and finds the two closest points.
import csv
import math
def read_points_from_csv(filename):
points = []
try:
with open(filename, newline='') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
try:
point = tuple(float(coord) for coord in row)
if len(point) != 3:
print(f"Skipping row: {row}")
continue
points.append(point)
except ValueError:
print(f"Skipping invalid row: {row}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return points
def find_closest_points(points):
min_distance = float('inf')
closest_pair = (None, None)
for i in range(len(points)):
for j in range(i + 1, len(points)):
p1, p2 = points[i], points[j]
distance = math.sqrt(sum((a - b) ** 2 for a, b in zip(p1,
p2)))
if distance < min_distance:
min_distance = distance
closest_pair = (p1, p2)
return closest_pair, min_distance
if __name__ == "__main__":
filename = 'points.csv'
points = read_points_from_csv(filename)
if len(points) < 2:
print("Not enough points to find a closest pair.")
else:
(p1, p2), distance = find_closest_points(points)
print(f"The closest points are {p1} and {p2} with a distance
of {distance:.4f}.")
The output should display the two closest points and their distance.
This script sorts city names alphabetically and writes them to a new file.
Create sort_cities.py:
try:
with open(output_file, 'w') as file:
for city in cities:
file.write(city + '\n')
except Exception as e:
print(f"Error writing to file '{output_file}': {e}")
return
if __name__ == "__main__":
input_filename = 'cities.txt'
output_filename = 'sorted_cities.txt'
sort_cities(input_filename, output_filename)
Once you have created any of the Python programs above, you can turn them into an executable file
(.exe) using PyInstaller.
On Windows:
Double-click extract_words.exe or run in the command prompt:
dist\extract_words.exe
On Linux/Mac:
./dist/extract_words
Summary of Steps
Task Steps
Extracting Words 1. Create input.txt2. Write Python script (extract_words.py)3. Run script
Finding Closest
1. Create points.csv2. Write script (closest_points.py)3. Run script
Points
Sorting City
1. Create cities.txt2. Write script (sort_cities.py)3. Run script
Names
Creating 1. Install PyInstaller2. Convert script using pyinstaller --onefile
Task Steps
Executable script.py3. Run the .exe file
Conclusion:
The experiment demonstrated the calculation of the gross salary of an employee using Python.
The program accurately computed allowances (DA, TA, HRA) and the gross salary based on the
user's input. This type of calculation is useful in payroll management systems and salary
calculators.
EXPERIMENT NO: 5
Experiment 5: Calculating Simple Interest
Aim:
To write a Python program that calculates the simple interest based on user input, including the
principal amount, rate of interest, and time period.
Theory:
Simple interest is a quick and easy way to calculate the interest charged on a loan or earned on
an investment. The formula to calculate simple interest is:
Where:
Concepts Involved:
1. User Input: Capturing numerical data (principal, rate, and time) from the user.
2. Mathematical Operations: Performing basic arithmetic operations to calculate the
interest.
3. Formatted Output: Displaying the result in a clear and user-friendly way.
Algorithm:
Code –
import logging
# 1. Basic Exception Handling
def divide_numbers():
try:
print(f"Result: {result}")
except ZeroDivisionError:
except ValueError:
divide_numbers()
# 2. Custom Exceptions
class InsufficientFundsError(Exception):
pass
class InvalidAccountError(Exception):
pass
else:
account_balance -= amount
return account_balance
try:
except InsufficientFundsError as e:
print(e)
except InvalidAccountError as e:
print(e)
def perform_operations():
logging.info("Starting operation...")
try:
x = int(input("Enter a number: "))
result = x / y
logging.info(f"Result: {result}")
except ZeroDivisionError:
except ValueError:
logging.info("Operation completed.")
perform_operations()
# 4. Using a Debugger
def buggy_function():
x = 10
print(z)
# Uncomment the next line and run with a debugger to analyze
# buggy_function()
def find_bug():
numbers = [1, 2, 3, 4, 5]
total = 0
total += numbers[i]
# find_bug()
Conclusion:
The experiment demonstrated the calculation of simple interest using a Python program. By
accepting user inputs for the principal, rate, and time, the program accurately computes the
simple interest and displays the result. This experiment highlights the practical use of arithmetic
operations in financial applications.
EXPERIMENT NO: 6
Experiment 6: Exploring Basic Arithmetic Operations in Python
Aim:
To write a Python program that performs basic arithmetic operations (addition, subtraction,
multiplication, division, and modulus) on two numbers provided by the user.
Theory:
Arithmetic operations are fundamental mathematical computations that can be performed using
Python. The basic arithmetic operators in Python include:
Input Handling:
Displaying Results:
The print() function is used to display the results of the arithmetic operations.
Algorithm:
# Encapsulation: Defining Event class with private attributes and getter methods
class Event:
self.__name = name
self.__location = location
self.__participants = []
self.__participants.append(participant)
def get_details(self):
class Organizer:
self.name = name
self.contact = contact
class Person:
self._name = name
self._email = email
def get_name(self):
return self._name
class Participant(Person):
super().__init__(name, email)
def get_info(self):
self.topic = topic
def get_details(self):
class Concert(Event):
self.artist = artist
def get_details(self):
if __name__ == "__main__":
event1.register_participant(participant1)
event1.register_participant(participant2)
event2.register_participant(participant1)
organizer.organize_event(event1)
organizer.organize_event(event2)
print(event1.get_details())
print(event2.get_details())
Conclusion:
The experiment successfully demonstrated the use of basic arithmetic operators in Python. The
program was able to take two numbers as input, perform addition, subtraction, multiplication,
division, and modulus, and display the results effectively. This experiment helps build a
foundation for more complex mathematical computations in Python.
EXPERIMENT NO: 7
Experiment 7: GUI for Developing Conversion Utilities
Aim:
To develop a Python GUI application that performs various unit conversions, such as:
Theory:
A graphical user interface (GUI) application provides an interactive way for users to perform
conversions. Python's Tkinter library is commonly used for creating GUI applications due to its
simplicity and versatility.
Key Concepts:
1. GUI Development:
o Tkinter provides a framework for creating windows, buttons, labels, text fields,
and other interactive components.
2. Event Handling:
o GUI applications respond to user actions like button clicks to trigger functions.
3. Conversion Logic:
o Formulas for different unit conversions:
Currency: USD=INR×Conversion Rate\text{USD} = \text{INR} \times \
text{Conversion Rate}
Temperature: F=C×95+32F = C \times \frac{9}{5} + 32
Length: Feet=Inches12\text{Feet} = \frac{\text{Inches}}{12}
Steps:
Code-
1. GUI for Developing Conversion Utilities: Develop a Python GUI application that
(Celsius to Fahrenheit), and length (Inches to Feet). The application should include input
fields for the values, dropdown menus or buttons to select the type of conversion, and
import tkinter as tk
def convert():
value = float(entry.get())
conversion_type = conversion_var.get()
result = ''
result_label.config(text=f'Result: {result}')
root = tk.Tk()
root.geometry('400x200')
entry = tk.Entry(root)
entry.pack()
conversion_dropdown.pack()
# Convert Button
convert_button.pack()
# Result Label
result_label.pack()
root.mainloop()
-------------------------------------------------------------------------
2. GUI for Calculating Areas of Geometric Figures: Develop a Python GUI application
that calculates the areas of different geometric figures such as circles, rectangles, and
triangles. Allows users to input the necessary dimensions for various geometric figures
and calculate their respective areas. The application should include input fields for the
dimensions, buttons to perform the calculations, and labels to display the results.
import tkinter as tk
import math
def calculate_area():
shape = shape_var.get()
try:
if shape == 'Circle':
radius = float(entry1.get())
length = float(entry1.get())
width = float(entry2.get())
base = float(entry1.get())
height = float(entry2.get())
result_label.config(text=result)
except ValueError:
root = tk.Tk()
root.geometry('400x300')
# Shape selection
shape_var = tk.StringVar(value='Circle')
shape_dropdown.pack()
# Dimension inputs
entry1 = tk.Entry(root)
entry1.pack()
entry2 = tk.Entry(root)
entry2.pack()
# Calculate button
calculate_button.pack()
# Result label
result_label.pack()
root.mainloop()
-----------------------------------------------------------------------------
3. College Admission Registration Form: The college admission registration form collects
students. Create a GUI as shown in Figure-1 that allows the user to input his/her
favorite game. When the user clicks the Submit button, it should display the output as
illustrated.
import tkinter as tk
def submit_details():
name = name_entry.get()
branch = branch_var.get()
games = []
if cricket_var.get():
games.append('Cricket')
if football_var.get():
games.append('Football')
if badminton_var.get():
games.append('Badminton')
game_text = ' and enjoy playing ' + ', '.join(games) if games else ''
messagebox.showinfo('Output', output)
root = tk.Tk()
root.title('College Admission Registration Form')
root.geometry('400x300')
# Student Name
name_entry = tk.Entry(root)
name_entry.pack()
# Branch Selection
# Favorite Games
cricket_var = tk.BooleanVar()
football_var = tk.BooleanVar()
badminton_var = tk.BooleanVar()
submit_button.pack()
root.mainloop()
Conclusion:
EXPERIMENT NO: 8
Experiment 8: Script to Validate Phone Number and Email ID Using Regular
Expressions
Aim:
To write a Python script that validates phone numbers and email IDs using regular expressions to
ensure they meet standard formatting requirements.
Theory:
Regular expressions (regex) are powerful tools used to match patterns within strings. They are
widely used for validating inputs such as phone numbers, email addresses, URLs, and more. In
Python, the re module provides functions to work with regular expressions.
Algorithm:
Code-
import re
def validate_phone_email():
email_pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
if phone_pattern.match(phone):
else:
if email_pattern.match(email):
else:
def check_password_strength():
password_pattern = re.compile(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\
d@$!%*?&]{8,}$")
if password_pattern.match(password):
print("Strong password.")
else:
print("Weak password. Ensure it's 8+ chars, contains uppercase, lowercase, digit, and
special char.")
# 3. URL Validator
def validate_url():
url_pattern = re.compile(r"^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/\S*)?$")
if url_pattern.match(url):
print("Valid URL.")
else:
print("Invalid URL.")
def extract_data_from_file(file_path):
content = file.read()
emails = re.findall(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", content)
if __name__ == "__main__":
validate_phone_email()
check_password_strength()
validate_url()
# extract_data_from_file("data.txt")
Conclusion:
The experiment successfully demonstrated how to validate phone numbers and email IDs using
regular expressions in Python. The program efficiently detected whether the inputs followed the
correct format, showcasing the power of regex for input validation in real-world applications.
EXPERIMENT NO: 9
Theory:
NumPy (Numerical Python) is a powerful library in Python used for numerical computations and
data manipulation. It provides support for multi-dimensional arrays and a wide range of
mathematical operations.
Key Concepts:
1. NumPy Arrays:
o A NumPy array is a grid of values, all of the same type, indexed by a tuple of
non-negative integers.
o The number of dimensions is called the rank, and the shape of the array is a tuple
of integers giving the size of the array along each dimension.
2. Creating Arrays:
o 1D Array: A simple list converted into an array using np.array().
o 2D Array: An array of arrays (matrix).
o 3D Array: An array of matrices.
3. Basic Operations:
o Reshaping: Changing the dimensions of an array.
o Slicing: Extracting a portion of the array.
o Indexing: Accessing specific elements.
o Mathematical Operations: Addition, subtraction, multiplication, and division.
Example Operations:
Algorithm:
Code-
import numpy as np
def create_arrays():
# 1D Array
# 2D Array
# 3D Array
# Reshaping
# 2. Array Mathematics
def array_math():
# Dot Product
# Cross Product
def statistical_operations():
print("Mean:", np.mean(data))
print("Median:", np.median(data))
print("Variance:", np.var(data))
# Correlation Coefficients
if __name__ == "__main__":
create_arrays()
array_math()
statistical_operations()
Conclusion:
The experiment successfully demonstrated how to create and manipulate arrays using the NumPy
library. The program performed various operations such as creating arrays of different
dimensions, reshaping, slicing, and performing arithmetic operations. These concepts are
fundamental in data analysis and scientific computing, making NumPy an essential tool for
efficient numerical computations.
EXPERIMENT NO: 10
Experiment 10: Data Manipulation and Visualization using Pandas and
Matplotlib
Aim:
To analyze real-world datasets using the Pandas library for data manipulation and the Matplotlib
library for data visualization, and to draw meaningful insights from the data.
Theory:
Data manipulation and visualization are essential components of data science and analysis.
Python's Pandas library provides powerful data structures (like DataFrames) for efficient data
manipulation, while Matplotlib offers versatile plotting tools for visual representation.
Key Concepts:
Steps Involved:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
if __name__ == "__main__":
file_path = "your_dataset.csv" # Replace with actual dataset
df = load_and_inspect(file_path)
df = clean_data(df)
aggregate_data(df)
plot_graphs(df)
Conclusion:
The experiment successfully demonstrated how to use Pandas for data manipulation and
Matplotlib for data visualization. The program effectively handled data loading, cleaning,
aggregation, and visual representation. This approach enhances data analysis by providing clear
and insightful graphical interpretations of complex datasets.