Practical PDF
Practical PDF
# math_operations.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Cannot divide by zero."
# Program using the mathematical operations module
# Import the mathematical operations module
# Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform mathematical operations
sum_result = add(num1, num2)
difference_result = subtract(num1, num2)
product_result = multiply(num1, num2)
division_result = divide(num1, num2)
# Output
print(f"Sum: {sum_result}")
print(f"Difference: {difference_result}")
print(f"Product: {product_result}")
print(f"Division: {division_result}")
OUTPUT:
6 . WRITE A PROGRAM TO READ AND WRITE FILES, CREATE AND DELETE
DIRECTORIES
import os
def read_file():
filename = input("Enter the name of the file to read: ")
try:
with open(filename, 'r') as file:
content = file.read()
print("\nFile content:\n", content)
except FileNotFoundError:
print(f"File '{filename}' not found.")
def write_to_file():
filename = input("Enter the name of the file to write: ")
content = input("Enter the content to write to the file: ")
with open(filename, 'w') as file:
file.write(content)
print(f"Content successfully written to '{filename}'.")
def create_directory():
dirname = input("Enter the name of the directory to create: ")
try:
os.mkdir(dirname)
print(f"Directory '{dirname}' created successfully.")
except FileExistsError:
print(f"Directory '{dirname}' already exists.")
def delete_directory():
dirname = input("Enter the name of the directory to delete: ")
try:
os.rmdir(dirname)
print(f"Directory '{dirname}' deleted successfully.")
except FileNotFoundError:
print(f"Directory '{dirname}' not found.")
except OSError as e:
print(f"Error deleting directory '{dirname}': {e}")
# Sample Input & Output
read_file()
write_to_file()
create_directory()
delete_directory()
OUTPUT:
7 . WRITE A PROGRAM WITH EXCEPTION HANDLING
def perform_division():
try:
# Input
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Division Operation
result = numerator / denominator
# Output
print(f"Result of {numerator} / {denominator} = {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid numbers.")
# Sample Input & Output
perform_division()
OUTPUT:
8. WRITE A PROGRAM USING CLASSES
class Book:
def __init__(self, title, author, publication_year):
self.title = title
self.author = author
self.publication_year = publication_year
def display_info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Publication Year: {self.publication_year}")
print()
# Sample Input & Output
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 1960)
book3 = Book("1984", "George Orwell", 1949)
# Display information about each book
print("Information about Book 1:")
book1.display_info()
print("Information about Book 2:")
book2.display_info()
print("Information about Book 3:")
book3.display_info()
OUTPUT:
9 . CONNECT WITH MYSQL AND CREATE ADDRESS BOOK
import mysql.connector
class AddressBook:
def __init__(self, host, user, password,database):
self.connection = mysql.connector.connect(
host=host,
user=user,
password=password,
database= database
)
self.cursor = self.connection.cursor()
self.create_table()
def create_table(self):
create_table_query = """
CREATE TABLE IF NOT EXISTS contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
phone_number VARCHAR(20)
)
"""
self.cursor.execute(create_table_query)
self.connection.commit()
def display_contacts(self):
select_query = "SELECT * FROM contacts"
self.cursor.execute(select_query)
contacts = self.cursor.fetchall()
print("\nAddress Book:")
for contact in contacts:
print(f"ID: {contact[0]}, Name: {contact[1]}, Email: {contact[2]}, Phone:
{contact[3]}")
print()
def close_connection(self):
self.cursor.close()
self.connection.close()
# Insert contacts
address_book.insert_contact("John Doe", "[email protected]", "123-456-
7890")
address_book.insert_contact("Jane Smith", "[email protected]", "987-654-
3210")
# Display contacts
address_book.display_contacts()
import re
def validate_and_extract_email(input_email):
# Regular expression pattern for a simple email validation
email_pattern = r'^\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
# Check if the input email matches the pattern
match_result = re.match(email_pattern, input_email)
if match_result:
print(f"The email '{input_email}' is valid.")