Program Code:
# Simple Calculator Program in Python
# Function to perform addition
def add(x, y):
return x + y
# Function to perform subtraction def
subtract(x, y):
return x - y
# Function to perform multiplication def
multiply(x, y):
return x * y
# Function to perform division def
divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
# Function to display the menu and take user input for the operation
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Take user input for operation choice
choice = input("Enter choice (1/2/3/4): ")
# Take user input for two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Perform the selected operation
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}") elif
choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input!")
# Loop to allow multiple calculations
while True: calculator()
# Ask if the user wants to perform another operation
another_calculation = input("Do you want to perform another calculation?
(yes/no): ").lower()
if another_calculation != 'yes':
print("Exiting the calculator. Goodbye!")
break
def add(x, y):
return x + y
# Function to perform subtraction def
subtract(x, y):
return x - y
# Function to perform multiplication def
multiply(x, y):
return x * y
# Function to perform division def
divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
# Function to display the menu and take user input for the operation
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Take user input for operation choice
choice = input("Enter choice (1/2/3/4): ")
# Take user input for two numbers num1 =
float(input("Enter first number: ")) num2 =
float(input("Enter second number: "))
# Perform the selected operation if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}") elif
choice == '2': print(f"{num1} - {num2} =
{subtract(num1, num2)}") elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input!")
# Loop to allow multiple calculations
while True:
calculator()
# Ask if the user wants to perform another operation
another_calculation = input("Do you want to perform another calculation?
(yes/no): ").lower()
if another_calculation != 'yes':
print("Exiting the calculator. Goodbye!")
break
OUTPUT:
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 5
Enter second number: 3
5.0 + 3.0 = 8.0
Do you want to perform another calculation? (yes/no): yes
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 4
Enter first number: 5
Enter second number: 0
5.0 / 0.0 = Error! Division by zero.
Do you want to perform another calculation? (yes/no): no Exiting
the calculator. Goodbye!
Program Code:
def check_number(): #
Take input from the user
number = float(input("Enter a number: "))
# Check if the number is positive, negative, or zero using if-elif-else
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
# Function to check if a word is in a list def
check_word_in_list():
words = ['apple', 'banana', 'cherry', 'orange']
# Take input from the user for a word to search in the list
word = input("Enter a word to check if it is in the list (apple, banana, cherry,
orange): ").lower()
# Check if the word is in the list if word
in words:
print(f"The word '{word}' is in the list.")
else:
print(f"The word '{word}' is not in the list.")
# Main program that calls the functions print("Control
flow demonstration:")
print("1. Check if the number is positive, negative, or zero") print("2.
Check if a word is in the list")
choice = input("Choose an option (1/2): ")
if choice == '1':
check_number() elif
choice == '2':
check_word_in_list() else:
print("Invalid choice! Please select 1 or 2.")
OUTPUT:
Control flow demonstration:
1. Check if the number is positive, negative, or zero
2. Check if a word is in the list
Choose an option (1/2): 1
Enter a number: 5 The
number is positive.
Control flow demonstration:
1. Check if the number is positive, negative, or zero
2. Check if a word is in the list
Choose an option (1/2): 2
Enter a word to check if it is in the list (apple, banana, cherry, orange): banana
The word 'banana' is in the list.
Program code:
def iterate_list():
fruits = ['apple', 'banana', 'cherry', 'orange']
# Using a for loop to iterate through the list and print each
element
print("Fruits in the list:") for fruit in fruits:
print(fruit)
# Function to demonstrate iterating over a
range def iterate_range():
print("Printing numbers from 1 to 5:")
# Using a for loop to iterate over a range of
numbers for num in range(1, 6):
print(num)
# Function to demonstrate iterating over a
string def iterate_string():
message = "Python"
# Using a for loop to iterate over each character in the
string print("Characters in the string:")
for char in message:
print(char)
# Main program that calls the functions
print("Demonstrating for loop in Python:")
print("1. Iterate over a list")
print("2. Iterate over a range")
print("3. Iterate over a string")
choice = input("Choose an option (1/2/3): ")
if choice == '1':
iterate_list() elif choice == '2':
iterate_range() elif choice == '3':
iterate_string() else:
print("Invalid choice! Please select 1, 2, or 3.")
OUTPUT:
1. Iterate over a list
2. Iterate over a range
3. Iterate over a string
Choose an option (1/2/3): 1Control flow demonstration:
1. Check if the number is positive, negative, or zero
2. Check if a word is in the list
Choose an option (1/2): 2
Enter a word to check if it is in the list (apple, banana, cherry, orange):
banana
The word 'banana' is in the list.
1. Iterate over a list
2. Iterate over a range
3. Iterate over a string Choose an option (1/2/3): 2 Printing numbers from
1 to 5:
1
2
3
4
5
Demonstrating for loop in Python:
1. Iterate over a list
2. Iterate over a range
3. Iterate over a string
Choose an option (1/2/3): 3
Characters in the string:
P
y
t
h
o
n
Program code:
class Stack:
def __init__(self):
self.stack = []
# Using a list as a stack
def push(self, item):
self.stack.append(item) # Push item onto the stack
def pop(self):
if not self.is_empty():
return self.stack.pop() # Pop item from the top
else:
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.stack[-1] # Return top item without popping
else:
return "Stack is empty"
def is_empty(self):
return len(self.stack) == 0 # Check if stack is empty
def size(self):
return len(self.stack) # Return the size of the stack
# Example Usage if
__name__ == "__main__":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print("Stack after pushing:", stack.stack)
print("Top element:", stack.peek())
print("Popped element:", stack.pop())
print("Stack after popping:", stack.stack)
print("Is stack empty?", stack.is_empty())
OUTPUT:
Stack after pushing: [10, 20, 30]
Top element: 30
Popped element: 30
Stack after popping: [10, 20]
Is stack empty? False
Program Code:
def queue_operations():
queue = [] # Initialize an empty list to represent the queue
while True:
print("\nQueue Operations Menu:")
print("1. Enqueue an element into the queue")
print("2. Dequeue an element from the queue")
print("3. Peek at the front element of the queue")
print("4. Check if the queue is empty")
print("5. Display the queue")
print("6. Exit")
# Take the user's choice of operation
choice = input("Choose an option (1/2/3/4/5/6): ")
if choice == '1':
# Enqueue an element into the queue
element = input("Enter an element to enqueue into the queue: ")
queue.append(element)
print(f"'{element}' has been enqueued into the queue.")
elif choice == '2':
# Dequeue an element from the queue
if queue: # Check if queue is not empty
dequeued_element = queue.pop(0)
print(f"'{dequeued_element}' has been dequeued from the queue.")
else:
print("Error: The queue is empty, cannot dequeue.")
elif choice == '3':
# Peek at the front element of the queue
if queue: # Check if queue is not empty
print(f"The front element of the queue is: '{queue[0]}'")
else:
print("Error: The queue is empty, no front element.")
elif choice == '4':
# Check if the queue is empty
if not queue:
print("The queue is empty.")
else:
print("The queue is not empty.")
elif choice == '5':
# Display the current state of the queue
print("Current queue:", queue)
elif choice == '6':
# Exit the program
print("Exiting the queue operations menu. Goodbye!")
break
else:
print("Invalid choice! Please choose a valid option (1/2/3/4/5/6).")
# Call the function to run the queue operations
queue_operations()
OUTPUT:
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 1 Enter an
element to enqueue into the queue: 10 '10' has
been enqueued into the queue.
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 1 Enter an
element to enqueue into the queue: 100 '100' has
been enqueued into the queue.
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 1
Enter an element to enqueue into the queue: 1000 '1000'
has been enqueued into the queue.
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 2
'10' has been dequeued from the queue.
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 3
The front element of the queue is: '100'
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 4 The
queue is not empty.
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 5
Current queue: ['100', '1000']
Queue Operations Menu:
1. Enqueue an element into the queue
2. Dequeue an element from the queue
3. Peek at the front element of the queue
4. Check if the queue is empty
5. Display the queue
6. Exit
Choose an option (1/2/3/4/5/6): 6
Exiting the queue operations menu. Goodbye!
Program Code:
# Function to demonstrate various tuple operations
def tuple_operations():
# Create a tuple with heterogeneous elements
tuple_example = (1, "Hello", 3.14, True, "Python")
# Display the tuple
print("Original Tuple:", tuple_example)
# Accessing elements of the tuple using indexing
print("\nElement at index 0:", tuple_example[0]) # Accessing first element
print("Element at index 3:", tuple_example[3]) # Accessing fourth element
# Slicing the tuple to get a part of the tuple
sliced_tuple = tuple_example[1:4] # Elements from index 1 to 3
print("\nSliced Tuple (from index 1 to 3):", sliced_tuple)
# Iterating through the tuple using a for loop
print("\nIterating through the tuple:")
for item in tuple_example:
print(item)
# Tuple length
print("\nLength of the tuple:", len(tuple_example))
# Tuple concatenation
another_tuple = (5, "World", 7.2)
concatenated_tuple = tuple_example + another_tuple
print("\nConcatenated Tuple:", concatenated_tuple)
# Tuple repetition
repeated_tuple = tuple_example * 2
print("\nRepeated Tuple (tuple_example * 2):", repeated_tuple)
# Checking membership of an element
print("\nIs 'Python' in the tuple?", "Python" in tuple_example)
print("Is 'Java' in the tuple?", "Java" in tuple_example)
# Call the function to demonstrate tuple operations
tuple_operations()
OUTPUT:
Original Tuple: (1, 'Hello', 3.14, True, 'Python')
Element at index 0: 1
Element at index 3: True
Sliced Tuple (from index 1 to 3): ('Hello', 3.14, True)
Iterating through the tuple:
1
Hello
3.14
True
Python
Length of the tuple: 5
Concatenated Tuple: (1, 'Hello', 3.14, True, 'Python', 5, 'World', 7.2)
Repeated Tuple (tuple_example * 2): (1, 'Hello', 3.14, True, 'Python', 1, 'Hello',
3.14, True, 'Python')
Is 'Python' in the tuple? True
Is 'Java' in the tuple? False
Program Code:
1. # math_operations.py (This is the custom module for mathematical
operations)
# Function for addition
def add(a, b): return
a+b
# Function for subtraction def
subtract(a, b):
return a - b
# Function for multiplication def
multiply(a, b):
return a * b
# Function for division
def divide(a, b): if b
== 0:
return "Error! Division by zero is not allowed."
else:
return a / b
2.# main_program.py (Main program that imports math_operations module)
# Importing the custom module
import math_operations
def main(): print("Choose a mathematical
operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Taking user input for operation choice
choice = input("Enter choice (1/2/3/4): ")
# Taking user input for numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Performing operations based on user choice
if choice == '1':
result = math_operations.add(num1, num2)
print(f"The result of addition is: {result}")
elif choice == '2':
result = math_operations.subtract(num1, num2)
print(f"The result of subtraction is: {result}")
elif choice == '3':
result = math_operations.multiply(num1, num2)
print(f"The result of multiplication is: {result}")
elif choice == '4':
result = math_operations.divide(num1, num2)
print(f"The result of division is: {result}")
else:
print("Invalid input! Please select a valid option.")
# Calling the main function if
__name__ == "__main__":
main()
OUTPUT:
Choose a mathematical operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter the first number: 10
Enter the second number: 20
The result of addition is: 30.0
Choose a mathematical operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 2
Enter the first number: 10
Enter the second number: 20
The result of subtraction is: -10.0
Choose a mathematical operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 3
Enter the first number: 10
Enter the second number: 10
The result of multiplication is: 100.0
Choose a mathematical operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 4
Enter the first number: 10
Enter the second number: 2
The result of division is: 5.0
Program Code:
import os
def read_file(file_path):
try:
# Open the file in read mode
with open(file_path, 'r') as file:
content = file.read()
print("File Content:")
print(content) except
FileNotFoundError:
print(f"The file '{file_path}' does not exist.")
def write_to_file(file_path, content):
try:
# Open the file in write mode
with open(file_path, 'w') as file:
file.write(content)
print(f"Content written to '{file_path}' successfully.")
except Exception as e:
print(f"An error occurred: {e}")
def create_directory(directory_path):
try:
# Create a new directory
os.mkdir(directory_path)
print(f"Directory '{directory_path}' created successfully.")
except FileExistsError:
print(f"The directory '{directory_path}' already exists.")
except Exception as e: print(f"An error occurred: {e}")
def delete_directory(directory_path):
try:
# Remove the directory
os.rmdir(directory_path)
print(f"Directory '{directory_path}' deleted successfully.")
except FileNotFoundError:
print(f"The directory '{directory_path}' does not exist.")
except OSError:
print(f"The directory '{directory_path}' is not empty and cannot be
deleted.")
except Exception as e:
print(f"An error occurred: {e}")
# Main function to test the above functions
if __name__ == "__main__":
# File and directory paths
file_path = "example.txt"
directory_path = "example_directory"
# Writing to the file
write_to_file(file_path, "This is a test content written to the file.")
# Reading from the file
read_file(file_path)
# Creating a directory
create_directory(directory_path)
# Deleting the directory
delete_directory(directory_path)
OUTPUT:
Content written to 'example.txt' successfully.
File Content:
This is a test content written to the file.
Directory 'example_directory' created successfully.
Directory 'example_directory' deleted successfully.
Program Code:
def divide_numbers():
try:
# Taking input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Trying to divide the numbers
result = num1 / num2
print(f"The result of {num1} divided by {num2} is: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter valid numbers!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Division completed successfully.")
finally:
print("Division attempt finished.")
def file_operations():
try:
# Trying to open a file
with open("non_existing_file.txt", 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The file was not found.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("File operation attempt finished.")
def get_number():
try:
# Asking the user to enter a number
number = int(input("Enter a number: "))
print(f"You entered the number: {number}")
except ValueError:
print("Error: Invalid input! Please enter an integer.")
finally:
print("Input attempt finished.")
# Main function to test the above functionalities if
__name__ == "__main__":
print("Testing division operation with exception handling:")
divide_numbers()
print("\nTesting file operation with exception handling:")
file_operations()
print("\nTesting number input with exception handling:")
get_number()
OUTPUT:
Testing division operation with exception handling:
Enter the first number: 10
Enter the second number: 20 The result
of 10.0 divided by 20.0 is: 0.5 Division
completed successfully.
Division attempt finished.
Program code:
class Book:
# Constructor to initialize the book details
def __init__(self, title, author, price):
self.title = title # Title of the book
self.author = author # Author of the book
self.price = price # Price of the book
# Method to display book details
def display_details(self):
print(f"Book Title: {self.title}")
print(f"Author: {self.author}")
print(f"Price: ${self.price:.2f}")
# Method to apply a discount to the price
def apply_discount(self, discount_percentage):
discount_amount = (self.price * discount_percentage) / 100
self.price -= discount_amount
print(f"Discount applied: {discount_percentage}%")
print(f"New price after discount: ${self.price:.2f}")
# Main function to test the class if
__name__ == "__main__":
# Create an object of the Book class
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 20.0)
# Display book details before applying discount
print("Book Details Before Discount:")
book1.display_details()
# Apply a 10% discount to the book
book1.apply_discount(10)
# Display book details after applying discount
print("\nBook Details After Discount:")
book1.display_details()
OUTPUT:
Book Details Before Discount:
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $20.00
Discount applied: 10%
New price after discount: $18.00
Book Details After Discount:
Book Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $18.00
Program Code:
import mysql.connector
# Establishing connection to MySQL database
def connect_to_db():
try:
conn = mysql.connector.connect(
host='localhost', # MySQL server address
user='root', # MySQL username
password='', # MySQL password (empty if no password)
database='address_book' # Database name
)
return conn except
mysql.connector.Error as err:
print(f"Error: {err}")
return None
# Create the contacts table if it doesn't exist
def create_table(conn): cursor =
conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
phone_number VARCHAR(15),
email VARCHAR(100)
)
''')
conn.commit()
# Add a new contact to the address book def
add_contact(conn, name, phone_number, email):
cursor = conn.cursor()
cursor.execute('''
INSERT INTO contacts (name, phone_number, email)
VALUES (%s, %s, %s) ''',
(name, phone_number, email))
conn.commit()
print("Contact added successfully!")
# View all contacts in the address book
def view_contacts(conn): cursor =
conn.cursor()
cursor.execute('SELECT * FROM
contacts')
contacts = cursor.fetchall()
if contacts:
for contact in contacts:
print(f"ID: {contact[0]}, Name: {contact[1]}, Phone: {contact[2]},
Email: {contact[3]}") else:
print("No contacts found.")
# Update contact information def update_contact(conn, contact_id,
name, phone_number, email):
cursor = conn.cursor()
cursor.execute('''
UPDATE contacts
SET name = %s, phone_number = %s, email = %s
WHERE id = %s
''', (name, phone_number, email, contact_id))
conn.commit()
print(f"Contact with ID {contact_id} updated successfully!")
# Delete a contact by ID def
delete_contact(conn, contact_id):
cursor = conn.cursor()
cursor.execute('DELETE FROM contacts WHERE id = %s', (contact_id,))
conn.commit()
print(f"Contact with ID {contact_id} deleted successfully!")
# Main function to demonstrate the address book operations
if __name__ == "__main__":
conn = connect_to_db()
if conn:
create_table(conn) # Ensure the contacts table is created
# Example operations
while True:
print("\nAddress Book Menu:")
print("1. Add Contact")
print("2. View Contacts")
print("3. Update Contact")
print("4. Delete Contact")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone number: ")
email = input("Enter email: ")
add_contact(conn, name, phone, email)
elif choice == '2':
view_contacts(conn)
elif choice == '3':
contact_id = int(input("Enter contact ID to update: "))
name = input("Enter new name: ") phone =
input("Enter new phone number: ") email =
input("Enter new email: ")
update_contact(conn, contact_id, name, phone, email)
elif choice == '4':
contact_id = int(input("Enter contact ID to delete: "))
delete_contact(conn, contact_id)
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
conn.close() # Close the connection to the database
OUTPUT:
Address Book Menu:
1. Add Contact
2. View Contacts
3. Update Contact
4. Delete Contact
5. Exit
Enter your choice (1-5): 1
Enter name: Alice Smith
Enter phone number: 9876543210
Enter email: alice@example.com
Contact added successfully!
Address Book Menu:
1. Add Contact
2. View Contacts
3. Update Contact
4. Delete Contact
5. Exit
Enter your choice (1-5): 3
Enter contact ID to update: 1
Enter new name: Alice Johnson
Enter new phone number: 9998887776
Enter new email: alice.j@example.com
Contact with ID 1 updated successfully!
Address Book Menu:
1. Add Contact
2. View Contacts
3. Update Contact
4. Delete Contact
5. Exit
Enter your choice (1-5): 4
Enter contact ID to delete: 1
Contact with ID 1 deleted successfully!
Program Code:
import re
# Function to validate email using regular expression
def validate_email(email):
# Regular expression pattern for a valid email
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
# Matching the input email with the pattern
if re.match(pattern, email):
return "Valid Email"
else:
return "Invalid Email"
# Main program if __name__
== "__main__":
# Accepting email input from user
email = input("Enter an email address: ")
# Validate and print the result
result = validate_email(email)
print(result)
OUTPUT:
Enter an email address: mailmecks01@gmail.com
Valid Email