PYTHON PROGRAMMING LAB 2021-24
PYTHON PROGRAMMING LAB 2021-24
4. Data structures
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.
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 1
PROGRAMMING IN PYTHON – 22UCAP07
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 2
PROGRAMMING IN PYTHON – 22UCAP07
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
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 3
PROGRAMMING IN PYTHON – 22UCAP07
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
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
except ValueError:
print("Invalid input! Please enter an integer.")
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
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.")
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
Code:
# Demonstration of Data Structures in Python
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 9
PROGRAMMING IN PYTHON – 22UCAP07
stack = []
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 10
PROGRAMMING IN PYTHON – 22UCAP07
# 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:
Code:
# math_operations.py
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 12
PROGRAMMING IN PYTHON – 22UCAP07
# main.py
import math_operations as mo
def main():
a = 10
b=5
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:
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 14
PROGRAMMING IN PYTHON – 22UCAP07
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 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)
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
Aim:
To develop a python program with exception handling.
Algorithm:
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
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
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 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
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()
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}")
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 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"
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
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
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.")
Mr. S.YOGESHWAR, B.C.A., M.Sc., B.Ed., ASST. PROF. IN COMPUTER APPLICATION Page 28
PROGRAMMING IN PYTHON – 22UCAP07
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