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

Python Labb

The document contains a series of programming exercises demonstrating various coding concepts in Python, including creating a simple calculator, using control flow tools, implementing loops, and utilizing data structures like lists and tuples. It also covers file handling, exception handling, class creation, and connecting to a MySQL database to manage an address book. Each exercise includes sample input/output and confirms successful execution of the code.

Uploaded by

priyacs104
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Labb

The document contains a series of programming exercises demonstrating various coding concepts in Python, including creating a simple calculator, using control flow tools, implementing loops, and utilizing data structures like lists and tuples. It also covers file handling, exception handling, class creation, and connecting to a MySQL database to manage an address book. Each exercise includes sample input/output and confirms successful execution of the code.

Uploaded by

priyacs104
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

EX.

NO: 01
CREATE A SIMPLE CALCULATOR TO DO ALL THE

DATE: ARITHMETIC OPERATIONS

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

SAMPLE INPUT / OUTPUT:


Simple Calculator
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter choice (1/2/3/4): 3
Enter first number: 4
Enter second number: 5
4.0 * 5.0 = 20.0

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

SAMPLE INPUT / OUTPUT:


Enter a number: -5
-5.0 is a negative number.

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

SAMPLE INPUT / OUTPUT:


Enter the value of n: 5
The sum of the first 5 natural numbers is: 15

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)

SAMPLE INPUT / OUTPUT:


Stack: [1, 2]
Popped Element: 3

B. USE LIST AS QUEUE


CODING:
# Using list as a queue
# Initialize an empty list as a queue
queue = []
# Enqueue elements
queue.append(1)

9
queue.append(2)
queue.append(3)
# Dequeue elements
dequeued_element = queue.pop(0)
# Output
print("Queue:", queue)
print("Dequeued Element:", dequeued_element)

SAMPLE INPUT / OUTPUT:


Queue: [2, 3]
Dequeued Element: 1

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

SAMPLE INPUT / OUTPUT:


Enter the first number: 10
Enter the second number: 5
Sum: 15.0
Difference: 5.0
Product: 50.0
Division: 2.0

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

SAMPLE INPUT / OUTPUT:


Enter the name of the file to read: sample.txt
File 'sample.txt' not found.

Enter the name of the file to write: new_file.txt


Enter the content to write to the file: This is a new file content.

Content successfully written to 'new_file.txt'.

Enter the name of the directory to create: new_directory


Directory 'new_directory' created successfully.

Enter the name of the directory to delete: new_directory


Directory 'new_directory' deleted successfully.

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

SAMPLE INPUT / OUTPUT:


Enter the numerator: 10
Enter the denominator: 2
Result of 10.0 / 2.0 = 5.0
Enter the numerator: 8
Enter the denominator: 0
Error: Cannot divide by zero.
Enter the numerator: abc
Error: Please enter valid numbers.

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

SAMPLE INPUT / OUTPUT:


Information about Book 1:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Publication Year: 1925

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:”)

newssn = raw_input(“Enter the new ssn number:”)


cursor.execute(“””
update addresses set ssn = %s
where ssn = %s”””,(newssn,ssn))
#Delete records
def Delete():
ssn = raw_input(“Enter the ssn record to be deleted:”)
cursor.execute(“””
delete from addresses
where ssn=%s”””,ssn)
#View Records
def List():
print ‘List the Records’
cursor.execute(“select * from addresses”)
result = cursor.fetchall()
for record in result:
print record[0],”–&gt;”,record[1],”–&gt;”,record[2],”–&gt;”,record[3],”–&gt;”,record[4]
def Exit():
sys.exit()
def printToConsole():
while True:
print ‘1.Add Record’
print ‘2.Modify Record’
print ‘3.Delete Record’
print ‘4.List Record’

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

Enter the State:TamilNadu


Enter the Postcode:600062
Enter the country:India
Add Another Record y/n
Enter the option:y
Enter SSN number:789
Enter a Name:Selvi
Enter the Address:ThenMada Street
Enter the City:Chennai
Enter the State:TamilNadu
Enter the Postcode:600089
Enter the country:India
Add Another Record y/n
Enter the option:n
1.Add Record
2.Modify Record
3.Delete Record
4.List Record
5.Exit

28
Enter the Option :4
List the Records
123 –&gt; Shrini –&gt; Kambar Street –&gt; Kanchipuram –&gt; TamilNadu –&gt; 600078 –
&gt; India
456 –&gt; Raji –&gt; Gandhi Street –&gt; Chennai –&gt; TamilNadu –&gt; 600062 –&gt; India
789 –&gt; Selvi –&gt; ThenMada Street –&gt; Chennai –&gt; TamilNadu –&gt; 600089 –&gt;
India
OUTPUT FROM MYSQL DATABASE:
mysql&gt; 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 |


| 789 | Selvi | ThenMada Street | Chennai | TamilNadu | 600089 | India |
+—–+——–+—————–+————-+———–+———-+———+
3 rows in set (0.00 sec)
OUTPUT FROM CONSOLE(MODIFY OPTION):
Enter the Option :2
Enter the old ssn number to update:789
Enter the new ssn number:101
1.Add Record
2.Modify Record
3.Delete Record
4.List Record
5.Exit
Enter the Option :4
List the Records

29
123 –&gt; Shrini –&gt; Kambar Street –&gt; Kanchipuram –&gt; TamilNadu –&gt; 600078 –
&gt; India
456 –&gt; Raji –&gt; Gandhi Street –&gt; Chennai –&gt; TamilNadu –&gt; 600062 –&gt; India
101 –&gt; Selvi –&gt; ThenMada Street –&gt; Chennai –&gt; TamilNadu –&gt; 600089 –&gt;
India (Modified data)
OUTPUT FROM MYSQL DATABASE(MODIFY OPTION):
mysql&gt; 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

Enter the ssn record to be deleted:101


1.Add Record
2.Modify Record
3.Delete Record
4.List Record
5.Exit
Enter the Option :4
List the Records
123 –&gt; Shrini –&gt; Kambar Street –&gt; Kanchipuram –&gt; TamilNadu –&gt; 600078 –
&gt; India
456 –&gt; Raji –&gt; Gandhi Street –&gt; Chennai –&gt; TamilNadu –&gt; 600062 –&gt; India

30
OUTPUT FROM MYSQL DATABASE(DELETE OPTION):
mysql&gt; 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

You might also like