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

Python Final i32 Merged

The document outlines various Python programming exercises aimed at teaching fundamental concepts such as salary calculation, simple interest, data structures like lists and dictionaries, control structures, file handling, and exception management. Each section includes a specific aim, theory, program code, output examples, and conclusions summarizing the effectiveness of the implemented programs. The exercises are designed for students at Thadomal Shahani Engineering College, focusing on practical applications of Python in real-world scenarios.

Uploaded by

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

Python Final i32 Merged

The document outlines various Python programming exercises aimed at teaching fundamental concepts such as salary calculation, simple interest, data structures like lists and dictionaries, control structures, file handling, and exception management. Each section includes a specific aim, theory, program code, output examples, and conclusions summarizing the effectiveness of the implemented programs. The exercises are designed for students at Thadomal Shahani Engineering College, focusing on practical applications of Python in real-world scenarios.

Uploaded by

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

THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no:I-32

[31/01/25] 1. Basics of Python:LO1


1.
AIM:
To write a Python program that calculates the gross salary of an employee using given
percentages for DA, TA, and HRA.

THEORY:
Gross salary is the total salary an employee earns before deductions like taxes, PF, etc. It consists
of the basic salary and various allowances.

The program takes the Basic Salary (BS) as input from the user and calculates:
- Dearness Allowance (DA) = 70% of BS
- Travel Allowance (TA) = 30% of BS
- House Rent Allowance (HRA) = 10% of BS

Gross Salary = BS + DA + TA + HRA

This program demonstrates the use of:


- Basic arithmetic operations
- User input handling
- Data type conversion
- Output formatting

Program :

bs = float(input("Enter Basic Salary: "))

da = 0.70 * bs
ta = 0.30 * bs
hra = 0.10 * bs

gross_salary = bs + da + ta + hra

1
print(f"\nBasic Salary: ₹{bs:.2f}")
print(f"Dearness Allowance (70%): ₹{da:.2f}")
print(f"Travel Allowance (30%): ₹{ta:.2f}")
print(f"House Rent Allowance (10%): ₹{hra:.2f}")
print(f"Gross Salary: ₹{gross_salary:.2f}")

OUTPUT:
Enter Basic Salary: 50000

Basic Salary: ₹50000.00


Dearness Allowance (70%): ₹35000.00
Travel Allowance (30%): ₹15000.00
House Rent Allowance (10%): ₹5000.00
Gross Salary: ₹105000.00

CONCLUSION:
The program successfully calculates the gross salary of an employee by taking the basic salary as
input
and computing allowances based on fixed percentages. This allows organizations to automate
salary breakdowns
and ensure accurate financial calculations in payroll systems.

2
2.
AIM:
To write a Python program that calculates Simple Interest based on user input for principal, rate
of interest, and time.

THEORY:
Simple Interest is the method of calculating interest on a principal amount over a period of time at
a fixed rate.

Formula:
Simple Interest (SI) = (Principal × Rate × Time) / 100

Where:
- Principal = Initial amount of money invested/loaned
- Rate = Annual interest rate (in %)
- Time = Duration of the loan/investment in years

This program demonstrates basic mathematical computation and input/output handling in Python.

PROGRAM:'
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"\nPrincipal Amount: ₹{principal:.2f}")


print(f"Rate of Interest: {rate:.2f}%")
print(f"Time Period: {time:.2f} years")
print(f"Simple Interest: ₹{simple_interest:.2f}")

OUTPUT:
Example:
Enter the Principal amount (₹): 10000
Enter the Rate of Interest (%): 5
Enter the Time period (in years): 2

Principal Amount: ₹10000.00


Rate of Interest: 5.00%
Time Period: 2.00 years
Simple Interest: ₹1000.00

3
CONCLUSION:
The program accurately computes the simple interest using the standard formula and provides a
clear breakdown
of the principal, rate, time, and resulting interest. This type of computation is commonly used in
financial applications.

4
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no:I-15

[14/02/25] 2. Built in Datatypes: LO1

1.
Aim: To develop a Python program to manage a task list using lists and tuples, including adding,

removing, updating, and sorting tasks.

Theory:
- A list in Python is a collection of items that are ordered and mutable.
- A tuple is an immutable collection, meaning it cannot be changed after creation.
- This program will use a list of tuples to manage tasks, where each tuple contains (task_id,
task_name, priority).
- Functions will be implemented to add, remove, update, and sort tasks based on priority.

Program :

def display_tasks(tasks):
if not tasks:
print("No tasks available.")
return
print("\nTask List:")
print("ID | Task Name | Priority")
print(" ")
for task in tasks:
print(f"{task[0]:<3} | {task[1]:<15} | {task[2]}")

def add_task(tasks, task_id, task_name, priority):


tasks.append((task_id, task_name, priority))
print(f"Task '{task_name}' added successfully!")

5
def remove_task(tasks, task_id):
for task in tasks:
if task[0] == task_id:
tasks.remove(task)
print(f"Task '{task[1]}' removed successfully!")
return
print("Task ID not found.")

def update_task(tasks, task_id, new_name, new_priority):


for i, task in enumerate(tasks):
if task[0] == task_id:
tasks[i] = (task_id, new_name, new_priority)
print(f"Task '{task_id}' updated successfully!")
return
print("Task ID not found.")

def sort_tasks(tasks):
tasks.sort(key=lambda x: x[2])
print("Tasks sorted by priority!")

tasks = []
add_task(tasks, 1, "Complete assignment", 2)
add_task(tasks, 2, "Go grocery shopping", 3)
add_task(tasks, 3, "Read a book", 1)

display_tasks(tasks)

remove_task(tasks, 2)
display_tasks(tasks)

update_task(tasks, 1, "Complete math assignment", 1)


display_tasks(tasks)

sort_tasks(tasks)
display_tasks(tasks)

Output:

Task List:
ID | Task Name | Priority

6
1 | Complete assignment | 2
2 | Go grocery shopping | 3
3 | Read a book |1

Task 'Go grocery shopping' removed successfully!

Task List:
ID | Task Name | Priority

1 | Complete assignment | 2
3 | Read a book |1

Task '1' updated successfully!

Task List:
ID | Task Name | Priority

1 | Complete math assignment | 1


3 | Read a book |1

Tasks sorted by priority!

Conclusion:

• This program successfully implements a task list manager using lists and

tuples. It allows users to add, remove, update, and sort tasks efficiently.

7
2.
Aim:To develop a Python program demonstrating the use of sets and performing set operations (union,
intersection, difference) to manage student enrollments in multiple courses or entrance exams like CET,
JEE, and NEET.

Theory:

- A set in Python is an unordered collection of unique elements.

- Set operations like union, intersection, and difference help in analyzing relationships between
different groups.

- Union: Combines elements from multiple sets.

- Intersection: Finds common elements in sets.

- Difference: Finds elements in one set but not in another.

PROGRAM:

cet_students = {"A", "B", "C", "D"}


jee_students = {"C", "E", "F", "B"}
neet_students = {"G", "E", "A", "D"}

print("Students enrolled in CET:", cet_students)


print("Students enrolled in JEE:", jee_students)
print("Students enrolled in NEET:", neet_students)

all_students = cet_students.union(jee_students, neet_students)


print("\nStudents appearing in at least one exam:", all_students)

common_cet_jee = cet_students.intersection(jee_students)
print("\nStudents appearing in both CET and JEE:", common_cet_jee)

cet_not_jee = cet_students.difference(jee_students)
print("\nStudents appearing in CET but not in JEE:", cet_not_jee)

jee_not_neet = jee_students.difference(neet_students)
print("\nStudents appearing in JEE but not in NEET:", jee_not_neet)

8
Output:
Students enrolled in CET: {'A', 'B', 'C', 'D'}
Students enrolled in JEE: {'C', 'E', 'F', 'B'}
Students enrolled in NEET: {'G', 'E', 'A', 'D'}

Students appearing in at least one exam: {'A', 'B', 'C', 'D', 'E', 'F', 'G'}

Students appearing in both CET and JEE: {'C', 'B'}

Students appearing in CET but not in JEE: {'A', 'D'}

Students appearing in JEE but not in NEET: {'C', 'F', 'B'}

Conclusion:

This program successfully demonstrates the use of sets in Python to manage student enrollments
in multiple entrance exams.

It performs union, intersection, and difference operations to analyze student participation.

9
3.
Aim: To develop a Python program to create, update, and manipulate a dictionary of student

records, including their grades and attendance.

Theory:
-A dictionary in Python is a collection of key-value pairs, where each key is unique.

- This program will use a dictionary to store student records with keys as student IDs and values
as another dictionary containing name, grade, and attendance.

- Operations such as adding, updating, and displaying student records will be performed.

Program:
students = {}

def add_student(student_id, name, grade, attendance):


students[student_id] = {"Name": name, "Grade": grade, "Attendance": attendance}
print(f"Student {name} added successfully!")

def update_grade(student_id, new_grade):


if student_id in students:
students[student_id]["Grade"] = new_grade
print(f"Updated grade for {students[student_id]['Name']} to {new_grade}.")
else:
print("Student ID not found.")

def update_attendance(student_id, new_attendance):


if student_id in students:
students[student_id]["Attendance"] = new_attendance
print(f"Updated attendance for {students[student_id]['Name']} to {new_attendance}%.")
else:
print("Student ID not found.")

def display_students():
if not students:
print("No student records available.")
return

10
print("\nStudent Records:")

for student_id, info in students.items():


print(f"ID: {student_id}, Name: {info['Name']}, Grade: {info['Grade']}, Attendance:
{info['Attendance']}%")

add_student(1, "Roshan", "A", 95)


add_student(2, "Virat Kohli", "B", 85)
display_students()

update_grade(2, "A")
update_attendance(1, 98)
display_students()

Output:

Student Roshan added successfully!


Student Virat Kohli added successfully!

Student Records:
ID: 1, Name: Roshan, Grade: A, Attendance: 95%
ID: 2, Name: Virat Kohli, Grade: B, Attendance: 85%

Updated grade for Virat Kohli to A.


Updated attendance for Roshan to 98%.

Student Records:
ID: 1, Name: Roshan, Grade: A, Attendance: 98%
ID: 2, Name: Virat Kohli, Grade: A, Attendance: 85%

Conclusion:
This program successfully demonstrates how to use dictionaries to manage student records. It allows

adding, updating, and displaying student details efficiently.

11
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no:I-15

[07/02/25] 3. Control Structures: LO2


1.
AIM: Write a Python program to print a triangle pattern (give any),emphasizing the transition from C to
Python syntax.

THEORY:
- Demonstrates nested loops and indentation in Python.
- Uses range() and string multiplication.

PROGRAM:
def print_triangle(n):
for i in range(1, n + 1):
print("* " * i)

print("Triangle Pattern:")
print_triangle(5)

OUTPUT:
*
**
***
****
*****

Conclusion:
Conditional logic in Python effectively categorizes numbers as even or odd through simple checks.

12
2.
Aim: Design a Python program to compute the factorial of a given integer N.

Theory:
• The factorial of a number is the product of all positive integers up to that number.
• Can be computed using iterative loops or recursion.
• Python’s handling of large integers allows computing factorials for big numbers.
• The math.factorial() function provides a built-in solution.
• Recursive functions simplify the logic for factorial computation.

Program:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

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


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

OUTPUT:
Enter a number: 5
Factorial of 5 is 120

Conclusion:
Python’s loop and recursion capabilities allow efficient computation of factorials for various applications.

13
THADOMAL SHAHANI ENGINEERING
DEPARTMENT OF INFORMATION
TECHNOLOGY

Roll no:I-15

[20/2/25] 4. File Handling: LO3


1.
Aim: 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.

Theory:

• Python’s file handling capabilities allow reading and writing files.

• String manipulation functions help filter words based on length.

• Looping through file content allows targeted word extraction.

• Regular expressions can enhance pattern matching.

• Handling exceptions like FileNotFoundError ensures error-free execution

Program :

with open("/Users/shauryasingh/Desktop/file handling/q15.txt","r") as file:


text=file.read()
words=text.split(" “)
maxlen=0
for word in words:
if(len(word)>=maxlen):
maxlen=len(word)

desired=int(input("Enter the numbver of letters in a word:"))


found=[word for word in words if len(word)==desired]
if found:
print("words of length",desired)
for element in found:
print(element)
else:
print("No words of length”,desired)

14
Output:
1,2,3
4,5,6
7,8,9
2,3,4

Conclusion:

File handling and string manipulation enable efficient extraction of words based on length from
text files.

15
2.
Aim: 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.

Theory:
• Reading file content line by line allows handling city names.

• Sorting functions like sorted() or sort() alphabetically organize data.

• Writing sorted data to a new file helps maintain data integrity.

• Handling file encoding prevents character-related issues.

• Removing duplicates enhances data accuracy.

Program :

with open ('/Users/shauryasingh/python practice/q17.txt','r') as file:


cities=file.readlines()
cities=[city.strip() for city in cities]
cities.sort()
print("sorted cities:")
for city in cities:
print(city)

Output:
sorted cities:
Bengaluru
Chennai
Delhi
Kolkata
Mumbai

Conclusion:
File reading and sorting enable systematic arrangement of city names for better data managrmrnt

16
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no:I-15

[04/04/25] 5. Exception Handling :LO3

1.
Aim:
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.

Theory:
In Python, exception handling is used to manage errors that may occur during program execution.
This helps prevent the program from crashing and provides a way to respond to errors gracefully.

Python uses the `try-except` block to catch and handle exceptions. Common exceptions include:
- `ValueError`: Occurs when the input cannot be converted to a number (e.g., entering text instead
of a number).
- `ZeroDivisionError`: Occurs when trying to divide a number by zero, which is mathematically
undefined.

The structure of exception handling:


- `try`: Code that might raise an exception is placed here.
- `except`: Code to handle the error is written here.
- `else`: Executes if no exceptions occur.
- `finally`: Executes no matter what, often used for cleanup or final messages.

By using exception handling, we can make programs more robust and user-friendly.

Program:
try:
num1 = input("Enter the numerator: ")
num2 = input("Enter the denominator: ")
num1 = float(num1)
num2 = float(num2)
result = num1 / num2

17
except ValueError:
print("Invalid input! Please enter numeric values only.")

except ZeroDivisionError:
print("Error! Division by zero is not allowed.")

except TypeError:
print("Type error occurred! Please check your input types.")

except OverflowError:
print("Overflow error! The number is too large to handle.")

except Exception as e:
print(f"An unexpected error occurred: {e}")

else:
print(f"Result of {num1} / {num2} = {result:.2f}")

finally:
print("Program execution completed.")

divide_numbers()

Output:
Enter the numerator: 100
Enter the denominator: 4
Result of 100.0 / 4.0 = 25.00
Program execution completed.

Enter the numerator: 15


Enter the denominator: 0
Error! Division by zero is not allowed.
Program execution completed.

Enter the numerator: abc


Enter the denominator: 5
Invalid input! Please enter numeric values only.
Program execution completed.

Enter the numerator: 1e308

18
Enter the denominator: 1e-308
Result of 1e+308 / 1e-308 = inf
Program execution completed.

Enter the numerator: ^C


An unexpected error occurred: EOF when reading a line
Program execution completed.

Conclusion:
The program successfully handles user input and performs division while managing common
errors using exception handling.
It prevents the program from crashing due to invalid input or division by zero, making it more
reliable and user-friendly.

19
2.
Aim:
To demonstrate the use of a Python debugger (`pdb`) by running a sample program that contains
intentional errors and tracing them step by step.

Theory:
Debugging is a critical part of software development that helps identify and fix bugs in the code.
Python provides a built-in debugger called `pdb` which allows developers to:
- Step through the code line by line
- Examine variable values
- Set breakpoints
- Continue execution or quit debugging as needed

The basic commands in `pdb` include:


- `l` (list): Show source code around the current line
- `n` (next): Execute the next line
- `s` (step): Step into function calls
- `c` (continue): Continue execution until the next breakpoint
- `p` (print): Print the value of a variable
- `q` (quit): Exit the debugger

Using `pdb.set_trace()` sets a breakpoint in the code.

Program:
import pdb

def calculate_area(length, width):

pdb.set_trace() # Debugger starts here


area = length * width
return area

def main()
l = "10"
w=5
result = calculate_area(l, w)

print("Area is:", result)

main()

20
Output:
> /.../filename.py(6)calculate_area()
-> area = length * width
(Pdb) p length
'10'
(Pdb) p width
5
(Pdb) n
> /.../filename.py(7)calculate_area()
-> return area
(Pdb) p area
'1010101010'
(Pdb) q
Program exited.

Conclusion:
The program demonstrates how to use the `pdb` debugger to trace and fix bugs in Python code.
Using `pdb.set_trace()` allowed us to pause execution, inspect variables, and understand why the
output was incorrect.
This is a powerful tool for diagnosing logic and runtime errors during development.

21
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no:I-15
[28/2/25] 6. OOP: LO4
AIM: To design a system using classes for vehicles, rental agencies, and rental transactions.
Implement methods to handle vehicle availability, rental periods, pricing, and customer bookings.

THEORY:

- Object-oriented programming (OOP) is a programming paradigm that organizes data and


behavior into reusable structures called classes and objects.

- It focuses on four main principles:

1. Encapsulation: Bundling data and methods within a class.

2. Abstraction: Hiding implementation details while exposing functionality.

3. Inheritance: Creating new classes from existing ones to promote code reuse.

4. Polymorphism: Using a single interface to represent different data types.

- This system includes three main classes:

1. Vehicle: Represents individual rental vehicles with attributes like model, type, and availability.

2. RentalAgency: Manages vehicles and rental transactions.

3. RentalTransaction: Handles rental details like duration, pricing, and customer details.

- Methods will be implemented to handle vehicle availability, rental processing, and pricing
calculations efficiently.

PROGRAM:

class Vehicle:
def init (self, vehicle_id, model, vehicle_type, rent_per_day, available=True):

22
self.vehicle_id = vehicle_id
self.model = model
self.vehicle_type = vehicle_type
self.rent_per_day = rent_per_day
self.available = available

def mark_rented(self):
self.available = False

def mark_available(self):
self.available = True

class RentalAgency:
def init (self, name):
self.name = name
self.vehicles = []

def add_vehicle(self, vehicle):


self.vehicles.append(vehicle)

def display_available_vehicles(self):
print("\nAvailable Vehicles:")
for vehicle in self.vehicles:
if vehicle.available:
print(f"ID: {vehicle.vehicle_id}, Model: {vehicle.model}, Type:
{vehicle.vehicle_type}, Rent: rs{vehicle.rent_per_day}/day")

def rent_vehicle(self, vehicle_id, customer_name, rental_days):


for vehicle in self.vehicles:
if vehicle.vehicle_id == vehicle_id and vehicle.available:
transaction = RentalTransaction(vehicle, customer_name, rental_days)
vehicle.mark_rented()
return transaction
return None

class RentalTransaction:
def init (self, vehicle, customer_name, rental_days):
self.vehicle = vehicle
self.customer_name = customer_name
self.rental_days = rental_days
self.total_cost = self.calculate_total_cost()

23
def calculate_total_cost(self):
return self.vehicle.rent_per_day * self.rental_days

def display_receipt(self):
print("\nRental Receipt")
print(f"Customer: {self.customer_name}")
print(f"Vehicle Model: {self.vehicle.model} ({self.vehicle.vehicle_type})")
print(f"Rental Period: {self.rental_days} days")
print(f"Total Cost: rs{self.total_cost}")

agency = RentalAgency("Quick Rentals")


agency.add_vehicle(Vehicle(1, "Toyota Corolla", "Sedan", 50))
agency.add_vehicle(Vehicle(2, "Honda Civic", "Sedan", 55))
agency.add_vehicle(Vehicle(3, "Ford Explorer", "SUV", 80))

agency.display_available_vehicles()

transaction = agency.rent_vehicle(2, "Roshan", 3) if


transaction:
transaction.display_receipt()
else:
print("Vehicle not available!")

agency.display_available_vehicles()

OUTPUT:

Available Vehicles:
ID: 1, Model: Toyota Corolla, Type: Sedan, Rent: rs50/day
ID: 2, Model: Honda Civic, Type: Sedan, Rent: rs55/day
ID: 3, Model: Ford Explorer, Type: SUV, Rent: rs80/day

Rental Receipt
Customer: Roshan
Vehicle Model: Honda Civic (Sedan)
Rental Period: 3 days
Total Cost: rs165

24
Available Vehicles:
ID: 1, Model: Toyota Corolla, Type: Sedan, Rent: rs50/day
ID: 3, Model: Ford Explorer, Type: SUV, Rent: rs80/day

CONCLUSION:

- Successfully implemented a rental system using object-oriented principles in Python.

- Managed vehicle availability and rental transactions efficiently.

- Demonstrated the use of classes, methods, and interactions between objects to create a real-world
application.

- Showcased the benefits of OOP principles such as encapsulation, abstraction, and modular
design.

25
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no: I-15


[11/04/25] 7. GUI :LO5

Aim:
To write a Python GUI program using Tkinter that creates a student form with input fields for
Name, Age, Branch, and Favourite Games, and displays the entered information in a text box.

Theory:
Graphical User Interface (GUI) applications allow users to interact with software through visual
elements like buttons, text boxes, and labels. Python provides several libraries for GUI
development; one of the most popular and built-in options is `Tkinter`.

Key Tkinter Widgets Used:


- `Label`: Displays text on the window.
- `Entry`: Allows single-line user input.
- `Text`: Used to display multi-line text output.
- `Button`: Executes a function when clicked.

Event Handling:
In GUI programming, an event (like a button click) triggers a function. In this program, clicking
the "Submit" button gathers the input data and displays it in the text box.

Program:
import tkinter as tk
from tkinter import messagebox

def display_info():
name = entry_name.get()
age = entry_age.get()
branch = entry_branch.get()
games = entry_games.get()

26
if not name or not age or not branch or not games:
messagebox.showwarning("Input Error", "Please fill all the fields.")
return

output_box.delete("1.0", tk.END)

info = f"Student Information:\n"


info += f"Name: {name}\n"
info += f"Age: {age}\n"
info += f"Branch: {branch}\n"
info += f"Favourite Games: {games}\n"

output_box.insert(tk.END, info)

root = tk.Tk()
root.title("Student Form")
root.geometry("400x400")

tk.Label(root, text="Name").pack(pady=5)
entry_name = tk.Entry(root)
entry_name.pack(pady=5)

tk.Label(root, text="Age").pack(pady=5)
entry_age = tk.Entry(root)
entry_age.pack(pady=5)

tk.Label(root, text="Branch").pack(pady=5)
entry_branch = tk.Entry(root)
entry_branch.pack(pady=5)

tk.Label(root, text="Favourite Games").pack(pady=5)


entry_games = tk.Entry(root)
entry_games.pack(pady=5)

submit_btn = tk.Button(root, text="Submit", command=display_info)


submit_btn.pack(pady=10)
output_box = tk.Text(root, height=8, width=40)
output_box.pack(pady=10)

root.mainloop()

27
Output:

Conclusion:
The program successfully demonstrates the use of `Tkinter` to create a basic GUI-based student
form.
It takes input from the user and displays the details in a text box upon submission.
Such GUI forms are useful for real-world applications like surveys, registration forms, and more.

28
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no: I-15

[11/04/25] 8. Pattern Matching:LO5

Aim:
To write a Python script that validates a user's password using regular expressions based on
specific criteria:
- Minimum 8 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one digit
- At least one special character

THEORY:
Password validation is a common task in security-focused applications. Regular Expressions
(regex) provide a flexible way to define complex string patterns.

In this program, we use Python's built-in `re` module to define a pattern that checks:
- Length: `.{8,}` means at least 8 characters
- Uppercase: `[A-Z]`
- Lowercase: `[a-z]`
- Digit: `[0-9]`
- Special character: `[@$!%*?&]` or any other you define

A password must satisfy all these conditions to be considered valid.

PROGRAM:
import re

def validate_password(password):
length_error = len(password) < 8
uppercase_error = re.search(r"[A-Z]", password) is None
lowercase_error = re.search(r"[a-z]", password) is None

29
digit_error = re.search(r"[0-9]", password) is None
special_char_error = re.search(r"[!@#$%^&*(),.?\":{}|<>]", password) is None

if length_error:
print("Password must be at least 8 characters long.")
if uppercase_error:
print("Password must contain at least one uppercase letter.")
if lowercase_error:
print("Password must contain at least one lowercase letter.")
if digit_error:
print("Password must contain at least one digit.")
if special_char_error:
print("Password must contain at least one special character.")

if not (length_error or uppercase_error or lowercase_error or digit_error or special_char_error):


print("Password is valid.")

user_password = input("Enter your password to validate: ")


validate_password(user_password)

OUTPUT:
Enter your password to validate: Hello123
Password must contain at least one special character.

Enter your password to validate: hello@123


Password must contain at least one uppercase letter.

Enter your password to validate: Hello@123


Password is valid.

CONCLUSION:
The program successfully validates passwords using regular expressions based on length, character
type, and special symbol criteria.
This method is efficient for enforcing strong password policies in real-world applications such as
login systems or user account setups.

30
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no:I-15

[07/03/25] 9. Arrays: LO6

1.
AIM:

To create 1D, 2D, and 3D NumPy arrays and perform basic operations like reshaping, slicing, and
indexing.

THEORY:

- NumPy (Numerical Python) is a powerful library used for numerical computations.

- Arrays in NumPy can be of multiple dimensions: 1D (vector), 2D (matrix), and 3D (tensor).

- Reshaping modifies the shape of an array without changing its data.

- Slicing allows selecting specific portions of an array.

PROGRAM:

import numpy as np

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


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

reshaped_arr = arr_1d.reshape(5, 1)

slice_2d = arr_2d[:, 1] # Extract second column

print("1D Array:", arr_1d)


print("2D Array:", arr_2d)
print("3D Array:", arr_3d)
print("Reshaped 1D to 2D:", reshaped_arr)

31
print("Sliced 2D Array:", slice_2d)

OUTPUT:

1D Array: [1 2 3 4 5]
2D Array: [[1 2 3]
[4 5 6]]
3D Array: [[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Reshaped 1D to 2D: [[1]
[2]
[3]
[4]
[5]]
Sliced 2D Array: [2 5]

CONCLUSION:

Successfully created and manipulated NumPy arrays using reshaping, slicing, and indexing.

32
2.
AIM:

To perform element-wise addition, subtraction, multiplication, and division on NumPy arrays.


Also, to calculate dot product and cross product of vectors.

THEORY:

- Element-wise operations allow performing arithmetic operations between arrays of the same
shape.

- The dot product is a scalar obtained from two equal-length vectors.

- The cross product results in a new vector perpendicular to the input vectors.

PROGRAM:

import numpy as np

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


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

addition = arr1 + arr2


subtraction = arr1 - arr2
multiplication = arr1 * arr2
division = arr1 / arr2

dot_product = np.dot(arr1, arr2)


cross_product = np.cross(arr1, arr2)

print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Dot Product:", dot_product)
print("Cross Product:", cross_product)

33
OUTPUT:

Addition: [5 7 9]
Subtraction: [-3 -3 -3]
Multiplication: [4 10 18]
Division: [0.25 0.4 0.5]
Dot Product: 32
Cross Product: [-3 6 -3]

CONCLUSION:

Successfully implemented element-wise operations and computed dot and cross products using
NumPy.

34
THADOMAL SHAHANI ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

Roll no: I-15

[27/03/25] 10. Pandas and Matplotlib: LO6

1.
Aim:
To analyse the Iris dataset by reading, cleaning, and summarizing its features using Python,
including operations like handling missing values, grouping by species, and computing statistics
such as mean, min, and max of Sepal length.

Theory:
The Iris dataset is a classic dataset in machine learning that contains measurements of sepal length,
sepal width, petal length, and petal width for three species of iris flowers. It is widely used for data
analysis and classification tasks. In this project, the dataset is loaded and the first few rows are
observed. The script also includes steps to handle missing data by either filling with the mean or
removing incomplete rows. Finally, it groups the dataset by species to perform aggregation and
calculates statistical summaries (mean, min, max) of the sepal length, which helps understand
variations across flower species.

This kind of data preprocessing and analysis is an important first step in data science workflows.
Cleaning data and understanding basic statistics allow us to detect patterns, make comparisons,
and prepare the dataset for further modeling or visualization tasks.

Program:
import pandas as pd
df = pd.read_csv('Iris.csv')

print("First 8 rows of the dataset:")

35
print(df.head(8))

print("\nColumn names:")

print(df.columns.tolist())

df_filled = df.copy()

df_filled.fillna(df_filled.mean(numeric_only=True), inplace=True)

print("\nData after filling missing values with mean (if any):")

print(df_filled.head())

df_no_missing = df.dropna()
print("\nData after removing rows with missing values:")

print(df_no_missing.head())

grouped = df.groupby("Species")

print("\nSepalLengthCm statistics (Grouped by Species):")

sepal_stats = grouped['SepalLengthCm'].agg(['mean', 'min', 'max'])

print(sepal_stats)

36
Output:

Conclusion:
The analysis of the Iris dataset using Python provides meaningful insights into the data by cleaning it, grouping it
based on species, and extracting key statistical values. These operations help in better understanding the
structure of the dataset

37
2.
Aim:
To develop a Python program that reads data from a CSV file and utilizes data visualization
techniques using Pandas and Matplotlib to generate various plots such as scatter plots, histograms,
bar charts, pie charts, and box plots for better understanding and presentation of the dataset.

Theory:
This program is based on the concepts of data visualization using Python. Python provides
powerful libraries like Pandas for data handling and Matplotlib for creating visual representations
of data. These tools allow users to explore datasets, identify patterns, and communicate findings
effectively through various types of plots. The program reads a dataset from a CSV file, processes
it, and generates visual outputs like scatter plots, histograms, bar plots, pie charts, and box plots.
These visualizations help in simplifying complex data, making it easier to understand and interpret.
Such programs are widely used in data analysis, reporting, and decision-making across industries.

Program:
import pandas as pd

import matplotlib.pyplot as plt

df = pd.read_csv('Toyota.csv')

plt.figure(figsize=(8,6))

plt.scatter(df['Age'], df['Price'], color='blue', alpha=0.6)

plt.title('Scatter Plot: Age vs Price')

plt.xlabel('Age (months)')

plt.ylabel('Price')

plt.grid(True)

plt.show()

38
plt.figure(figsize=(8,6))

plt.hist(df['KM'], bins=30, color='orange', edgecolor='black')

plt.title('Histogram: Kilometers Driven')

plt.xlabel('KM Driven')

plt.ylabel('Frequency')

plt.grid(True)

plt.show()

fuel_counts = df['FuelType'].value_counts()

plt.figure(figsize=(8,6))

plt.bar(fuel_counts.index, fuel_counts.values, color='skyblue', edgecolor='black')

plt.title('Bar Plot: Fuel Type Distribution')

plt.xlabel('Fuel Type')

plt.ylabel('Count')

plt.grid(axis='y')

plt.show()

plt.figure(figsize=(6,6))

plt.pie(fuel_counts, labels=fuel_counts.index, autopct='%1.1f%%', startangle=140,


colors=['#ff9999','#66b3ff','#99ff99'])

plt.title('Pie Chart: Fuel Type Percentage')

plt.axis('equal')

plt.show()

fuel_types = df['FuelType'].unique()

price_data = [df[df['FuelType'] == ft]['Price'] for ft in fuel_types]

39
plt.figure(figsize=(8,6))

plt.boxplot(price_data, labels=fuel_types)

plt.title('Box Plot: Price by Fuel Type')

plt.xlabel('Fuel Type')

plt.ylabel('Price')

plt.grid(True)

plt.show()

Output:

40
Conclusion:
The program successfully demonstrates the use of Python for data visualization using libraries like
Pandas and Matplotlib. It efficiently loads and processes a real-world dataset and generates various
plots, including scatter plots, histograms, bar charts, pie charts, and box plots. These visualizations
showcase the capability of Python to present data in a meaningful and interpretable way, making
it a powerful tool for data analysis and presentation.

41

You might also like