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

PYTHON PROGRAMMING LAB 2021-24

The document outlines a Python programming lab with a series of exercises including creating a simple calculator, using control flow tools, implementing data structures, and developing a mathematical operations module. Each program includes an aim, algorithm, and code examples to demonstrate functionality. The document serves as a comprehensive guide for students to practice and enhance their Python programming skills.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PYTHON PROGRAMMING LAB 2021-24

The document outlines a Python programming lab with a series of exercises including creating a simple calculator, using control flow tools, implementing data structures, and developing a mathematical operations module. Each program includes an aim, algorithm, and code examples to demonstrate functionality. The document serves as a comprehensive guide for students to practice and enhance their Python programming skills.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

PROGRAMMING IN PYTHON – 22UCAP07

PYTHON PROGRAMMING LAB


LIST OF PROGRAMS:

1. Create a simple calculator to do all the arithmetic operations.

2. Write a program to use control flow tools like if.

3. Write a program to use for loop.

4. Data structures

a. use list as stack.

b. use list as queue.

c. tuple, sequence.

5. Create new module for mathematical operations and use in your program.

6. Write a program to read and write files, create and delete directories.

7. Write a program with exception handling.

8. Write a program using classes.

9. Connect with MySQL and create address book.

10. Write a program using string handling and regular expressions.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 1
PROGRAMMING IN PYTHON – 22UCAP07

1. CREATE A SIMPLE CALCULATOR TO DO ALL THE ARITHMETIC


OPERATIONS.
Aim:
To write a program to create a simple calculator to do all the arithmetic operations.
Algorithm:
1. Define validate_operation function:
 Prompt the user to enter an arithmetic operation.
 Check if the input operation is valid (+, -, *, /, %, **).
 If valid, return the operation.
 If invalid, display an error message and return None.
2. Define calculator function:
 Display a welcome message and list the available operations.
 Call the validate_operation function to get the user's desired operation.
 If the operation is invalid (returned None), terminate the function.
 Prompt the user to enter two numbers.
 Convert the inputs to floating-point numbers.
 If input is invalid, catch the exception and display an error message.
 Perform the selected operation:
 Addition (+): Add the two numbers.
 Subtraction (-): Subtract the second number from the first.
 Multiplication (*): Multiply the two numbers.
 Division (/): Check for division by zero. If valid, divide the first number by the
second.
 Modulus (%): Compute the remainder of the division of the two numbers.
 Exponentiation (**): Compute the first number raised to the power of the second
number.
 Display the result of the operation.
 Handle division by zero gracefully by displaying an error message.
3. Main Program:
 If the script is run directly, call the calculator function.
Code:
def validate_operation():
"""
Prompts the user to enter a valid arithmetic operation.
Returns the operation if valid, otherwise returns None.
"""

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 2
PROGRAMMING IN PYTHON – 22UCAP07

operation = input("Enter the operation (+, -, *, /, %, **): ")


if operation not in ['+', '-', '*', '/', '%', '**']:
print("Invalid operation! Please try again.")
return None
return operation

def calculator():
"""
A simple calculator program that performs basic arithmetic operations.
Allows the user to input two numbers and choose an operation to perform.
Supports addition, subtraction, multiplication, division, modulus, and exponentiation.
Handles invalid inputs and division by zero gracefully.
"""
print("Simple Calculator")
print("Operations:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Modulus (%)")
print("6. Exponentiation (**)")

try:
# Take input from the user
operation = validate_operation()
if not operation:
return

# Get the two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform the operation


if operation == '+':
result = num1 + num2
elif operation == '-':

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 3
PROGRAMMING IN PYTHON – 22UCAP07

result = num1 - num2


elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 == 0:
print("Division by zero is not allowed!")
return
result = num1 / num2
elif operation == '%':
result = num1 % num2
elif operation == '**':
result = num1 ** num2

# Display the result


print(f"The result of {num1} {operation} {num2} is: {result}")
except ValueError:
print("Invalid input! Please enter numeric values.")

# Run the calculator


if __name__ == "__main__":
calculator()

Result:
Thus the program to create a simple calculator to do all the arithmetic operations has
been executed and verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 4
PROGRAMMING IN PYTHON – 22UCAP07

2. Write a program to use control flow tools like if.


Aim:
To write a program to use control flow tools like if.
Algorithm:
1. Define the number_category function:
 Purpose: Categorize a number as positive, negative, or zero, and determine
whether it is even or odd (if applicable).
2. User Input:
 Prompt the user to enter a number.
 Convert the input into an integer.
 If the conversion fails (non-integer input), display an error message and terminate
the function.
3. Determine the Number's Category:
 If the number is greater than 0:
 Print "The number is positive."
 Else if the number is less than 0:
 Print "The number is negative."
 Else:
 Print "The number is zero."
4. Determine the Parity (Even or Odd):
 If the number is not zero:
 If the number is divisible by 2 (remainder is 0):
 Print "The number is even."
 Else:
 Print "The number is odd."
5. Error Handling:
 If the user input is invalid (not an integer), catch the ValueError and display:
"Invalid input! Please enter an integer."
6. Main Program:
 If the script is run directly:
 Call the number_category function.

Code:
def number_category():
"""
A program that categorizes a number as positive, negative, or zero

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 5
PROGRAMMING IN PYTHON – 22UCAP07

and determines whether it is even or odd (if applicable).


"""
try:
# Input from the user
number = int(input("Enter a number: "))

# Check if the number is positive, negative, or zero


if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

# Check if the number is even or odd


if number != 0:
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

except ValueError:
print("Invalid input! Please enter an integer.")

# Run the program


if __name__ == "__main__":
number_category()

Result:
Thus the program to use control flow tools like “if” has been executed and verified
successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 6
PROGRAMMING IN PYTHON – 22UCAP07

3. Write a program to use for loop.


Aim:
To write a program to use for loop.
Algorithm:
1. Define Function:
a. Define a function print_squares(limit) that prints the squares of numbers from 1 to
the given limit.
2. Error Handling in Function:
a. Wrap the logic inside a try block to catch any potential TypeError.
b. Use a for loop to iterate through numbers from 1 to limit (inclusive).
c. For each number, calculate its square and print the result in a formatted string.
d. If the input is not a valid integer, handle the TypeError and print an error message.
3. Main Execution:
a. Check if the script is being run as the main program (if __name__ == "__main__":).
b. Initialize a predefined value for limit. (For environments without input(), a value of
10 is used.)
c. Validate the limit:
d. If limit is less than or equal to 0, print a message asking for a positive integer.
e. Otherwise, call the print_squares(limit) function.
f. Use a try block to catch any potential ValueError if the input is invalid.
4. Edge Cases:
a. Handle invalid inputs gracefully, such as non-integer or negative values.

Code:
def print_squares(limit):
"""
A program that prints the squares of numbers from 1 to the specified limit.
"""
try:
# Loop from 1 to the limit (inclusive)
for number in range(1, limit + 1):
print(f"The square of {number} is {number ** 2}")
except TypeError:
print("Invalid input! Please provide an integer.")

# Run the program


if __name__ == "__main__":
try:
# Predefined input for environments that do not support input()
limit = 10 # Replace this with any positive integer as needed
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 7
PROGRAMMING IN PYTHON – 22UCAP07

if limit <= 0:
print("Please enter a positive integer.")
else:
print_squares(limit)
except ValueError:
print("Invalid input! Please enter an integer.")

Result:
Thus the program to use for loop has been executed and verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 8
PROGRAMMING IN PYTHON – 22UCAP07

4. Write a program to perform Data Struction.


a) use list as stack.
b. use list as queue.
c. tuple, sequence.
Aim:
To write a program to use Data Structures in Python
Algorithm:

Input: None (demonstration involves predefined operations on data structures)

Output: Printed outputs for each operation's result

1. Using a List as a Stack


a. Initialize an empty list as a stack.
b. Push three elements (1, 2, 3) onto the stack using the append() method.
c. Print the stack after pushing elements.
d. Pop the top element using the pop() method.
e. Print the popped element.
f. Print the stack after popping an element.
2. Using a List as a Queue
a. Import the deque class from the collections module.
b. Initialize an empty deque as a queue.
c. Enqueue three elements (1, 2, 3) into the queue using the append() method.
d. Print the queue after enqueuing elements.
e. Dequeue the front element using the popleft() method.
f. Print the dequeued element.
g. Print the queue after dequeuing an element.
3. Working with Tuples and Sequences
a. Create a tuple my_tuple with values (10, 20, 30, 40).
b. Print the tuple.
c. Access the first element of the tuple using index 0 and print it.
d. Define a string my_string with the value "Hello".
e. Print the string as a sequence.
f. Iterate through the string, printing each character.
g. Slice the tuple from index 1 to 2 (inclusive of start, exclusive of end) and print the sliced
portion.

Code:
# Demonstration of Data Structures in Python

# Part a: Using a List as a Stack


# A stack is a Last In, First Out (LIFO) data structure

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 9
PROGRAMMING IN PYTHON – 22UCAP07

stack = []

# Push elements onto the stack


stack.append(1)
stack.append(2)
stack.append(3)
print("Stack after pushing elements:", stack)

# Pop elements from the stack


element = stack.pop()
print("Popped element:", element)
print("Stack after popping an element:", stack)

# Part b: Using a List as a Queue


# A queue is a First In, First Out (FIFO) data structure
from collections import deque
queue = deque()

# Enqueue elements into the queue


queue.append(1)
queue.append(2)
queue.append(3)
print("Queue after enqueuing elements:", queue)

# Dequeue elements from the queue


element = queue.popleft()
print("Dequeued element:", element)
print("Queue after dequeuing an element:", queue)

# Part c: Working with Tuples and Sequences


# Tuple: An immutable sequence
my_tuple = (10, 20, 30, 40)
print("Tuple:", my_tuple)

# Accessing elements in a tuple


first_element = my_tuple[0]

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 10
PROGRAMMING IN PYTHON – 22UCAP07

print("First element of the tuple:", first_element)

# Sequence: Strings, lists, and tuples are examples of sequences


# Example of a string as a sequence
my_string = "Hello"
print("String as a sequence:", my_string)

# Iterating over a sequence


print("Characters in the string:")
for char in my_string:
print(char)

# Slicing a sequence
sliced_tuple = my_tuple[1:3]
print("Sliced tuple:", sliced_tuple)
Result:
Thus the program to demonstrate the data structure using python has been executed and
verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 11
PROGRAMMING IN PYTHON – 22UCAP07

5. Create new module for mathematical operations and use in your program.
Aim:
To write a program to create new module for mathematical operations and use in your
program.

Algorithm:

1. Define Functions for Mathematical Operations (in math_operations.py):


a. Create a function add(a, b) to calculate and return the sum of two numbers.
b. Create a function subtract(a, b) to calculate and return the difference between two
numbers.
c. Create a function multiply(a, b) to calculate and return the product of two numbers.
d. Create a function divide(a, b) to calculate and return the quotient of two numbers.
o Ensure the divisor b is not zero.
o If b is zero, raise a ValueError with an appropriate message.
2. Write the Main Program Logic (in main.py):
a. Import the math_operations module as mo.
b. Define a main() function to execute the following steps:
o Initialize two numbers a and b with values 10 and 5, respectively.
o Call and display the results of the mathematical operations by using the functions from
the math_operations module:
 Print the result of mo.add(a, b) with a label "Addition".
 Print the result of mo.subtract(a, b) with a label "Subtraction".
 Print the result of mo.multiply(a, b) with a label "Multiplication".
 Print the result of mo.divide(a, b) with a label "Division".
3. Run the Program:
a. Use the if __name__ == "__main__": block to ensure the main() function runs only when
the script is executed directly.
b. Execute the main() function.

Code:
# math_operations.py

def add(a, b):


"""Return the sum of two numbers."""
return a + b

def subtract(a, b):


"""Return the difference of two numbers."""
return a - b

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 12
PROGRAMMING IN PYTHON – 22UCAP07

def multiply(a, b):


"""Return the product of two numbers."""
return a * b

def divide(a, b):


"""Return the quotient of two numbers."""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b

# main.py

import math_operations as mo

def main():
a = 10
b=5

print("Addition:", mo.add(a, b))


print("Subtraction:", mo.subtract(a, b))
print("Multiplication:", mo.multiply(a, b))
print("Division:", mo.divide(a, b))

if __name__ == "__main__":
main()

Result:
Thus the program to create new module for mathematical operations and use in your
program has been executed and verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 13
PROGRAMMING IN PYTHON – 22UCAP07

6. Write a program to read and write files, create and delete directories.

Aim:
To write a program to read and write files, create and delete directories.

Algorithm:

1. Import Necessary Libraries:


o Import the os module to perform file and directory operations.
2. Define Utility Functions:
o create_directory(directory_name)
 Check if the specified directory exists using
os.path.exists(directory_name).
 If it does not exist, create the directory using os.makedirs(directory_name)
and print a success message.
 If it exists, print a message indicating the directory already exists.
o delete_directory(directory_name)
 Check if the specified directory exists using
os.path.exists(directory_name).
 If it exists, delete the directory using os.rmdir(directory_name) and print a
success message.
 If it does not exist, print a message indicating the directory does not exist.
o write_to_file(file_path, content)
 Open the file at the specified path in write mode ('w') using with
open(file_path, 'w').
 Write the provided content to the file and print a success message.
o read_from_file(file_path)
 Check if the specified file exists using os.path.exists(file_path).
 If it exists, open the file in read mode ('r') and read its contents.
 Print the content of the file.
 If the file does not exist, print a message indicating the file does not exist.
3. Define the Main Function:
o Set Paths:
 Define a directory name (example_dir).
 Define a file name (example_file.txt) and construct its full path using
os.path.join(directory_name, file_name).
o Perform Operations:
 Create the directory by calling create_directory(directory_name).
 Define content for the file and write it using write_to_file(file_path,
content).
 Read and display the file's content using read_from_file(file_path).
 Check if the file exists using os.path.exists(file_path) and delete it using
os.remove(file_path), then print a message.
 Delete the directory by calling delete_directory(directory_name).

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 14
PROGRAMMING IN PYTHON – 22UCAP07

4. Execute the Script:


o Use the if __name__ == "__main__": block to call the main() function, ensuring it
only executes when the script is run directly.

Code:
import os

def create_directory(directory_name):
"""Create a directory if it doesn't already exist."""
if not os.path.exists(directory_name):
os.makedirs(directory_name)
print(f"Directory '{directory_name}' created.")
else:
print(f"Directory '{directory_name}' already exists.")

def delete_directory(directory_name):
"""Delete a directory if it exists."""
if os.path.exists(directory_name):
os.rmdir(directory_name)
print(f"Directory '{directory_name}' deleted.")
else:
print(f"Directory '{directory_name}' does not exist.")

def write_to_file(file_path, content):


"""Write content to a file."""
with open(file_path, 'w') as file:
file.write(content)
print(f"Content written to file '{file_path}'.")

def read_from_file(file_path):
"""Read content from a file."""
if os.path.exists(file_path):
with open(file_path, 'r') as file:
content = file.read()
print(f"Content of file '{file_path}':\n{content}")
else:
print(f"File '{file_path}' does not exist.")

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 15
PROGRAMMING IN PYTHON – 22UCAP07

def main():
# Directory and file paths
directory_name = "example_dir"
file_name = "example_file.txt"
file_path = os.path.join(directory_name, file_name)

# Create a directory
create_directory(directory_name)

# Write to a file
content = "Hello, this is a sample file content."
write_to_file(file_path, content)

# Read from the file


read_from_file(file_path)

# Delete the file and directory


if os.path.exists(file_path):
os.remove(file_path)
print(f"File '{file_path}' deleted.")
delete_directory(directory_name)

if __name__ == "__main__":
main()

Result:
Thus the program to read and write files, create and delete directories using python has
been executed and verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 16
PROGRAMMING IN PYTHON – 22UCAP07

7. Write a program with exception handling.

Aim:
To develop a python program with exception handling.

Algorithm:

1. Define the Function arithmetic_operations:


o Input Phase:
 Prompt the user to input two numbers (num1 and num2) and convert them to
floating-point values.
 Prompt the user to input an operation (+, -, *, /) and store it as a string.
o Process Phase:
 Check the selected operation:
 If the operation is +, calculate the sum of num1 and num2.
 If the operation is -, calculate the difference between num1 and num2.
 If the operation is *, calculate the product of num1 and num2.
 If the operation is /:
 Check if num2 is 0. If true, raise a ZeroDivisionError.
 Otherwise, calculate the quotient of num1 divided by num2.
 If none of the above, raise a ValueError indicating an invalid operation.
o Output Phase:
 Print the result of the operation in the format <num1> <operation> <num2> =
<result>.
2. Error Handling:
o Use a try-except block to handle potential errors:
 ValueError:
 Catch and print a message indicating an invalid number or operation was
entered.
 ZeroDivisionError:
 Catch and print a message indicating division by zero is not allowed.
 General Exception:
 Catch and print a message for any other unexpected errors.
o Use a finally block to print a thank-you message indicating the calculation is
complete.
3. Execute the Function:
o Use the if __name__ == "__main__": block to call the arithmetic_operations()
function, ensuring it only runs when the script is executed directly.

Code:
def arithmetic_operations():
try:
# Get user inputs
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 17
PROGRAMMING IN PYTHON – 22UCAP07

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
operation = input("Choose an operation (+, -, *, /): ").strip()

# Perform the selected operation


if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
if num2 == 0:
raise ZeroDivisionError("Division by zero is not allowed.")
result = num1 / num2
else:
raise ValueError("Invalid operation selected. Please choose +, -, *, or /.")

print(f"The result of {num1} {operation} {num2} is: {result}")

except ValueError as ve:


print(f"Value Error: {ve}")
except ZeroDivisionError as zde:
print(f"Math Error: {zde}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("Calculation complete. Thank you for using the calculator.")

if __name__ == "__main__":
arithmetic_operations()

Result:
Thus the python program with exception handling has been executed and verified
successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 18
PROGRAMMING IN PYTHON – 22UCAP07

8. Write a program using classes.


Aim:
To develop a python program using classes.
Algorithm:

1. Define the BankAccount Class:


o Initialization (__init__):
 Accept account_holder (name of the account holder) and an optional
initial_balance (default 0.0).
 Set self.account_holder to account_holder.
 Set self.balance to initial_balance.
o Deposit Method (deposit):
 Check if the deposit amount is greater than 0:
 If valid, add the amount to self.balance and print the updated balance.
 If invalid, print an error message indicating the deposit must be positive.
o Withdraw Method (withdraw):
 Check if the withdrawal amount is positive and does not exceed the account
balance:
 If valid, subtract the amount from self.balance and print the updated
balance.
 If invalid, print an appropriate error message (e.g., insufficient funds or
invalid withdrawal amount).
o Balance Inquiry (get_balance):
 Print the current account balance.
o String Representation (__str__):
 Return a string summarizing the account holder's name and the current balance.
2. Define the Main Program Logic:
o Account Creation:
 Prompt the user for their name and create a BankAccount object with the
provided name.
o User Interaction Loop:
 Display the banking system menu:
 Option 1 (Deposit):
 Prompt the user for a deposit amount.
 Call the deposit method to update the account balance.
 Option 2 (Withdraw):
 Prompt the user for a withdrawal amount.
 Call the withdraw method to process the withdrawal.
 Option 3 (Check Balance):
 Call the get_balance method to display the account balance.
 Option 4 (Exit):
 Print a thank-you message and terminate the loop.
 Invalid Input:

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 19
PROGRAMMING IN PYTHON – 22UCAP07


Print an error message if the user's input does not match the
options.
o Repeat the loop until the user chooses to exit.
3. Execute the Program:
o Use the if __name__ == "__main__": block to call the main() function, ensuring it
only runs when the script is executed directly.

Code:
class BankAccount:
"""A class to represent a bank account."""

def __init__(self, account_holder, initial_balance=0.0):


"""Initialize account holder and balance."""
self.account_holder = account_holder
self.balance = initial_balance

def deposit(self, amount):


"""Deposit money into the account."""
if amount <= 0:
print("Deposit amount must be positive.")
else:
self.balance += amount
print(f"Deposited ${amount:.2f}. New balance: ${self.balance:.2f}")

def withdraw(self, amount):


"""Withdraw money from the account."""
if amount <= 0:
print("Withdrawal amount must be positive.")
elif amount > self.balance:
print("Insufficient funds.")
else:
self.balance -= amount
print(f"Withdrew ${amount:.2f}. New balance: ${self.balance:.2f}")

def get_balance(self):
"""Return the current balance."""
print(f"Account balance: ${self.balance:.2f}")

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 20
PROGRAMMING IN PYTHON – 22UCAP07

def __str__(self):
"""Return a string representation of the account."""
return f"BankAccount({self.account_holder}, Balance: ${self.balance:.2f})"

def main():
# Create an account for the user
name = input("Enter account holder's name: ")
account = BankAccount(name)
while True:
print("\n--- Banking System ---")
print("1. Deposit")
print("2. Withdraw")
print("3. Check Balance")
print("4. Exit")
choice = input("Choose an option (1-4): ")

if choice == "1":
amount = float(input("Enter deposit amount: "))
account.deposit(amount)
elif choice == "2":
amount = float(input("Enter withdrawal amount: "))
account.withdraw(amount)
elif choice == "3":
account.get_balance()
elif choice == "4":
print("Thank you for using the banking system. Goodbye!")
break
else:
print("Invalid option. Please try again.")

if __name__ == "__main__":
main()

Result:
Thus the program to demonstrate the classes concept using python has been executed and
verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 21
PROGRAMMING IN PYTHON – 22UCAP07

9. Connect with MySQL and create address book.


Aim:
To develop a python program for connecting with the MySQL database and to create an
address book.
Algorithm:

1. Initialize the AddressBook Class:


o Establish a connection to the MySQL database using provided credentials (host, user,
password, database).
o Create a cursor object for executing SQL queries.
2. Define the Class Methods:
o add_contact(name, phone, email)
 Construct an SQL INSERT query to add a new contact with the given name,
phone, and email.
 Execute the query and commit the transaction.
 Print a success message or handle errors.
o view_contacts()
 Construct an SQL SELECT query to retrieve all contacts.
 Execute the query and fetch the results.
 If contacts are found, display each contact's details (ID, name, phone, email).
Otherwise, print a message indicating no contacts.
o update_contact(contact_id, name=None, phone=None, email=None)
 Build an SQL UPDATE query dynamically based on which fields (name, phone,
email) are provided.
 Execute the query with updated values and commit the transaction.
 Print a success message or handle errors.
o delete_contact(contact_id)
 Construct an SQL DELETE query to remove a contact by their ID.
 Execute the query and commit the transaction.
 Print a success message or handle errors.
o close()
 Close the database cursor and connection.
3. Define the Main Function:
o Set Up:
 Specify database credentials.
 Create an instance of the AddressBook class.
o User Interaction Loop:
 Display the menu options:
 Option 1 (Add Contact):
 Prompt the user for name, phone, and email.
 Call add_contact with the provided values.
 Option 2 (View Contacts):
 Call view_contacts to display all stored contacts.
 Option 3 (Update Contact):
 Prompt the user for the contact_id of the contact to update.
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 22
PROGRAMMING IN PYTHON – 22UCAP07


Ask for new values for name, phone, and email. Leave blank to
retain current values.
 Call update_contact with the provided values.
 Option 4 (Delete Contact):
 Prompt the user for the contact_id of the contact to delete.
 Call delete_contact with the provided ID.
 Option 5 (Exit):
 Call close() to terminate the database connection.
 Break the loop to exit the program.
 Invalid Input:
 Print a message indicating the input is invalid and prompt again.
o Repeat until the user chooses to exit.
4. Execute the Program:
o Use the if __name__ == "__main__": block to call the main() function, ensuring it
only runs when the script is executed directly.

Code:
import mysql.connector

class AddressBook:
def __init__(self, host, user, password, database):
"""Initialize the connection to the database."""
self.conn = mysql.connector.connect(
host=host,
user=user,
password=password,
database=database
)
self.cursor = self.conn.cursor()

def add_contact(self, name, phone, email):


"""Add a new contact to the address book."""
try:
query = "INSERT INTO contacts (name, phone, email) VALUES (%s, %s, %s)"
self.cursor.execute(query, (name, phone, email))
self.conn.commit()
print("Contact added successfully.")
except Exception as e:
print(f"Error adding contact: {e}")

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 23
PROGRAMMING IN PYTHON – 22UCAP07

def view_contacts(self):
"""View all contacts in the address book."""
try:
query = "SELECT * FROM contacts"
self.cursor.execute(query)
results = self.cursor.fetchall()
if results:
print("\n--- Address Book ---")
for contact in results:
print(f"ID: {contact[0]}, Name: {contact[1]}, Phone: {contact[2]}, Email:
{contact[3]}")
else:
print("No contacts found.")
except Exception as e:
print(f"Error retrieving contacts: {e}")

def update_contact(self, contact_id, name=None, phone=None, email=None):


"""Update an existing contact."""
try:
fields = []
values = []
if name:
fields.append("name = %s")
values.append(name)
if phone:
fields.append("phone = %s")
values.append(phone)
if email:
fields.append("email = %s")
values.append(email)
if not fields:
print("No updates provided.")
return

query = f"UPDATE contacts SET {', '.join(fields)} WHERE id = %s"

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 24
PROGRAMMING IN PYTHON – 22UCAP07

values.append(contact_id)
self.cursor.execute(query, values)
self.conn.commit()
print("Contact updated successfully.")
except Exception as e:
print(f"Error updating contact: {e}")

def delete_contact(self, contact_id):


"""Delete a contact from the address book."""
try:
query = "DELETE FROM contacts WHERE id = %s"
self.cursor.execute(query, (contact_id,))
self.conn.commit()
print("Contact deleted successfully.")
except Exception as e:
print(f"Error deleting contact: {e}")

def close(self):
"""Close the database connection."""
self.cursor.close()
self.conn.close()

def main():
# Replace with your MySQL credentials
host = "localhost"
user = "root"
password = "your_password"
database = "address_book"

address_book = AddressBook(host, user, password, database)

while True:
print("\n--- Address Book Menu ---")
print("1. Add Contact")
print("2. View Contacts")

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 25
PROGRAMMING IN PYTHON – 22UCAP07

print("3. Update Contact")


print("4. Delete Contact")
print("5. Exit")
choice = input("Choose an option (1-5): ")

if choice == "1":
name = input("Enter name: ")
phone = input("Enter phone number: ")
email = input("Enter email address: ")
address_book.add_contact(name, phone, email)
elif choice == "2":
address_book.view_contacts()
elif choice == "3":
contact_id = int(input("Enter contact ID to update: "))
name = input("Enter new name (leave blank to keep current): ").strip() or None
phone = input("Enter new phone number (leave blank to keep current): ").strip() or
None
email = input("Enter new email address (leave blank to keep current): ").strip() or None
address_book.update_contact(contact_id, name, phone, email)
elif choice == "4":
contact_id = int(input("Enter contact ID to delete: "))
address_book.delete_contact(contact_id)
elif choice == "5":
print("Exiting Address Book. Goodbye!")
address_book.close()
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Result:
Thus the program to for connecting with the MySQL database and to create an address
book using python has been executed and verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 26
PROGRAMMING IN PYTHON – 22UCAP07

10. Write a program using string handling and regular expressions


Aim:
To develop a python program using string handling and regular expressions.
Algorithm:

1. Import Required Libraries:


o Import the re module for regular expression operations.
2. Define the validate_email Function:
o Input: A string email.
o Process:
 Define a regular expression pattern that matches standard email formats.
 Use re.match to check if the email matches the pattern.
o Output: Return True if the email is valid; otherwise, return False.
3. Define the extract_emails Function:
o Input: A string text.
o Process:
 Define a regular expression pattern to identify email addresses in the text.
 Use re.findall to extract all matching email addresses from the text.
o Output: Return a list of extracted email addresses.
4. Define the main Function:
o Display a menu with the following options:
 Option 1: Validate Email
 Prompt the user to enter an email address.
 Call validate_email with the input email.
 Print whether the email is valid or invalid based on the function's result.
 Option 2: Extract Emails from Text
 Prompt the user to enter a block of text.
 Call extract_emails with the input text.
 If email addresses are found, print them; otherwise, indicate no valid
email addresses were found.
 Option 3: Exit
 Print a goodbye message and terminate the program.
 Invalid Input:
 Display an error message if the input does not match the menu options.
o Repeat the menu until the user chooses to exit.
5. Execute the Program:
o Use the if __name__ == "__main__": block to call the main() function, ensuring the
program runs only when executed directly.

Code:
import re

def validate_email(email):

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 27
PROGRAMMING IN PYTHON – 22UCAP07

"""
Validates if the given email address matches the standard format.
Returns True if valid, False otherwise.
"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))

def extract_emails(text):
"""
Extracts all valid email addresses from the given text using regular expressions.
Returns a list of email addresses.
"""
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
return re.findall(pattern, text)

def main():
print("=== Email Validator and Extractor ===")

while True:
print("\n1. Validate Email")
print("2. Extract Emails from Text")
print("3. Exit")
choice = input("Choose an option (1-3): ")

if choice == "1":
email = input("Enter an email address to validate: ")
if validate_email(email):
print(f"'{email}' is a valid email address.")
else:
print(f"'{email}' is not a valid email address.")

elif choice == "2":


print("Enter a block of text containing email addresses:")
text = input()
emails = extract_emails(text)
if emails:

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 28
PROGRAMMING IN PYTHON – 22UCAP07

print("\nValid email addresses found:")


for email in emails:
print(f" - {email}")
else:
print("No valid email addresses found.")

elif choice == "3":


print("Exiting the program. Goodbye!")
break

else:
print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
main()

Result:
Thus the program to demonstrate string handling and regular expressions using python has
been executed and verified successfully.

Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 29

You might also like