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

Python Lab Manual

The document outlines the Python Lab course (VSEC202) for Semester-II at B. R. Harne College of Engineering and Technology, detailing the lab outcomes and term work assessment. It includes a comprehensive list of experiments and objectives aimed at enhancing students' proficiency in Python programming, data structures, control flow, file operations, object-oriented programming, GUI applications, regular expressions, and data handling using libraries like NumPy and Pandas. The course is designed to equip students with practical skills through hands-on programming tasks and real-world applications.

Uploaded by

rohancoder7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Lab Manual

The document outlines the Python Lab course (VSEC202) for Semester-II at B. R. Harne College of Engineering and Technology, detailing the lab outcomes and term work assessment. It includes a comprehensive list of experiments and objectives aimed at enhancing students' proficiency in Python programming, data structures, control flow, file operations, object-oriented programming, GUI applications, regular expressions, and data handling using libraries like NumPy and Pandas. The course is designed to equip students with practical skills through hands-on programming tasks and real-world applications.

Uploaded by

rohancoder7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

B. R.

Harne College of Engineering and Technology,


Vangani

COURSE: PYTHON LAB


COURSE CODE: VSEC202

Semester-II

SUBJECT TEACHER
PROF. NIKITA KHURPADE

Academic Year : 2024-25


Lab Outcome:

After successful completion of the course students will be able to


1. Demonstrate the proficiency in basic python programming or Create and perform various operations on data
structures like list, tuple dictionaries and strings.
2. Apply Control Flow and Functions for efficient coding to solve problems.
3. Demonstrate proficiency in handling file operations, managing exceptions, and developing Python packages and
executable files for modular programming.
4. Illustrate the concept of Object-Oriented Programming used in python.
5. Design Graphical User Interface (GUI) applications, utilizing appropriate Python libraries to create user-friendly
interfaces.
6. Investigate and apply popular python libraries to conduct efficient data handling tasks.

Term work:

25 Marks (Total marks) = 10 Marks (Experiment) + 10 Marks (Internal


Practical Exam) + 5 Marks (Attendance)
LAB MANUAL

PYTHON
Experiments List

1. Personalized Greeting Generator* - Write a python code to generate Personalized


Greeting.
2. Calculating Areas of Geometric Figures* - Write a python program to calculate areas
of any geometric figures like circle, rectangle and triangle.
3. Developing Conversion Utilities: Develop any converter such as Rupees to dollar,
temperature convertor, inch to feet etc.
4. Calculating Gross Salary of an Employee*: Write a Python program to calculate the
gross salary of an employee. The program should prompt the user for the basic salary
(BS) and then compute the dearness allowance (DA) as 70% of BS, the travel allowance
(TA) as 30% of BS, and the house rent allowance (HRA) as 10% of BS. Finally, it should
calculate the gross salary as the sum of BS, DA, TA, and HRA and display the result.
5. Calculating Simple Interest: Write a Python program to calculate the simple interest
based on user input. The program should prompt the user to enter the principal amount,
the rate of interest, and the time period in years. It should then compute the simple interest
using the formula Simple Interest=(Principal×Rate×Time) /100 and display the result
6. Exploring Basic Arithmetic Operations in Python*: Write a Python program to
explore basic arithmetic operations. The program should prompt the user to enter two
numbers and then perform addition, subtraction, multiplication, division, and modulus
operations on those numbers. The results of each operation should be displayed to the
user.
1
Objective: Mastering Python New Data Structures for Practical Applications

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.

Choose any use case from below.


1. GUI for Developing Conversion Utilities: Develop a Python GUI application that
performs various unit conversions such as currency (Rupees to Dollars), temperature
(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
labels to display the results.
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.
3. College Admission Registration Form: The college admission registration form collects
essential personal, educational, and contact information from prospective
students. Create a GUI as shown in Figure-1 that allows the user to input his/her
name, branch and
favorite game. When the user clicks the Submit button, it should display the output as
illustrated.
7
Objective: To enable learners to effectively utilize regular expressions in Python for pattern
matching, validation, and data extraction tasks, enhancing their ability to process textual data
efficiently and accurately.
1. Script to Validate Phone Number and Email ID *: Write a Python script that prompts
the user to enter their phone number and email ID. It then employs Regular Expressions
to verify if these inputs adhere to standard phone number and email address formats
2. Password Strength Checker: Write a Python script that prompts the user to enter a
password. Use regular expressions to validate the password based on these criteria: At
least 8 characters long, Contains at least one uppercase letter, one lowercase letter, one
digit, and one special character.
3. URL Validator: Develop a script that verifies if a given string is a valid URL. Use regular
expressions to check for standard URL formats, including protocols (http, https), domain
names, and optional path segments. Test with various URLs and ensure the validation
covers common cases.
4. Extracting Data from Text *: Create a program that reads a text file containing various
data (e.g., names, emails, phone numbers). Use regular expressions to extract specific
types of data, such as email addresses, phone numbers, dates (e.g., MM/DD/YYYY
format).
8
9 Objective: To equip learners with the skills to utilize the NumPy libraries for efficient
numerical computing.
1. Creating and Manipulating Arrays*: Write a Python program to create a 1D, 2D,
and 3D NumPy array. Perform basic operations like reshaping, slicing, and indexing.
2. Array Mathematics*: Develop a Python script to create two arrays of the same shape
and perform element-wise addition, subtraction, multiplication, and division.
Calculate the dot product and cross product of two vectors.
3. Statistical Operations*: Write a Python program to calculate mean, median,
standard deviation, variance, and correlation coefficients of a given array.

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.

Following task should be performing on a real-world dataset:

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

Experiment 1: Personalized Greeting Generator


Aim:

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:

1. Input Handling: Capturing data from the user.


2. String Formatting: Using f-strings to embed variables within a string.
3. Displaying Output: Using the print() function to show the personalized greeting.

Algorithm:

1. Start the program.


2. Prompt the user to enter their name.
3. Store the user's input in a variable.
4. Use an f-string or concatenation to create a personalized greeting.
5. Display the greeting.
6. End the program.

Code –

1. Personalized Greeting Generator

name = input("Enter your name: ")

print(f"Hello, {name}! Welcome!")

-----------------------
2. Calculating Areas of Geometric Figures

shape = input("Enter the shape (circle, rectangle, triangle): ").lower()

if shape == "circle":

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

area = 3.14 * radius ** 2

print(f"Area of the circle: {area}")

elif shape == "rectangle":

length = float(input("Enter the length: "))

width = float(input("Enter the width: "))

area = length * width

print(f"Area of the rectangle: {area}")

elif shape == "triangle":

base = float(input("Enter the base: "))

height = float(input("Enter the height: "))

area = 0.5 * base * height

print(f"Area of the triangle: {area}")

else:

print("Invalid shape!")

---------------
3. Developing Conversion Utilities

conversion_type = input("Enter conversion type (rupees_to_dollars, celsius_to_fahrenheit,


inches_to_feet): ").lower()

if conversion_type == "rupees_to_dollars":

rupees = float(input("Enter amount in Rupees: "))

dollars = rupees / 75

print(f"{rupees} Rupees is {dollars} Dollars.")

elif conversion_type == "celsius_to_fahrenheit":

celsius = float(input("Enter temperature in Celsius: "))

fahrenheit = (celsius * 9/5) + 32

print(f"{celsius} Celsius is {fahrenheit} Fahrenheit.")

elif conversion_type == "inches_to_feet":

inches = float(input("Enter length in inches: "))

feet = inches / 12

print(f"{inches} inches is {feet} feet.")

else:

print("Invalid conversion type!")

----------------------------------

4. Calculating Gross Salary of an Employee

basic_salary = float(input("Enter the basic salary: "))


da = 0.70 * basic_salary

ta = 0.30 * basic_salary

hra = 0.10 * basic_salary

gross_salary = basic_salary + da + ta + hra

print(f"The gross salary is: {gross_salary}")

----------------------------

5. Calculating Simple Interest

principal = float(input("Enter the principal amount: "))

rate = float(input("Enter the rate of interest: "))

time = float(input("Enter the time period in years: "))

simple_interest = (principal * rate * time) / 100

print(f"The simple interest is: {simple_interest}")

--------------------------

6. Exploring Basic Arithmetic Operations in Python

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

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


print(f"Addition: {num1 + num2}")

print(f"Subtraction: {num1 - num2}")

print(f"Multiplication: {num1 * num2}")

print(f"Division: {num1 / num2 if num2 != 0 else 'undefined'}")

print(f"Modulus: {num1 % num2 if num2 != 0 else 'undefined'}")

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:

1. Start the program.


2. Prompt the user to select a shape (circle, rectangle, triangle).
3. Accept the required dimensions based on the selected shape.
4. Use the respective formula to calculate the area.
5. Display the calculated area.
6. End the program.

Code-

Objective: Mastering Python New Data Structures for Practical Applications

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.

-----------------------------------------

1. Task List Manager (Using Lists and Tuples)

class TaskManager:

def __init__(self):

self.tasks = []

def add_task(self, task):

self.tasks.append(task)

print(f"Task '{task}' added successfully.")

def remove_task(self, task):

if task in self.tasks:

self.tasks.remove(task)

print(f"Task '{task}' removed successfully.")

else:

print("Task not found!")


def update_task(self, old_task, new_task):

if old_task in self.tasks:

index = self.tasks.index(old_task)

self.tasks[index] = new_task

print(f"Task '{old_task}' updated to '{new_task}'.")

else:

print("Task not found!")

def show_tasks(self):

if self.tasks:

print("Task List:")

for i, task in enumerate(sorted(self.tasks), 1):

print(f"{i}. {task}")

else:

print("No tasks available.")

# Example usage

manager = TaskManager()

manager.add_task("Complete Python assignment")

manager.add_task("Read a cryptography book")

manager.show_tasks()

manager.update_task("Read a cryptography book", "Read a machine learning book")

manager.remove_task("Complete Python assignment")


manager.show_tasks()

------------------------------------

2. Student Enrollment Manager (Using Sets and Set Operations)

class StudentEnrollment:

def __init__(self):

self.courses = {

"CET": set(),

"JEE": set(),

"NEET": set()

def enroll_student(self, name, exam):

if exam in self.courses:

self.courses[exam].add(name)

print(f"{name} enrolled in {exam} successfully.")

else:

print("Invalid exam name!")


def show_students(self, exam):

if exam in self.courses:

print(f"Students enrolled in {exam}: {self.courses[exam]}")

else:

print("Invalid exam name!")

def show_common_students(self, exam1, exam2):

if exam1 in self.courses and exam2 in self.courses:

common = self.courses[exam1].intersection(self.courses[exam2])

print(f"Students appearing for both {exam1} and {exam2}: {common}")

else:

print("Invalid exam names!")

def show_all_students(self):

all_students = self.courses["CET"].union(self.courses["JEE"], self.courses["NEET"])

print(f"All enrolled students: {all_students}")

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

------------------------------------

3. Student Record Keeper (Using Dictionaries)

class StudentRecord:

def __init__(self):

self.records = {}

def add_student(self, name, grades, attendance):

self.records[name] = {"Grades": grades, "Attendance": attendance}

print(f"Student {name} added successfully.")

def update_grades(self, name, new_grades):

if name in self.records:

self.records[name]["Grades"] = new_grades

print(f"Updated grades for {name}.")

else:

print("Student not found!")

def update_attendance(self, name, new_attendance):

if name in self.records:

self.records[name]["Attendance"] = new_attendance
print(f"Updated attendance for {name}.")

else:

print("Student not found!")

def show_student(self, name):

if name in self.records:

print(f"Record for {name}: {self.records[name]}")

else:

print("Student not found!")

def show_all_students(self):

if self.records:

for name, data in self.records.items():

print(f"{name}: Grades: {data['Grades']}, Attendance: {data['Attendance']}%")

else:

print("No student records available.")

# Example usage

record = StudentRecord()

record.add_student("Alice", [85, 90, 88], 95)

record.add_student("Bob", [78, 82, 80], 88)

record.show_all_students()

record.update_grades("Alice", [90, 92, 89])

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:

1. Input Handling: Capturing the value to be converted.


2. Mathematical Operations: Applying the appropriate conversion formula.
3. Formatted Output: Displaying the result in a user-friendly format.

Common Conversion Formulas:

1. Currency Conversion (INR to USD):

USD=INR×conversion rate\text{USD} = \text{INR} \times \text{conversion rate}

Example rate: 1 INR = 0.012 USD (rate may vary)

2. Temperature Conversion (Celsius to Fahrenheit):

F=(C×95)+32F = (C \times \frac{9}{5}) + 32

3. Length Conversion (Inches to Feet):

Feet=Inches12\text{Feet} = \frac{\text{Inches}}{12}

Algorithm:

1. Start the program.


2. Display a menu with conversion options:
o Rupees to Dollars
o Celsius to Fahrenheit
o Inches to Feet
3. Prompt the user to select a conversion type.
4. Take the input value from the user.
5. Apply the appropriate conversion formula.
6. Display the converted result.
7. End the program.

Code –

### 1. Triangle Pattern Generator

This prints a right-angled triangle pattern using loops.

```python

rows = int(input("Enter the number of rows: "))

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

print("*" * i)

```

---

### 2. Number Type Identifier (Even or Odd)

This program checks whether a number is even or odd.

```python

num = int(input("Enter a number: "))

if num % 2 == 0:
print("Even")

else:

print("Odd")

```

---

### 3. Character Type Identifier

This determines if the input is a digit, lowercase, uppercase, or special character.

```python

char = input("Enter a character: ")

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

This generates the multiplication table of a given number.

```python

num = int(input("Enter a number: "))

for i in range(1, 11):

print(f"{num} x {i} = {num * i}")

```

---

### 5. Fibonacci Sequence Generator (Using While Loop)

This prints Fibonacci numbers up to a given count.

```python

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

a, b = 0, 1

count = 0

while count < n:

print(a, end=" ")

a, b = b, a + b
count += 1

```

---

### 6. Factorial Generator

This calculates the factorial of a number using a loop.

```python

num = int(input("Enter a number: "))

factorial = 1

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

factorial *= i

print(f"Factorial of {num} is {factorial}")

```

---

### 7. Prime Number Analyzer (Using Function)

This checks if a number is prime or not.

```python

def is_prime(n):
if n < 2:

return False

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return False

return True

num = int(input("Enter a number: "))

if is_prime(num):

print("Prime Number")

else:

print("Not a Prime Number")

```

---

### 8. Simple Calculator Using Functions

A basic calculator performing arithmetic operations.

```python

def add(x, y):

return x + y
def subtract(x, y):

return x - y

def multiply(x, y):

return x * y

def divide(x, y):

return x / y if y != 0 else "Cannot divide by zero"

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

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

operation = input("Choose operation (+, -, *, /): ")

if operation == '+':

print("Result:", add(num1, num2))

elif operation == '-':

print("Result:", subtract(num1, num2))

elif operation == '*':

print("Result:", multiply(num1, num2))

elif operation == '/':

print("Result:", divide(num1, num2))

else:

print("Invalid operation")
```

---

### 9. Interactive Guessing Game

A simple number guessing game with user interaction.

```python

import random

secret_number = random.randint(1, 100)

attempts = 0

while True:

guess = int(input("Guess the number (1-100): "))

attempts += 1

if guess < secret_number:

print("Too low! Try again.")

elif guess > secret_number:

print("Too high! Try again.")

else:

print(f"Congratulations! You guessed it in {attempts} attempts.")

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

Experiment 4: Calculating Gross Salary of an Employee


Aim:

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.

Gross Salary Formula:

Gross Salary=BS+DA+TA+HRA\text{Gross Salary} = \text{BS} + \text{DA} + \text{TA} + \


text{HRA}

Allowance Calculations:

 Dearness Allowance (DA) = 70% of BS


 Travel Allowance (TA) = 30% of BS
 House Rent Allowance (HRA) = 10% of BS

Steps Involved:

1. Take the basic salary as input from the user.


2. Calculate DA, TA, and HRA based on the given percentages.
3. Calculate the gross salary by summing BS, DA, TA, and HRA.
4. Display the calculated gross salary.

Python Concepts Used:

 Input Handling: Using input() to read the basic salary.


 Mathematical Calculations: Calculating allowances based on the given percentages.
 Formatted Output: Displaying the gross salary using the print() function.

Code-

Step 1: Create the Input File

1. Open Notepad or any text editor.


2. Write some text in it. Example:
3. The fox jumps over the lazy dog. A quick brown fox.
4. Save the file as input.txt in the same directory where your Python script will be located.

Step 2: Write the Python Script

Create a Python script (extract_words.py) with the following code:

import re

def extract_words_by_length(filename, lengths):


try:
with open(filename, 'r') as file:
text = file.read()
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return
except Exception as e:
print(f"Error reading file '{filename}': {e}")
return

words = re.findall(r'\b\w+\b', text)


filtered_words = [word for word in words if len(word) in lengths]

print("Words matching the specified lengths:")


for word in filtered_words:
print(word)

if __name__ == "__main__":
file_name = 'input.txt'
desired_lengths = [3, 4, 5]
extract_words_by_length(file_name, desired_lengths)

Step 3: Run the Script

1. The output should display words of the specified lengths (3, 4, or 5 letters).

2. Finding Closest Points in 3D from a CSV File

This program reads a CSV file containing 3D coordinates and finds the two closest points.

Step 1: Create the CSV File

1. Open Excel or a text editor.


2. Add the following lines:
3. 1.0,2.0,3.0
4. 4.0,5.0,6.0
5. 1.1,2.1,3.1
6. 7.0,8.0,9.0
7. Save it as points.csv in the same directory as your script.

Step 2: Write the Python Script

Create a file closest_points.py and add the following:

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

Step 3: Run the Script


python closest_points.py

The output should display the two closest points and their distance.

3. Sorting City Names from a File

This script sorts city names alphabetically and writes them to a new file.

Step 1: Create the Input File

1. Open Notepad and enter:


2. Mumbai
3. Delhi
4. Kolkata
5. Bangalore
6. Chennai
7. Save as cities.txt.

Step 2: Write the Python Script

Create sort_cities.py:

def sort_cities(input_file, output_file):


try:
with open(input_file, 'r') as file:
cities = [line.strip() for line in file if line.strip()]
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
return

cities.sort(key=lambda city: city.lower())

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

print(f"Sorted cities written to '{output_file}'.")

if __name__ == "__main__":
input_filename = 'cities.txt'
output_filename = 'sorted_cities.txt'
sort_cities(input_filename, output_filename)

Step 3: Run the Script


python sort_cities.py

The sorted city names will be saved in sorted_cities.txt.

4. Creating an Executable File

Once you have created any of the Python programs above, you can turn them into an executable file
(.exe) using PyInstaller.

Step 1: Install PyInstaller

pip install pyinstaller

Step 2: Convert Python Script to Executable

To create an executable for Extracting Words script:

pyinstaller --onefile extract_words.py

 The --onefile flag bundles everything into a single .exe file.


 If you want a windowed app (without a console):
 pyinstaller --onefile --noconsole extract_words.py

Step 3: Find the Executable

 Go to the dist directory inside your project folder.


 You will find extract_words.exe (on Windows) or extract_words (on Linux/Mac).

Step 4: Run the Executable

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

Simple Interest (SI)=(P×R×T)100\text{Simple Interest (SI)} = \frac{(P \times R \times T)}{100}

Where:

 PP = Principal amount (the initial sum of money)


 RR = Rate of interest per annum
 TT = Time (in years)

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:

1. Start the program.


2. Prompt the user to enter the principal amount.
3. Prompt the user to enter the rate of interest.
4. Prompt the user to enter the time period in years.
5. Use the formula to calculate simple interest.
6. Display the calculated simple interest.
7. End the program.

Code –

import logging
# 1. Basic Exception Handling

def divide_numbers():

try:

num1 = float(input("Enter the numerator: "))

num2 = float(input("Enter the denominator: "))

result = num1 / num2

print(f"Result: {result}")

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Invalid input. Please enter numeric values.")

divide_numbers()

# 2. Custom Exceptions

class InsufficientFundsError(Exception):

pass

class InvalidAccountError(Exception):

pass

def withdraw_money(account_balance, amount):

if amount > account_balance:


raise InsufficientFundsError("Insufficient funds for this transaction.")

elif account_balance <= 0:

raise InvalidAccountError("Invalid account. Balance cannot be zero or negative.")

else:

account_balance -= amount

return account_balance

try:

balance = 500 # Example balance

amount_to_withdraw = float(input("Enter withdrawal amount: "))

new_balance = withdraw_money(balance, amount_to_withdraw)

print(f"New balance: {new_balance}")

except InsufficientFundsError as e:

print(e)

except InvalidAccountError as e:

print(e)

# 3. Logging for Debugging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %


(message)s')

def perform_operations():

logging.info("Starting operation...")

try:
x = int(input("Enter a number: "))

y = int(input("Enter another number: "))

logging.debug(f"Numbers entered: {x}, {y}")

result = x / y

logging.info(f"Result: {result}")

except ZeroDivisionError:

logging.error("Attempted to divide by zero.")

except ValueError:

logging.error("Invalid input provided.")

logging.info("Operation completed.")

perform_operations()

# 4. Using a Debugger

# To debug, use 'pdb':

# import pdb; pdb.set_trace()

def buggy_function():

x = 10

y = 0 # Intentional division by zero error

z = x / y # Use pdb to set breakpoints and step through code

print(z)
# Uncomment the next line and run with a debugger to analyze

# buggy_function()

# 5. Scientific Debugging Techniques

def find_bug():

numbers = [1, 2, 3, 4, 5]

total = 0

for i in range(len(numbers) + 1): # Intentional off-by-one error

total += numbers[i]

print(f"Total sum: {total}")

# Apply binary search debugging by checking midpoints

# Uncomment and run step by step

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

1. Addition (+): Adds two numbers.


2. Subtraction (-): Subtracts the second number from the first.
3. Multiplication (*): Multiplies two numbers.
4. Division (/): Divides the first number by the second, resulting in a float.
5. Modulus (%): Finds the remainder when the first number is divided by the second.

Input Handling:

 Python uses the input() function to accept user inputs.


 The input is converted to a numerical format using int() or float() for calculation.

Displaying Results:

 The print() function is used to display the results of the arithmetic operations.

Algorithm:

1. Start the program.


2. Prompt the user to enter two numbers.
3. Store the input values in variables after converting them to integers or floats.
4. Perform the following operations:
o Addition
o Subtraction
o Multiplication
o Division
o Modulus
5. Display the results of each operation.
6. End the program.
Code-

from datetime import datetime

# Encapsulation: Defining Event class with private attributes and getter methods

class Event:

def __init__(self, name, date, location):

self.__name = name

self.__date = datetime.strptime(date, '%Y-%m-%d')

self.__location = location

self.__participants = []

def register_participant(self, participant):

self.__participants.append(participant)

print(f"{participant.get_name()} registered for {self.__name}")

def get_details(self):

return f"Event: {self.__name}, Date: {self.__date.strftime('%Y-%m-%d')}, Location:


{self.__location}, Participants: {len(self.__participants)}"

# Inheritance: Organizer is a subclass of Event

class Organizer:

def __init__(self, name, contact):

self.name = name
self.contact = contact

def organize_event(self, event):

print(f"Organizer {self.name} is organizing {event.get_details()}")

# Inheritance: Participant class with base class Person

class Person:

def __init__(self, name, email):

self._name = name

self._email = email

def get_name(self):

return self._name

class Participant(Person):

def __init__(self, name, email, participant_type):

super().__init__(name, email)

self.participant_type = participant_type # Attendee, Speaker, Volunteer

def get_info(self):

return f"Participant: {self._name}, Email: {self._email}, Type: {self.participant_type}"

# Polymorphism: Different event types with overridden get_details method


class Workshop(Event):

def __init__(self, name, date, location, topic):

super().__init__(name, date, location)

self.topic = topic

def get_details(self):

return super().get_details() + f", Topic: {self.topic}"

class Concert(Event):

def __init__(self, name, date, location, artist):

super().__init__(name, date, location)

self.artist = artist

def get_details(self):

return super().get_details() + f", Artist: {self.artist}"

# Testing the Event Management System

if __name__ == "__main__":

event1 = Workshop("AI Workshop", "2025-06-15", "Hall A", "Machine Learning Basics")

event2 = Concert("Rock Night", "2025-07-20", "Main Auditorium", "The Rockers")

organizer = Organizer("Alice Johnson", "[email protected]")

participant1 = Participant("Bob Smith", "[email protected]", "Attendee")


participant2 = Participant("Charlie Brown", "[email protected]", "Speaker")

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:

1. Currency conversion (e.g., Rupees to Dollars).


2. Temperature conversion (e.g., Celsius to Fahrenheit).
3. Length conversion (e.g., Inches to Feet).

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:

1. Import the Tkinter library.


2. Create the main application window.
3. Add labels, input fields, and buttons for each conversion type.
4. Define functions for each conversion.
5. Bind the functions to button click events.
6. Display the converted results in the GUI.
7. Run the Tkinter event loop.

Code-
1. GUI for Developing Conversion Utilities: Develop a Python GUI application that

performs various unit conversions such as currency (Rupees to Dollars), temperature

(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

labels to display the results

import tkinter as tk

from tkinter import ttk

def convert():

value = float(entry.get())

conversion_type = conversion_var.get()

result = ''

if conversion_type == 'Rupees to Dollars':

result = f'${value / 82:.2f}'

elif conversion_type == 'Celsius to Fahrenheit':

result = f'{(value * 9/5) + 32:.2f} °F'

elif conversion_type == 'Inches to Feet':

result = f'{value / 12:.2f} ft'

result_label.config(text=f'Result: {result}')
root = tk.Tk()

root.title('Unit Conversion Utilities')

root.geometry('400x200')

# Input field for value

tk.Label(root, text='Enter Value:').pack()

entry = tk.Entry(root)

entry.pack()

# Conversion type dropdown

tk.Label(root, text='Select Conversion Type:').pack()

conversion_var = tk.StringVar(value='Rupees to Dollars')

conversion_dropdown = ttk.Combobox(root, textvariable=conversion_var)

conversion_dropdown['values'] = ('Rupees to Dollars', 'Celsius to Fahrenheit', 'Inches to Feet')

conversion_dropdown.pack()

# Convert Button

convert_button = tk.Button(root, text='Convert', command=convert)

convert_button.pack()

# Result Label

result_label = tk.Label(root, text='Result:')

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

from tkinter import ttk

import math

def calculate_area():

shape = shape_var.get()

try:

if shape == 'Circle':

radius = float(entry1.get())

area = math.pi * radius ** 2

result = f'Area of Circle: {area:.2f}'

elif shape == 'Rectangle':

length = float(entry1.get())
width = float(entry2.get())

area = length * width

result = f'Area of Rectangle: {area:.2f}'

elif shape == 'Triangle':

base = float(entry1.get())

height = float(entry2.get())

area = 0.5 * base * height

result = f'Area of Triangle: {area:.2f}'

result_label.config(text=result)

except ValueError:

result_label.config(text='Please enter valid numbers')

root = tk.Tk()

root.title('Geometric Area Calculator')

root.geometry('400x300')

# Shape selection

tk.Label(root, text='Select Shape:').pack()

shape_var = tk.StringVar(value='Circle')

shape_dropdown = ttk.Combobox(root, textvariable=shape_var)

shape_dropdown['values'] = ('Circle', 'Rectangle', 'Triangle')

shape_dropdown.pack()
# Dimension inputs

entry1 = tk.Entry(root)

entry1.pack()

entry2 = tk.Entry(root)

entry2.pack()

# Calculate button

calculate_button = tk.Button(root, text='Calculate Area', command=calculate_area)

calculate_button.pack()

# Result label

result_label = tk.Label(root, text='Area:')

result_label.pack()

root.mainloop()

-----------------------------------------------------------------------------

3. College Admission Registration Form: The college admission registration form collects

essential personal, educational, and contact information from prospective

students. Create a GUI as shown in Figure-1 that allows the user to input his/her

name, branch and

favorite game. When the user clicks the Submit button, it should display the output as
illustrated.

import tkinter as tk

from tkinter import messagebox

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

output = f'Your name is {name}.\n{name} is from {branch} Department.{game_text}'

messagebox.showinfo('Output', output)

root = tk.Tk()
root.title('College Admission Registration Form')

root.geometry('400x300')

# Student Name

tk.Label(root, text='Enter Student Name:').pack()

name_entry = tk.Entry(root)

name_entry.pack()

# Branch Selection

tk.Label(root, text='Select Your Branch:').pack()

branch_var = tk.StringVar(value='Computer Engineering')

tk.Radiobutton(root, text='Computer Engineering', variable=branch_var, value='Computer


Engineering').pack()

tk.Radiobutton(root, text='Information Technology', variable=branch_var, value='Information


Technology').pack()

# Favorite Games

tk.Label(root, text='Select Favorite Games:').pack()

cricket_var = tk.BooleanVar()

football_var = tk.BooleanVar()

badminton_var = tk.BooleanVar()

tk.Checkbutton(root, text='Cricket', variable=cricket_var).pack()

tk.Checkbutton(root, text='Football', variable=football_var).pack()

tk.Checkbutton(root, text='Badminton', variable=badminton_var).pack()


# Submit Button

submit_button = tk.Button(root, text='Submit', command=submit_details)

submit_button.pack()

root.mainloop()

Conclusion:

The experiment successfully demonstrated the development of a user-friendly GUI application


for unit conversions using Python and Tkinter. The application allowed users to perform
conversions interactively and displayed accurate results based on user input. This experiment
enhanced skills in GUI development and real-world application of Python programming.

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.

Regular Expressions for Validation:

1. Phone Number Validation:


o A valid phone number usually follows patterns like:
 Starts with a country code (optional) like +91 or 91.
 Followed by 10 digits.
 May include spaces, hyphens, or parentheses.
o Example Pattern: ^(\+91[\-\s]?)?[0]?[789]\d{9}$
2. Email ID Validation:
o An email ID typically follows the pattern:
 Username: Alphanumeric characters, periods, underscores.
 At symbol (@).
 Domain name: Alphanumeric characters and periods.
 Top-level domain (TLD): Commonly 2-4 characters.
o Example Pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$

Algorithm:

1. Start the program.


2. Prompt the user to enter a phone number and an email ID.
3. Use regular expressions to validate the phone number.
4. Use regular expressions to validate the email ID.
5. Display a message indicating whether each input is valid or not.
6. End the program.

Code-
import re

# 1. Validate Phone Number and Email ID

def validate_phone_email():

phone_pattern = re.compile(r"^\+?[0-9]{10,15}$") # Supports international and local


numbers

email_pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")

phone = input("Enter phone number: ")

email = input("Enter email ID: ")

if phone_pattern.match(phone):

print("Valid phone number.")

else:

print("Invalid phone number.")

if email_pattern.match(email):

print("Valid email ID.")

else:

print("Invalid email ID.")

# 2. Password Strength Checker

def check_password_strength():
password_pattern = re.compile(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\
d@$!%*?&]{8,}$")

password = input("Enter a password: ")

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*)?$")

url = input("Enter a URL: ")

if url_pattern.match(url):

print("Valid URL.")

else:

print("Invalid URL.")

# 4. Extract Data from Text File

def extract_data_from_file(file_path):

with open(file_path, 'r') as file:

content = file.read()
emails = re.findall(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", content)

phone_numbers = re.findall(r"\+?[0-9]{10,15}", content)

dates = re.findall(r"\b\d{2}/\d{2}/\d{4}\b", content) # Matches MM/DD/YYYY format

print("Extracted Emails:", emails)

print("Extracted Phone Numbers:", phone_numbers)

print("Extracted Dates:", dates)

# Testing the functions

if __name__ == "__main__":

validate_phone_email()

check_password_strength()

validate_url()

# Provide the path of a text file containing data to extract

# 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

Experiment 9: Creating and Manipulating Arrays using NumPy


Aim:

To create and manipulate one-dimensional (1D), two-dimensional (2D), and three-dimensional


(3D) arrays using the NumPy library in Python. Additionally, perform basic operations like
reshaping, slicing, and indexing on the arrays.

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:

 np.array([1, 2, 3]) - Creating a 1D array.


 np.reshape(array, (3, 3)) - Reshaping an array.
 array[0:2] - Slicing the array.

Algorithm:

1. Step 1: Import the NumPy library using import numpy as np.


2. Step 2: Create a 1D, 2D, and 3D array using np.array().
3. Step 3: Perform reshaping, slicing, and indexing operations on the arrays.
4. Step 4: Perform basic arithmetic operations between arrays.
5. Step 5: Display the results of each operation.
6. Step 6: End the program.

Code-

import numpy as np

# 1. Creating and Manipulating Arrays

def create_arrays():

# 1D Array

array_1d = np.array([1, 2, 3, 4, 5])

print("1D Array:", array_1d)

# 2D Array

array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("2D Array:\n", array_2d)

# 3D Array

array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("3D Array:\n", array_3d)

# Reshaping

reshaped_array = array_1d.reshape((5, 1))

print("Reshaped 1D to 2D:\n", reshaped_array)


# Slicing and Indexing

print("Slice first row of 2D Array:", array_2d[0, :])

print("Element at (1,2) in 2D Array:", array_2d[1, 2])

# 2. Array Mathematics

def array_math():

array_a = np.array([[1, 2, 3], [4, 5, 6]])

array_b = np.array([[7, 8, 9], [10, 11, 12]])

print("Element-wise Addition:\n", array_a + array_b)

print("Element-wise Subtraction:\n", array_a - array_b)

print("Element-wise Multiplication:\n", array_a * array_b)

print("Element-wise Division:\n", array_a / array_b)

# Dot Product

vector1 = np.array([1, 2, 3])

vector2 = np.array([4, 5, 6])

dot_product = np.dot(vector1, vector2)

print("Dot Product:", dot_product)

# Cross Product

cross_product = np.cross(vector1, vector2)

print("Cross Product:", cross_product)


# 3. Statistical Operations

def statistical_operations():

data = np.array([10, 20, 30, 40, 50])

print("Mean:", np.mean(data))

print("Median:", np.median(data))

print("Standard Deviation:", np.std(data))

print("Variance:", np.var(data))

# Correlation Coefficients

data2 = np.array([5, 10, 15, 20, 25])

correlation = np.corrcoef(data, data2)

print("Correlation Coefficients:\n", correlation)

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:

1. Data Loading: Using Pandas to read CSV files into DataFrames.


2. Data Cleaning: Handling missing values, duplicates, and inconsistencies.
3. Data Aggregation: Performing summary statistics, grouping, and transformations.
4. Data Visualization: Plotting graphs like line plots, bar plots, histograms, scatter plots,
and pie charts using Matplotlib.

Steps Involved:

1. Loading and Inspecting Data:


o Load a CSV file (e.g., COVID-19 cases data) into a DataFrame.
o Display the first few rows and check data types.
2. Data Cleaning:
o Identify and handle missing values.
o Remove duplicate rows.
o Ensure data consistency.
3. Data Aggregation:
o Perform statistical operations like mean, sum, and grouping.
4. Data Visualization:
o Generate various plots:
 Line plot for trends (e.g., case numbers over time).
 Bar plot for comparing data (e.g., cases by region).
 Histogram to show distribution (e.g., daily case counts).
 Scatter plot for relationships (e.g., age vs. price of cars).
 Pie chart for proportion (e.g., fuel types in car data).
Code-

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Task 1: Loading and Inspecting Data


def load_and_inspect(file_path):
df = pd.read_csv(file_path)
print("First few rows:")
print(df.head())
print("\nData Types:")
print(df.dtypes)
print("\nBasic Statistics:")
print(df.describe())
return df

# Task 2: Data Cleaning


def clean_data(df):
df.fillna(df.mean(), inplace=True) # Fill missing values with column mean
df.drop_duplicates(inplace=True) # Remove duplicates
print("\nMissing values after cleaning:")
print(df.isnull().sum())
return df

# Task 3: Data Aggregation


def aggregate_data(df):
aggregated = df.groupby("species").agg({'sepal_length': ['mean', 'min', 'max']})
print("\nAggregated Data:")
print(aggregated)

# Task 4: Plotting Graphs


def plot_graphs(df):
# Line Plot Example (COVID-19 Cases Trend)
if 'date' in df.columns and 'cases' in df.columns:
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df['cases'].plot(title='COVID-19 Cases Trend', xlabel='Date', ylabel='Cases')
plt.show()

# Scatter Plot (Car Age vs Price)


if 'Age' in df.columns and 'Price' in df.columns:
plt.figure(figsize=(8, 5))
sns.scatterplot(x=df['Age'], y=df['Price'])
plt.title('Car Age vs Price')
plt.xlabel('Age of Car')
plt.ylabel('Price')
plt.show()
# Histogram (Kilometers Driven)
if 'Kilometers_Driven' in df.columns:
plt.figure(figsize=(8, 5))
sns.histplot(df['Kilometers_Driven'], bins=30, kde=True)
plt.title('Distribution of Kilometers Driven')
plt.show()

# Bar Plot (Car Distribution by Fuel Type)


if 'Fuel_Type' in df.columns:
plt.figure(figsize=(8, 5))
sns.countplot(x=df['Fuel_Type'])
plt.title('Distribution of Cars by Fuel Type')
plt.show()

# Pie Chart (Percentage Distribution of Fuel Types)


if 'Fuel_Type' in df.columns:
fuel_counts = df['Fuel_Type'].value_counts()
plt.figure(figsize=(8, 5))
plt.pie(fuel_counts, labels=fuel_counts.index, autopct='%1.1f%%')
plt.title('Percentage Distribution of Cars by Fuel Type')
plt.show()

# Box Plot (Car Prices across Fuel Types)


if 'Fuel_Type' in df.columns and 'Price' in df.columns:
plt.figure(figsize=(8, 5))
sns.boxplot(x='Fuel_Type', y='Price', data=df)
plt.title('Car Price Distribution by Fuel Type')
plt.show()

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.

You might also like