Python Lab Manual
Python Lab Manual
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}")
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")
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.
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()
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.")
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.")
def generate_multiplication_table():
try:
# Take numerical input from the user
number = int(input("Enter a number to generate its multiplication table: "))
except ValueError:
print("Please enter a valid integer.")
C. Develop a Python program to print the Fibonacci sequence using a while loop.
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 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
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)
import random
def number_guessing_game():
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
while True:
try:
# Ask the user for their guess
user_guess = int(input("Enter your guess: "))
attempts += 1
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()
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 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.
# 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: "))
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.")
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
}
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
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 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)
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 __str__(self):
return f"{self.name} - ${self.price} ({self.stock} in stock)"
class ShoppingCart:
def __init__(self):
self.items = {}
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()
# 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")
# Calculate Total
print(f"Total Cost: ${customer.cart.calculate_total():.2f}")
# Process Order
OrderProcessor.process_order(customer)
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
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 __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 show_available_vehicles(self):
print(f"\nAvailable Vehicles in {self.name}:")
for vehicle in self.vehicles:
if vehicle.available:
print(vehicle)
if not customer:
print("Invalid customer ID.")
return
if not vehicle:
print("Vehicle not available or invalid vehicle ID.")
return
# 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"))
# 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)
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)
# Convert button
tk.Button(self.root, text="Convert", font=("Arial", 12), bg="#4CAF50", fg="white",
command=self.convert).pack(pady=5)
def convert(self):
try:
value = float(self.value_entry.get())
conversion_type = self.conversion_type.get()
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
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))
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
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))
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()
print("\nExtracted Emails:")
for email in emails:
print(email)
print("\nExtracted Dates:")
for date in dates:
print('/'.join(date))
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
# Reshape 1D array to 2D
reshaped = arr_1d.reshape((5, 1))
print("\nReshaped 1D to 2D:\n", reshaped)
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
# Element-wise operations
print("Addition:\n", a + b)
print("\nSubtraction:\n", a - b)
print("\nMultiplication:\n", a * b)
print("\nDivision:\n", a / b)
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