Python Labb
Python Labb
NO: 01
CREATE A SIMPLE CALCULATOR TO DO ALL THE
1
CODING:
# 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':
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()
RESULT:
Thus the above program is verified and executed successfully.
3
EX. NO: 02
WRITE A PROGRAM TO USE CONTROL FLOW TOOLS LIKE IF
DATE:
4
CODING:
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.")
RESULT:
Thus the above program is verified and executed successfully.
5
EX. NO: 03
WRITE A PROGRAM TO USE FOR LOOP
DATE:
6
CODING:
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}")
RESULT:
Thus the above program is verified and executed successfully.
7
DATA STRUCTURES
EX. NO: 04
A. USE LIST AS STACK B. USE LIST AS QUEUE
C. TUPLE, SEQUENCE
DATE:
8
A. USE LIST AS STACK
CODING:
# 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)
9
queue.append(2)
queue.append(3)
# Dequeue elements
dequeued_element = queue.pop(0)
# Output
print("Queue:", queue)
print("Dequeued Element:", dequeued_element)
C. TUPLE, SEQUENCE
CODING:
# 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)
10
SAMPLE INPUT / OUTPUT:
1
2
3
4
5
Element at index 2: 3
RESULT:
Thus above program is verified and executed successfully.
11
EX. NO: 05 CREATE NEW MODULE FOR MATHEMATICAL OPERATIONS
AND USE IN YOUR PROGRAM
DATE:
12
CODING:
# 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
import math_operations as math_ops
# Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Perform mathematical operations
sum_result = math_ops.add(num1, num2)
difference_result = math_ops.subtract(num1, num2)
product_result = math_ops.multiply(num1, num2)
division_result = math_ops.divide(num1, num2)
# Output
print(f"Sum: {sum_result}")
print(f"Difference: {difference_result}")
print(f"Product: {product_result}")
13
print(f"Division: {division_result}")
RESULT:
Thus the above program is verified and executed successfully.
14
EX. NO: 06 WRITE A PROGRAM TO READ AND WRITE FILES, CREATE
AND DELETE DIRECTORIES
DATE:
15
CODING:
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.")
16
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()
RESULT:
Thus the above program is verified and executed successfully.
17
EX. NO: 07
WRITE A PROGRAM WITH EXCEPTION HANDLING
DATE:
18
CODING:
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()
19
RESULT:
Thus the above program is verified and executed successfully.
20
EX. NO: 08
WRITE A PROGRAM USING CLASSES
DATE:
21
CODING:
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()
22
Information about Book 2:
Title: To Kill a Mockingbird
Author: Harper Lee
Publication Year: 1960
Information about Book 3:
Title: 1984
Author: George Orwell
Publication Year: 1949
RESULT:
Thus the above program is verified and executed successfully.
23
EX. NO: 09
CONNECT WITH MYSQL AND CREATE ADDRESS BOOK
DATE:
24
CODING:
import sys
import MySQLdb
#connect
conn = MySQLdb.connect(host=”localhost”,user=”root”,passwd=”home”,db=”address_book”)
#create a cursor
cursor = conn.cursor()
#Add Records
def Add():
var = True
while var:
ssn = raw_input(“Enter SSN number:”)
name = raw_input(“Enter a Name:”)
address = raw_input(“Enter the Address:”)
city = raw_input(“Enter the City:”)
state= raw_input(“Enter the State:”)
postcode = raw_input(“Enter the Postcode:”)
country = raw_input(“Enter the country:”)
cursor.execute(“””
insert into addresses (ssn,name,address,city,state,postcode,country)
values (%s,%s,%s,%s,%s,%s,%s)”””,(ssn,name,address,city,state,postcode,country))
print “Add Another Record y/n”
enter = raw_input(“Enter the option:”)
if enter == ‘y’:
var = True
else:
var = False
#Modify Records
25
def Modify():
ssn = raw_input(“Enter the old ssn number to update:”)
26
print ‘5.Exit’
option = int(raw_input(‘Enter the Option :’))
if option == 1:
Add()
elif option == 2:
Modify()
elif option == 3:
Delete()
elif option == 4:
List()
elif option == 5:
Exit()
printToConsole()
OUTPUT FROM CONSOLE(ADD OPTION):
1.Add Record
2.Modify Record
3.Delete Record
4.List Record
5.Exit
SAMPLE INPUT/OUTPUT:
Enter the Option :1
Enter SSN number:123
Enter a Name:Shrini
Enter the Address:Kambar Street
Enter the City:Kanchipuram
Enter the State:TamilNadu
27
Enter the Postcode:600078
Enter the country:India
Add Another Record y/n
Enter the option:y
Enter SSN number:456
Enter a Name:Raji
Enter the Address:Gandhi Street
Enter the City:Chennai
28
Enter the Option :4
List the Records
123 –> Shrini –> Kambar Street –> Kanchipuram –> TamilNadu –> 600078 –
> India
456 –> Raji –> Gandhi Street –> Chennai –> TamilNadu –> 600062 –> India
789 –> Selvi –> ThenMada Street –> Chennai –> TamilNadu –> 600089 –>
India
OUTPUT FROM MYSQL DATABASE:
mysql> select * from addresses;
+—–+——–+—————–+————-+———–+———-+———+
| ssn | name | address | city | state | postcode | country |
+—–+——–+—————–+————-+———–+———-+———+
| 123 | Shrini | Kambar Street | Kanchipuram | TamilNadu | 600078 | India |
29
123 –> Shrini –> Kambar Street –> Kanchipuram –> TamilNadu –> 600078 –
> India
456 –> Raji –> Gandhi Street –> Chennai –> TamilNadu –> 600062 –> India
101 –> Selvi –> ThenMada Street –> Chennai –> TamilNadu –> 600089 –>
India (Modified data)
OUTPUT FROM MYSQL DATABASE(MODIFY OPTION):
mysql> select * from addresses;
+—–+——–+—————–+————-+———–+———-+———+
| ssn | name | address | city | state | postcode | country |
+—–+——–+—————–+————-+———–+———-+———+
| 123 | Shrini | Kambar Street | Kanchipuram | TamilNadu | 600078 | India |
| 456 | Raji | Gandhi Street | Chennai | TamilNadu | 600062 | India |
| 101 | Selvi | ThenMada Street | Chennai | TamilNadu | 600089 | India |
+—–+——–+—————–+————-+———–+———-+———+
3 rows in set (0.00 sec)
OUTPUT FROM CONSOLE(DELETE OPTION):
Enter the Option :3
30
OUTPUT FROM MYSQL DATABASE(DELETE OPTION):
mysql> select * from addresses;
+—–+——–+—————+————-+———–+———-+———+
| ssn | name | address | city | state | postcode | country |
+—–+——–+—————+————-+———–+———-+———+
| 123 | Shrini | Kambar Street | Kanchipuram | TamilNadu | 600078 | India |
| 456 | Raji | Gandhi Street | Chennai | TamilNadu | 600062 | India |
+—–+——–+—————+————-+———–+———-+———+
2 rows in set (0.00 sec)
RESULT:
Thus the above program is verified and executed successfully.
31
EX. NO: 10
WRITE A PROGRAM USING STRING HANDLING AND
DATE: REGULAR EXPRESSIONS
32
CODING:
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)
SAMPLE INPUT/OUTPUT:
Enter an email address: [email protected]
The email '[email protected]' is valid.
Username: john.doe
Domain: example
Top-level Domain: com
33
Enter an email address: invalid_email
The email 'invalid_email' is not valid.
RESULT:
Thus the above program is verified and executed successfully.
34