0% found this document useful (0 votes)
6 views36 pages

Python Lab Manual

The document outlines various Python programming experiments, including calculating areas of geometric figures, converting currencies and temperatures, managing a task list, performing set operations for student enrollments, and handling student records. It also includes programs for checking character types, generating multiplication tables, printing Fibonacci sequences, implementing a calculator, and creating a number guessing game. Each experiment provides code snippets and explanations for the functionality of the programs.

Uploaded by

Chitra Venkatesh
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)
6 views36 pages

Python Lab Manual

The document outlines various Python programming experiments, including calculating areas of geometric figures, converting currencies and temperatures, managing a task list, performing set operations for student enrollments, and handling student records. It also includes programs for checking character types, generating multiplication tables, printing Fibonacci sequences, implementing a calculator, and creating a number guessing game. Each experiment provides code snippets and explanations for the functionality of the programs.

Uploaded by

Chitra Venkatesh
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/ 36

Experiment No: 1

a. Write a python program to calculate areas of any geometric figures like circle, rectangle
and triangle.
import math

def calculate_area():
print("Choose a shape to calculate the area:")
print("1. Circle\n2. Rectangle\n3. Triangle")
choice = int(input("Enter your choice (1/2/3): "))

if choice == 1:
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"Area of the circle: {area:.2f}")
elif choice == 2:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"Area of the rectangle: {area:.2f}")
elif choice == 3:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"Area of the triangle: {area:.2f}")
else:
print("Invalid choice!")

calculate_area()
b. Develop any converter such as Rupees to dollar, temperature convertor, inch to feet
etc.
# Conversion Utilities
def rupees_to_dollars():
rupees = float(input("Enter amount in rupees: "))
dollars = rupees / 74.5 # Example conversion rate
print(f"Equivalent amount in dollars: ${dollars:.2f}")

def celsius_to_fahrenheit():
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"Temperature in Fahrenheit: {fahrenheit:.2f}")

rupees_to_dollars()
celsius_to_fahrenheit()
c. Write a Python program to calculate the gross salary of an employee.
basic_salary = float(input("Enter the basic salary: "))
da = 0.7 * basic_salary # Dearness Allowance
ta = 0.3 * basic_salary # Travel Allowance
hra = 0.1 * basic_salary # House Rent Allowance
gross_salary = basic_salary + da + ta + hra
print(f"Gross Salary: {gross_salary:.2f}")

d. Write a Python program to calculate the simple interest based on user input
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time (in years): "))
simple_interest = (principal * rate * time) / 100
print(f"Simple Interest: {simple_interest:.2f}")

e. Write a Python program to explore basic arithmetic operations.

# Basic Arithmetic Operations


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 'Division by zero error'}")
print(f"Modulus: {num1 % num2}")

Experiment No: 2
a. Develop a Python program to manage a task list using lists and tuples, including
adding, removing, updating, and sorting tasks.

def display_tasks(tasks):
if not tasks:
print("The task list is empty.")
else:
print("\nTask List:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
print()

def add_task(tasks):
task = input("Enter the task to add: ")
tasks.append(task)
print(f"Task '{task}' added successfully!\n")

def remove_task(tasks):
if not tasks:
print("The task list is empty. Nothing to remove.\n")
return
try:
display_tasks(tasks)
task_index = int(input("Enter the task number to remove: ")) - 1
if 0 <= task_index < len(tasks):
removed_task = tasks.pop(task_index)
print(f"Task '{removed_task}' removed successfully!\n")
else:
print("Invalid task number!\n")
except ValueError:
print("Please enter a valid number.\n")

def update_task(tasks):
if not tasks:
print("The task list is empty. Nothing to update.\n")
return
try:
display_tasks(tasks)
task_index = int(input("Enter the task number to update: ")) - 1
if 0 <= task_index < len(tasks):
new_task = input("Enter the new task: ")
old_task = tasks[task_index]
tasks[task_index] = new_task
print(f"Task '{old_task}' updated to '{new_task}' successfully!\n")
else:
print("Invalid task number!\n")
except ValueError:
print("Please enter a valid number.\n")

def sort_tasks(tasks):
if not tasks:
print("The task list is empty. Nothing to sort.\n")
return
tasks.sort()
print("Tasks sorted alphabetically!\n")

def task_manager():
tasks = [] # Using a list to store tasks
while True:
print("Task Manager Menu:")
print("1. Display tasks")
print("2. Add a task")
print("3. Remove a task")
print("4. Update a task")
print("5. Sort tasks")
print("6. Exit")

choice = input("Enter your choice (1-6): ")

if choice == "1":
display_tasks(tasks)
elif choice == "2":
add_task(tasks)
elif choice == "3":
remove_task(tasks)
elif choice == "4":
update_task(tasks)
elif choice == "5":
sort_tasks(tasks)
elif choice == "6":
print("Exiting Task Manager. Goodbye!")
break
else:
print("Invalid choice! Please try again.\n")
task_manager()

b. 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.

# Student Enrollment Manager

def display_set(student_set, name):


print(f"{name}: {', '.join(student_set) if student_set else 'No students enrolled.'}")

def main():
# Sample student enrollment data
cet_students = {"Alice", "Bob", "Charlie", "David"}
jee_students = {"Charlie", "David", "Eve", "Frank"}
neet_students = {"Alice", "Eve", "George", "Hannah"}
print("Student Enrollment Sets:")
display_set(cet_students, "CET Students")
display_set(jee_students, "JEE Students")
display_set(neet_students, "NEET Students")
print()

# Union operation
all_students = cet_students.union(jee_students, neet_students)
print("Union of all enrollments (all unique students):")
display_set(all_students, "All Students")
print()

# Intersection operation
common_cet_jee = cet_students.intersection(jee_students)
print("Intersection of CET and JEE enrollments (common students):")
display_set(common_cet_jee, "Common CET and JEE Students")
print()

# Difference operation
cet_only = cet_students.difference(jee_students, neet_students)
print("Students enrolled only in CET:")
display_set(cet_only, "CET-Only Students")
print()

# Symmetric difference operation (students in exactly one set)


exclusive_students =
cet_students.symmetric_difference(jee_students).symmetric_difference(neet_students)
print("Students enrolled in exactly one exam:")
display_set(exclusive_students, "Exclusive Students")
print()

# Checking if a student is enrolled


student_name = input("Enter the name of a student to check enrollment: ")
if student_name in all_students:
print(f"{student_name} is enrolled in at least one course.")
if student_name in cet_students:
print(f"{student_name} is enrolled in CET.")
if student_name in jee_students:
print(f"{student_name} is enrolled in JEE.")
if student_name in neet_students:
print(f"{student_name} is enrolled in NEET.")
else:
print(f"{student_name} is not enrolled in any course.")
# Run the program
main()

c. Write a Python program to create, update, and manipulate a dictionary of student


records, including their grades and attendance.

# Student Record Keeper

def display_records(records):
if not records:
print("No records available.")
return
print("\nStudent Records:")
for student_id, info in records.items():
print(f"ID: {student_id}, Name: {info['name']}, Grades: {info['grades']}, Attendance:
{info['attendance']}%")
print()

def add_record(records):
student_id = input("Enter Student ID: ")
if student_id in records:
print("Student ID already exists. Use update option instead.")
return
name = input("Enter Student Name: ")
grades = input("Enter Grades (comma-separated, e.g., 85,90,78): ")
attendance = float(input("Enter Attendance Percentage: "))
records[student_id] = {
"name": name,
"grades": [int(g) for g in grades.split(",")],
"attendance": attendance,
}
print("Record added successfully!")

def update_record(records):
student_id = input("Enter Student ID to update: ")
if student_id not in records:
print("Student ID not found.")
return
print("What would you like to update?")
print("1. Name\n2. Grades\n3. Attendance")
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
records[student_id]["name"] = input("Enter new name: ")
elif choice == 2:
grades = input("Enter new grades (comma-separated): ")
records[student_id]["grades"] = [int(g) for g in grades.split(",")]
elif choice == 3:
records[student_id]["attendance"] = float(input("Enter new attendance percentage: "))
else:
print("Invalid choice.")
print("Record updated successfully!")

def delete_record(records):
student_id = input("Enter Student ID to delete: ")
if student_id in records:
del records[student_id]
print("Record deleted successfully!")
else:
print("Student ID not found.")

def calculate_average_grade(records):
student_id = input("Enter Student ID to calculate average grade: ")
if student_id not in records:
print("Student ID not found.")
return
grades = records[student_id]["grades"]
average = sum(grades) / len(grades) if grades else 0
print(f"Average grade for {records[student_id]['name']}: {average:.2f}")

def main():
student_records = {}
while True:
print("\nStudent Record Keeper")
print("1. Display Records")
print("2. Add Record")
print("3. Update Record")
print("4. Delete Record")
print("5. Calculate Average Grade")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
display_records(student_records)
elif choice == 2:
add_record(student_records)
elif choice == 3:
update_record(student_records)
elif choice == 4:
delete_record(student_records)
elif choice == 5:
calculate_average_grade(student_records)
elif choice == 6:
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

# Run the program


main()

Experiment No: 3

a. Create a Python program to check whether the given input is a digit, lowercase
character, uppercase character, or a special character using an 'ifelse-if' ladder.

def check_character_type(char):
if char.isdigit():
print("The input is a digit.")
elif char.islower():
print("The input is a lowercase character.")
elif char.isupper():
print("The input is an uppercase character.")
else:
print("The input is a special character.")

# Input from the user


user_input = input("Enter a single character: ")

# Validate if input is a single character


if len(user_input) == 1:
check_character_type(user_input)
else:
print("Please enter only one character.")
B. Write a Python program to take a numerical input from the user and generate
its multiplication table using loops.

def generate_multiplication_table():
try:
# Take numerical input from the user
number = int(input("Enter a number to generate its multiplication table: "))

# Generate and display the multiplication table


print(f"\nMultiplication Table for {number}:\n")
for i in range(1, 11): # Loop through numbers 1 to 10
print(f"{number} x {i} = {number * i}")

except ValueError:
print("Please enter a valid integer.")

# Run the function


generate_multiplication_table()

C. Develop a Python program to print the Fibonacci sequence using a while loop.

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


a, b = 0, 1
count = 0

if num_terms <= 0:
print("Please enter a positive integer.")
elif num_terms == 1:
print(f"Fibonacci sequence up to {num_terms} term: {a}")
else:
print(f"Fibonacci sequence up to {num_terms} terms:")
while count < num_terms:
print(a, end=" ")
# Update values
a, b = b, a + b
count += 1

D. Implement a simple Python calculator that takes user input and performs basic
arithmetic operations (addition, subtraction, multiplication, division) using
functions.

def add(a, b):


return a + b
def subtract(a, b):
return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b == 0:
return "Error: Division by zero is not allowed."
return a / b

def calculator():
print("Welcome to the simple calculator!")
print("Available operations: add, subtract, multiply, divide")

while True:
operation = input("Enter operation (or 'exit' to quit): ").strip().lower()

if operation == "exit":
print("Exiting the calculator. Goodbye!")
break

if operation not in ["add", "subtract", "multiply", "divide"]:


print("Invalid operation. Please try again.")
continue

try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ValueError:
print("Invalid input. Please enter numeric values.")
continue

if operation == "add":
result = add(num1, num2)
elif operation == "subtract":
result = subtract(num1, num2)
elif operation == "multiply":
result = multiply(num1, num2)
elif operation == "divide":
result = divide(num1, num2)

print(f"The result is: {result}")


if __name__ == "__main__":
calculator()

E. 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.

import random

def number_guessing_game():
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")

# Generate a random number between 1 and 100


random_number = random.randint(1, 100)

# Initialize the number of attempts


attempts = 0

while True:
try:
# Ask the user for their guess
user_guess = int(input("Enter your guess: "))
attempts += 1

# Check if the guess is correct


if user_guess == random_number:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif user_guess < random_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")
except ValueError:
print("Invalid input. Please enter an integer.")

if __name__ == "__main__":
number_guessing_game()
Experiment No: 4
A.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.

import re
def find_words_by_length(file_name, lengths):
try:
with open(file_name, 'r') as file:
content = file.read()

# Use regex to split words and remove punctuation


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

# Filter words by specified lengths


words_by_length = {length: [] for length in lengths}
for word in words:
word_length = len(word)
if word_length in lengths:
words_by_length[word_length].append(word)

# Print the results


for length in lengths:
print(f"\nWords of length {length}:")
print(", ".join(words_by_length[length]) if words_by_length[length] else "No words
found.")
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
file_name = input("Enter the name of the text file (with extension): ")
try:
lengths = input("Enter the word lengths to search for (comma-separated): ")
lengths = [int(length.strip()) for length in lengths.split(",")]
find_words_by_length(file_name, lengths)
except ValueError:
print("Invalid input. Please enter valid integers for word lengths.")
B. Write a python code to take a csv file as input with coordinates of points in three
dimensions. Find out the two closest points

import csv
import math
from itertools import combinations

def read_csv(file_path):
"""Reads the CSV file and returns a list of points."""
points = []
with open(file_path, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
points.append((float(row['x']), float(row['y']), float(row['z'])))
return points

def calculate_distance(point1, point2):


"""Calculates the Euclidean distance between two 3D points."""
return math.sqrt(
(point1[0] - point2[0]) ** 2 +
(point1[1] - point2[1]) ** 2 +
(point1[2] - point2[2]) ** 2
)

def find_closest_points(points):
"""Finds the two closest points in the list."""
min_distance = float('inf')
closest_pair = None
for point1, point2 in combinations(points, 2):
distance = calculate_distance(point1, point2)
if distance < min_distance:
min_distance = distance
closest_pair = (point1, point2)
return closest_pair, min_distance

def main():
# Provide the path to your CSV file
file_path = 'points.csv' # Replace with your file path
points = read_csv(file_path)
if len(points) < 2:
print("Not enough points to find the closest pair.")
return
closest_pair, distance = find_closest_points(points)
print(f"The closest points are: {closest_pair}")
print(f"The distance between them is: {distance:.4f}")

if __name__ == '__main__':
main()

C. 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.

def sort_city_names(input_file, output_file):


try:
# Read city names from the input file
with open(input_file, 'r') as file:
city_names = file.readlines()

# Strip whitespace and sort the city names alphabetically


city_names = [city.strip() for city in city_names]
city_names.sort()

# Write the sorted city names to the output file


with open(output_file, 'w') as file:
for city in city_names:
file.write(city + '\n')

print(f"City names sorted and written to {output_file}")


except FileNotFoundError:
print(f"Error: The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")

# Example usage
input_file = "cities.txt" # Replace with your input file name
output_file = "sorted_cities.txt" # Replace with your output file name
sort_city_names(input_file, output_file)
Experiment No: 5

A. 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.

def divide_numbers():
try:
# Take two inputs from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform the division


result = num1 / num2

except ValueError:
# Handle invalid input (e.g., non-numeric values)
print("Invalid input! Please enter numeric values.")

except ZeroDivisionError:
# Handle division by zero
print("Division by zero is not allowed. Please enter a non-zero divisor.")

else:
# Print the result if no exceptions occur
print(f"The result of the division is: {result}")

finally:
# Inform the user that the program has finished
print("Thank you for using the division program.")

# Call the function


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

class InsufficientFundsException(Exception):
def __init__(self, message="Insufficient funds in the account"):
self.message = message
super().__init__(self.message)

class InvalidAccountException(Exception):
def __init__(self, message="Invalid account number"):
self.message = message
super().__init__(self.message)

class Bank:
def __init__(self):
self.accounts = {
"12345": 5000.0,
"67890": 3000.0,
"11121": 7000.0
}

def withdraw(self, account_number, amount):


if account_number not in self.accounts:
raise InvalidAccountException(f"Account {account_number} does not exist.")

if self.accounts[account_number] < amount:


raise InsufficientFundsException(f"Account {account_number} has insufficient funds.")

self.accounts[account_number] -= amount
return f"Withdrawal successful. New balance: {self.accounts[account_number]}"

# Example usage
if __name__ == "__main__":
bank = Bank()
try:
acc_num = input("Enter account number: ")
amount = float(input("Enter amount to withdraw: "))
print(bank.withdraw(acc_num, amount))
except (InsufficientFundsException, InvalidAccountException) as e:
print(f"Error: {e}")
except ValueError:
print("Invalid input. Please enter a numeric value for the amount.")
Experiment No: 6

a. 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.

class Person:
"""Base class for all people involved in the event."""
def __init__(self, name, contact):
self.name = name
self.contact = contact

def display_details(self):
return f"Name: {self.name}, Contact: {self.contact}"

class Organizer(Person):
"""Class representing an organizer of the event."""
def __init__(self, name, contact, role):
super().__init__(name, contact)
self.role = role

def display_details(self):
return f"Organizer - {super().display_details()}, Role: {self.role}"

class Participant(Person):
"""Class representing a participant in the event."""
def __init__(self, name, contact, reg_id):
super().__init__(name, contact)
self.reg_id = reg_id

def display_details(self):
return f"Participant - {super().display_details()}, Registration ID: {self.reg_id}"

class Activity:
"""Class representing an activity in the event."""
def __init__(self, name, time, venue):
self.name = name
self.time = time
self.venue = venue

def display_details(self):
return f"Activity: {self.name}, Time: {self.time}, Venue: {self.venue}"

class Event:
"""Class representing an event."""
def __init__(self, name, date):
self.name = name
self.date = date
self.organizers = []
self.participants = []
self.activities = []

def add_organizer(self, organizer):


if isinstance(organizer, Organizer):
self.organizers.append(organizer)
else:
raise TypeError("Only instances of Organizer can be added.")

def add_participant(self, participant):


if isinstance(participant, Participant):
self.participants.append(participant)
else:
raise TypeError("Only instances of Participant can be added.")

def add_activity(self, activity):


if isinstance(activity, Activity):
self.activities.append(activity)
else:
raise TypeError("Only instances of Activity can be added.")

def display_event_details(self):
print(f"Event: {self.name}, Date: {self.date}\n")
print("Organizers:")
for organizer in self.organizers:
print(organizer.display_details())
print("\nParticipants:")
for participant in self.participants:
print(participant.display_details())
print("\nActivities:")
for activity in self.activities:
print(activity.display_details())

# Example Usage
if __name__ == "__main__":
# Create Event
college_fest = Event("TechFest", "2025-03-15")

# Add Organizers
organizer1 = Organizer("Alice", "123-456-7890", "Coordinator")
organizer2 = Organizer("Bob", "987-654-3210", "Logistics")
college_fest.add_organizer(organizer1)
college_fest.add_organizer(organizer2)

# Add Participants
participant1 = Participant("Charlie", "555-666-7777", "P1001")
participant2 = Participant("Diana", "444-555-8888", "P1002")
college_fest.add_participant(participant1)
college_fest.add_participant(participant2)

# Add Activities
activity1 = Activity("Coding Competition", "10:00 AM", "Auditorium")
activity2 = Activity("Robotics Workshop", "02:00 PM", "Lab 3")
college_fest.add_activity(activity1)
college_fest.add_activity(activity2)

# Display Event Details


college_fest.display_event_details()

b. 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.

Code:
class Product:
def __init__(self, product_id, name, price, stock):
self.product_id = product_id
self.name = name
self.price = price
self.stock = stock

def update_stock(self, quantity):


if quantity <= self.stock:
self.stock -= quantity
return True
else:
return False

def __str__(self):
return f"{self.name} - ${self.price} ({self.stock} in stock)"

class ShoppingCart:
def __init__(self):
self.items = {}

def add_product(self, product, quantity):


if product.product_id in self.items:
self.items[product.product_id]['quantity'] += quantity
else:
self.items[product.product_id] = {'product': product, 'quantity': quantity}
print(f"Added {quantity} x {product.name} to cart.")

def remove_product(self, product_id):


if product_id in self.items:
removed = self.items.pop(product_id)
print(f"Removed {removed['product'].name} from cart.")
else:
print("Product not in cart.")

def calculate_total(self):
total = sum(item['product'].price * item['quantity'] for item in self.items.values())
return total

def list_items(self):
if not self.items:
print("Cart is empty.")
return
print("Items in cart:")
for item in self.items.values():
print(f"{item['quantity']} x {item['product'].name} - ${item['product'].price} each")
def clear_cart(self):
self.items = {}

class Customer:
def __init__(self, customer_id, name):
self.customer_id = customer_id
self.name = name
self.cart = ShoppingCart()

def __str__(self):
return f"Customer {self.name} (ID: {self.customer_id})"

class OrderProcessor:
@staticmethod
def process_order(customer):
if not customer.cart.items:
print("Cart is empty. Cannot process order.")
return False

total_cost = customer.cart.calculate_total()

# Check product availability


for item in customer.cart.items.values():
product = item['product']
quantity = item['quantity']
if product.stock < quantity:
print(f"Insufficient stock for {product.name}.")
return False

# Deduct stock and confirm order


for item in customer.cart.items.values():
product = item['product']
quantity = item['quantity']
product.update_stock(quantity)

print(f"Order processed for {customer.name}. Total cost: ${total_cost:.2f}")


customer.cart.clear_cart()
return True

# Example Usage
if __name__ == "__main__":
# Create Products
product1 = Product(1, "Laptop", 1000, 10)
product2 = Product(2, "Mouse", 50, 100)
product3 = Product(3, "Keyboard", 80, 50)

# Create Customer
customer = Customer(101, "John Doe")

# Add Products to Cart


customer.cart.add_product(product1, 1)
customer.cart.add_product(product2, 2)
customer.cart.list_items()

# Calculate Total
print(f"Total Cost: ${customer.cart.calculate_total():.2f}")

# Process Order
OrderProcessor.process_order(customer)

# Check Stock After Order


print("\nProduct Stock After Order:")
print(product1)
print(product2)
print(product3)

c. 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

from datetime import datetime, timedelta


class Vehicle:
def __init__(self, vehicle_id, make, model, year, price_per_day, available=True):
self.vehicle_id = vehicle_id
self.make = make
self.model = model
self.year = year
self.price_per_day = price_per_day
self.available = available

def __str__(self):
status = "Available" if self.available else "Not Available"
return f"{self.year} {self.make} {self.model} - ₹{self.price_per_day}/day - {status}"
class Customer:
def __init__(self, customer_id, name, phone):
self.customer_id = customer_id
self.name = name
self.phone = phone
self.rental_history = []

def add_rental(self, rental):


self.rental_history.append(rental)

def __str__(self):
return f"{self.name} ({self.phone})"

class RentalTransaction:
def __init__(self, customer, vehicle, start_date, end_date):
self.customer = customer
self.vehicle = vehicle
self.start_date = start_date
self.end_date = end_date
self.total_cost = self.calculate_cost()

def calculate_cost(self):
days = (self.end_date - self.start_date).days + 1
return days * self.vehicle.price_per_day

def complete_transaction(self):
self.vehicle.available = True

def __str__(self):
return (f"Rental Transaction: {self.customer.name} rented {self.vehicle.make}
{self.vehicle.model} "
f"from {self.start_date} to {self.end_date} for ₹{self.total_cost}")

class RentalAgency:
def __init__(self, name):
self.name = name
self.vehicles = []
self.customers = []
self.transactions = []

def add_vehicle(self, vehicle):


self.vehicles.append(vehicle)

def add_customer(self, customer):


self.customers.append(customer)

def show_available_vehicles(self):
print(f"\nAvailable Vehicles in {self.name}:")
for vehicle in self.vehicles:
if vehicle.available:
print(vehicle)

def rent_vehicle(self, customer_id, vehicle_id, start_date, end_date):


customer = next((c for c in self.customers if c.customer_id == customer_id), None)
vehicle = next((v for v in self.vehicles if v.vehicle_id == vehicle_id and v.available), None)

if not customer:
print("Invalid customer ID.")
return
if not vehicle:
print("Vehicle not available or invalid vehicle ID.")
return

rental = RentalTransaction(customer, vehicle, start_date, end_date)


vehicle.available = False
self.transactions.append(rental)
customer.add_rental(rental)
print(f"\nBooking Successful!\n{rental}")

def show_rental_history(self, customer_id):


customer = next((c for c in self.customers if c.customer_id == customer_id), None)
if not customer:
print("Invalid customer ID.")
return

print(f"\nRental History for {customer.name}:")


for rental in customer.rental_history:
print(rental)

# ====== MAIN PROGRAM ======


if __name__ == "__main__":
agency = RentalAgency("Speedy Rentals")

# Add vehicles
agency.add_vehicle(Vehicle(1, "Toyota", "Camry", 2020, 1500))
agency.add_vehicle(Vehicle(2, "Honda", "Civic", 2019, 1200))
agency.add_vehicle(Vehicle(3, "Ford", "Mustang", 2022, 3000))
# Add customers
agency.add_customer(Customer(1, "John Doe", "9876543210"))
agency.add_customer(Customer(2, "Jane Smith", "9123456789"))

# Display available vehicles


agency.show_available_vehicles()

# Rent a vehicle
start_date = datetime.strptime("2025-03-15", "%Y-%m-%d")
end_date = datetime.strptime("2025-03-18", "%Y-%m-%d")
agency.rent_vehicle(1, 1, start_date, end_date)

# Show available vehicles after rental


agency.show_available_vehicles()

# Show rental history for a customer


agency.show_rental_history(1)

Experiment No: 7

a. 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 messagebox

class ConversionApp:
def __init__(self, root):
self.root = root
self.root.title("Unit Conversion Utility")
self.root.geometry("400x250")
self.root.configure(bg="#f0f0f0")

self.create_widgets()

def create_widgets(self):
# Label and Entry for input value
tk.Label(self.root, text="Enter Value:", bg="#f0f0f0", font=("Arial", 12)).pack(pady=5)
self.value_entry = tk.Entry(self.root, font=("Arial", 12), width=20)
self.value_entry.pack(pady=5)

# Dropdown for conversion type


self.conversion_type = tk.StringVar()
self.conversion_type.set("Select Conversion Type")
options = ["Rupees to Dollars", "Celsius to Fahrenheit", "Inches to Feet"]
tk.OptionMenu(self.root, self.conversion_type, *options).pack(pady=5)

# Convert button
tk.Button(self.root, text="Convert", font=("Arial", 12), bg="#4CAF50", fg="white",
command=self.convert).pack(pady=5)

# Label to display result


self.result_label = tk.Label(self.root, text="", font=("Arial", 14), bg="#f0f0f0", fg="#333")
self.result_label.pack(pady=10)

def convert(self):
try:
value = float(self.value_entry.get())
conversion_type = self.conversion_type.get()

if conversion_type == "Rupees to Dollars":


result = value * 0.012 # Example rate: 1 Rupee = 0.012 USD
self.result_label.config(text=f"{value} Rupees = {result:.2f} Dollars")
elif conversion_type == "Celsius to Fahrenheit":
result = (value * 9/5) + 32
self.result_label.config(text=f"{value}°C = {result:.2f}°F")
elif conversion_type == "Inches to Feet":
result = value / 12
self.result_label.config(text=f"{value} Inches = {result:.2f} Feet")
else:
messagebox.showwarning("Invalid Selection", "Please select a valid conversion
type")

except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid numeric value")

if __name__ == "__main__":
root = tk.Tk()
app = ConversionApp(root)
root.mainloop()
b. 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 messagebox
import math

# Function to calculate the area of a circle


def calculate_circle_area():
try:
radius = float(circle_radius_entry.get())
area = math.pi * radius ** 2
circle_result_label.config(text=f"Area: {area:.2f}")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid number for radius.")

# Function to calculate the area of a rectangle


def calculate_rectangle_area():
try:
length = float(rect_length_entry.get())
width = float(rect_width_entry.get())
area = length * width
rectangle_result_label.config(text=f"Area: {area:.2f}")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter valid numbers for length and width.")

# Function to calculate the area of a triangle


def calculate_triangle_area():
try:
base = float(tri_base_entry.get())
height = float(tri_height_entry.get())
area = 0.5 * base * height
triangle_result_label.config(text=f"Area: {area:.2f}")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter valid numbers for base and height.")

# Create main window


root = tk.Tk()
root.title("Geometric Area Calculator")
root.geometry("400x300")
root.configure(bg="#f0f0f0")

# ================= Circle Area =================


circle_frame = tk.Frame(root, bg="#d3d3d3", padx=10, pady=10)
circle_frame.pack(pady=5, fill="x")

tk.Label(circle_frame, text="Circle Radius:", bg="#d3d3d3").pack(side="left")


circle_radius_entry = tk.Entry(circle_frame)
circle_radius_entry.pack(side="left", padx=5)

circle_btn = tk.Button(circle_frame, text="Calculate", command=calculate_circle_area)


circle_btn.pack(side="left", padx=5)

circle_result_label = tk.Label(circle_frame, text="Area: -", bg="#d3d3d3")


circle_result_label.pack(side="left", padx=5)

# ================= Rectangle Area =================


rectangle_frame = tk.Frame(root, bg="#d3d3d3", padx=10, pady=10)
rectangle_frame.pack(pady=5, fill="x")

tk.Label(rectangle_frame, text="Length:", bg="#d3d3d3").pack(side="left")


rect_length_entry = tk.Entry(rectangle_frame)
rect_length_entry.pack(side="left", padx=5)

tk.Label(rectangle_frame, text="Width:", bg="#d3d3d3").pack(side="left")


rect_width_entry = tk.Entry(rectangle_frame)
rect_width_entry.pack(side="left", padx=5)

rect_btn = tk.Button(rectangle_frame, text="Calculate", command=calculate_rectangle_area)


rect_btn.pack(side="left", padx=5)

rectangle_result_label = tk.Label(rectangle_frame, text="Area: -", bg="#d3d3d3")


rectangle_result_label.pack(side="left", padx=5)

# ================= Triangle Area =================


triangle_frame = tk.Frame(root, bg="#d3d3d3", padx=10, pady=10)
triangle_frame.pack(pady=5, fill="x")

tk.Label(triangle_frame, text="Base:", bg="#d3d3d3").pack(side="left")


tri_base_entry = tk.Entry(triangle_frame)
tri_base_entry.pack(side="left", padx=5)
tk.Label(triangle_frame, text="Height:", bg="#d3d3d3").pack(side="left")
tri_height_entry = tk.Entry(triangle_frame)
tri_height_entry.pack(side="left", padx=5)

tri_btn = tk.Button(triangle_frame, text="Calculate", command=calculate_triangle_area)


tri_btn.pack(side="left", padx=5)

triangle_result_label = tk.Label(triangle_frame, text="Area: -", bg="#d3d3d3")


triangle_result_label.pack(side="left", padx=5)

# Start the application loop


root.mainloop()

Experiment No: 8

a. 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

import re

def validate_phone(phone):
pattern = r'^(\+\d{1,3})?\d{10}$'
return bool(re.match(pattern, phone))

def validate_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return bool(re.match(pattern, email))

phone = input("Enter phone number: ")


email = input("Enter email ID: ")

if validate_phone(phone):
print(" Valid phone number")
else:
print(" Invalid phone number")

if validate_email(email):
print(" Valid email ID")
else:
print(" Invalid email ID")
b. 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.

import re

def check_password_strength(password):
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=!]).{8,}$'
if re.match(pattern, password):
return True
return False

password = input("Enter password: ")

if check_password_strength(password):
print(" Strong password")
else:
print(" Weak password. Ensure it meets the strength criteria.")

c. 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.

import re

def validate_url(url):
pattern = r'^(https?://)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}(/.*)?$'
return bool(re.match(pattern, url))

url = input("Enter URL: ")


if validate_url(url):
print(" Valid URL")
else:
print(" Invalid URL")

d. 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 02 171 types of data, such as email addresses, phone numbers,
dates (e.g., MM/DD/YYYY format).

import re

def extract_data(filename):
with open(filename, 'r') as file:
content = file.read()

emails = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', content)


phone_numbers = re.findall(r'\+?\d{10,12}', content)
dates = re.findall(r'\b(0[1-9]|1[0-2])/(0[1-9]|[12]\d|3[01])/\d{4}\b', content)

print("\nExtracted Emails:")
for email in emails:
print(email)

print("\nExtracted Phone Numbers:")


for phone in phone_numbers:
print(phone)

print("\nExtracted Dates:")
for date in dates:
print('/'.join(date))

# Ensure you create a 'data.txt' file before running this code


extract_data('data.txt')

Experiment No: 9
a. 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.
import numpy as np

# Create 1D, 2D, and 3D arrays


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]]])

print("1D Array:\n", arr_1d)


print("\n2D Array:\n", arr_2d)
print("\n3D Array:\n", arr_3d)

# Reshape 1D array to 2D
reshaped = arr_1d.reshape((5, 1))
print("\nReshaped 1D to 2D:\n", reshaped)

# Slicing and Indexing


print("\nSlicing 2D Array (First row):\n", arr_2d[0, :])
print("\nIndexing 3D Array (Element at [1][0][1]):\n", arr_3d[1][0][1])

b. 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.

import numpy as np

# Create two arrays of the same shape


a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])

# Element-wise operations
print("Addition:\n", a + b)
print("\nSubtraction:\n", a - b)
print("\nMultiplication:\n", a * b)
print("\nDivision:\n", a / b)

# Dot product (for 2D arrays)


dot_product = np.dot(a, b.T)
print("\nDot Product:\n", dot_product)

# Cross product (for 1D vectors)


vec1 = np.array([1, 2, 3])
vec2 = np.array([4, 5, 6])
cross_product = np.cross(vec1, vec2)
print("\nCross Product:\n", cross_product)

c. Statistical Operations*: Write a Python program to calculate mean, median,


standard deviation, variance, and correlation coefficients of a given array.

import numpy as np

# Create an array
data = np.array([10, 20, 30, 40, 50, 60])

# Mean
mean = np.mean(data)
# Median
median = np.median(data)
# Standard Deviation
std_dev = np.std(data)
# Variance
variance = np.var(data)
# Correlation Coefficient
correlation = np.corrcoef(data, data * 2) # Example correlation with another array

print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std_dev)
print("Variance:", variance)
print("Correlation Coefficient:\n", correlation)
Experiment No: 10

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

# Load the dataset


file_path = '/content/Toyota.csv' # Replace with the actual file path
df = pd.read_csv(file_path)

# Display basic information about the dataset


print(df.info())
print(df.head())

#Task i: Scatter plot between Age and Price


plt.figure(figsize=(8, 5))
sns.scatterplot(x='Age', y='Price', data=df)
plt.title('Scatter Plot of Age vs Price of Cars')
plt.xlabel('Age of Car (in years)')
plt.ylabel('Price of Car')
plt.show()

# Task ii: Histogram for kilometers driven


plt.figure(figsize=(8, 5))
# The column name is likely 'KM' instead of 'Kilometers'
sns.histplot(df['KM'], bins=20, kde=True)
plt.title('Histogram of Kilometers Driven')
plt.xlabel('Kilometers Driven')
plt.ylabel('Frequency')
plt.show()

# Task iii: Bar plot for fuel type distribution


plt.figure(figsize=(8, 5))
sns.countplot(x='Fuel_Type', data=df)
plt.title('Bar Plot of Cars by Fuel Type')
plt.xlabel('Fuel Type')
plt.ylabel('Number of Cars')
plt.show()

# Task iv: Pie chart for fuel type distribution


fuel_type_counts = df['Fuel_Type'].value_counts()
plt.figure(figsize=(6, 6))
plt.pie(fuel_type_counts, labels=fuel_type_counts.index, autopct='%1.1f%%', startangle=140)
plt.title('Percentage Distribution of Cars by Fuel Type')
plt.show()

# Task v: Box plot for price distribution across fuel types


plt.figure(figsize=(8, 5))
sns.boxplot(x='Fuel_Type', y='Price', data=df)
plt.title('Box Plot of Car Prices by Fuel Type')
plt.xlabel('Fuel Type')
plt.ylabel('Price of Car')
plt.show()

You might also like