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

Practical PDF

The document provides code snippets for 10 programming tasks including: 1) Creating a simple calculator program 2) Using control flow tools like if statements 3) Using for loops 4) Using lists as stacks and queues 5) Creating modules for mathematical operations 6) Reading and writing files and creating/deleting directories 7) Exception handling 8) Using classes to represent books 9) Connecting to a MySQL database to create an address book 10) Validating emails and extracting information using regular expressions

Uploaded by

sivamahen143
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Practical PDF

The document provides code snippets for 10 programming tasks including: 1) Creating a simple calculator program 2) Using control flow tools like if statements 3) Using for loops 4) Using lists as stacks and queues 5) Creating modules for mathematical operations 6) Reading and writing files and creating/deleting directories 7) Exception handling 8) Using classes to represent books 9) Connecting to a MySQL database to create an address book 10) Validating emails and extracting information using regular expressions

Uploaded by

sivamahen143
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1.

CREATE A SIMPLE CALCULATOR TO DO ALL THE ARITHMETIC


OPERATIONS

# Simple Calculator Program


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."
def calculator():
print("Simple Calculator")
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter choice (1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
operator = "+"
elif choice == '2':
result = subtract(num1, num2)
operator = "-"
elif choice == '3':
result = multiply(num1, num2)
operator = "*"
elif choice == '4':
result = divide(num1, num2)
operator = "/"
print(f"{num1} {operator} {num2} = {result}")
else:
print("Invalid input. Please enter a valid operation (1/2/3/4).")
if __name__ == "__main__":
calculator()
OUTPUT:
2. WRITE A PROGRAM TO USE CONTROL FLOW TOOLS LIKE IF

number = float(input("Enter a number: "))


if number > 0:
print(f"{number} is a positive number.")
elif number < 0:
print(f"{number} is a negative number.")
else:
print("The number is zero.")
OUTPUT:
3. WRITE A PROGRAM TO USE FOR LOOP

n = int(input("Enter the value of n: "))


# Sum calculation using for loop
sum_of_numbers = 0
for i in range(1, n + 1):
sum_of_numbers += i
print(f"The sum of the first {n} natural numbers is: {sum_of_numbers}")
OUTPUT:
DATA STRUCTURES
4. (A). USE LIST AS STACK

# Using list as a stack


# Initialize an empty list as a stack
stack = []
# Push elements onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
# Pop elements from the top of the stack
popped_element = stack.pop()
# Output
print("Stack:", stack)
print("Popped Element:", popped_element)
OUTPUT:
DATA STRUCTURES
(B). USE LIST AS QUEUE

# Using list as a queue


# Initialize an empty list as a queue
queue = []
# Enqueue elements
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue elements
dequeued_element = queue.pop(0)
# Output
print("Queue:", queue)
print("Dequeued Element:", dequeued_element)
OUTPUT:
DATA STRUCTURES
(C). TUPLE, SEQUENCE

# Using tuple as a sequence


# Initialize a tuple
my_tuple = (1, 2, 3, 4, 5)
# Access elements using indexing
element_at_index_2 = my_tuple[2]
# Iterate through the tuple
for element in my_tuple:
print(element)
# Output
print("Element at index 2:", element_at_index_2)
OUTPUT:
5 . CREATE NEW MODULE FOR MATHEMATICAL OPERATIONS AND USE IN
YOUR PROGRAM

# 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 insert_contact(self, name, email, phone_number):


insert_query = "INSERT INTO contacts (name, email, phone_number) VALUES
(%s, %s, %s)"
contact_data = (name, email, phone_number)
self.cursor.execute(insert_query, contact_data)
self.connection.commit()
print("Contact added successfully.")

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

# Sample Input & Output


address_book = AddressBook(
host="localhost",
user="root",
password="srini@12345",
database="AddressBook"
)

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

# Close the connection


address_book.close_connection()
OUTPUT:
10. WRITE A PROGRAM USING STRING HANDLING AND REGULAR
EXPRESSIONS

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

# Extract information from the email using regular expressions


extracted_info = re.findall(r'([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+)\.([A-Z|a-
z]{2,})', input_email)

# Display extracted information


print("Username:", extracted_info[0][0])
print("Domain:", extracted_info[0][1])
print("Top-level Domain:", extracted_info[0][2])
else:
print(f"The email '{input_email}' is not valid.")
# Sample Input & Output
input_email = input("Enter an email address: ")
validate_and_extract_email(input_email)
OUTPUT:

You might also like