III Cs Python PRG Final 19.03.2024-1
III Cs Python PRG Final 19.03.2024-1
TIRUCHENGODE – 637205
PRACTICAL RECORD
NAME :
REG. NO :
SEMESTER – VI
PERIYAR UNIVERSITY
2023-2024
SENGUNTHAR ARTS AND SCIENCE COLLEGE
(Affiliated to Periyar University, Salem And Approved by AICTE, New Delhi )
An ISO 9001:2015 Certified Institution
Recognised Under Section 2(f) and 12(B) of UGC Act 1956 and
Accredited by NAAC with A+
TIRUCHENGODE – 637205
CERTIFICATE
This is certifying that is a bonafide record of the practical work done
by.................................................................Reg.No...........................................................
Tiruchengode.
PAGE
S.NO DATE TITLE SIGN
NO
3
WRITE A PROGRAM TO USE FOR LOOP
7 EXCEPTION HANDLING
Aim:
To create a python program to calculate simple Arithmetic operations.
Algorithm:
Step 1: Start the program.
Step 2: Display the options for arithmetic operations: addition, subtraction,
Multiplication and division.
Step 3: Prompt the user to enter their choice (1/2/3/4) for the desired operation.
Step 4: Check if the user's choice is valid (in ('1', '2', '3', '4')).
Step 6: Display the result of the calculation.
Step 7: Stop the program.
Program:
Calculator.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 "Cannot divide by zero!"
return x / y
print("\t\tSIMPLE ARITHMETIC CALCULATOR")
print("\t\t**********************************")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
while True:
choice = input("Enter choice (1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
result = divide(num1, num2)
print(num1, "/", num2, "=", result)
else:
print("Invalid choice")
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No : 02 PROGRAM USING CONTROL FLOW TOOLS
Date : (PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER)
Aim:
To write a python program to find the factorial of a given number use control flow tools like if.
Algorithm:
Step 1: Start the program.
Step 2: Input a number n from the user.
Step 3: Initialize factorial to 1.
Step 4: If n is less than 0, print “Factorial doesn't exist for negative numbers” and exit.
Step 5: n is greater than 0, perform the following steps:
a. Print “factorial of n is:”.
b. Run a loop from 1 to n (inclusive).
c. In each iteration of the loop.
Step 6: Print the value of factorial.
Step 7: Stop the program
Program:
Fact.py
#Program using control flow tools like if:
#Factorial of a given number
print("PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER\n")
n=int(input("enter the number:"))
factorial=1
if n<0:
print("factorial doesn't exist for negativ enumber")
elif n==0:
print("for zero factorialis always one")
else:
print("Factorial of{}is:".format(n))
for i in range(1,n+1):
factorial=factorial*i
print(factorial)
Output:
PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER
Enter the number: 8
Factorial of 8 is: 40320
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No : 03 PROGRAM USING FOR LOOP
(PROGRAM TO PRINT THE MULTIPLICATION TABLE OF A
Date : GIVEN NUMBER)
Aim:
To write a python program to display Multiplication Table Program using for loop .
Algorithm:
Step 1: Start the program.
Step 2: Input a number n from the user.
Step 3: For each integer i from 1 to 20 .
Step 4: Multiply n by i and store the result in a variable x.
Step 5: Print the equation “ n * i = x ”.
Step 6: Stop the program.
Program:
Mul.py
#MULTIPLICATION TABLE PROGRAM
n=int(input("enter the number:"))
for i in range(1,21):
x=n*i
print("{} *{}= {}".format(n,i,x))
Output:
==============================
Enter the number: 8
8 *1= 8
8 *2= 16
8 *3= 24
8 *4= 32
8 *5= 40
8 *6= 48
8 *7= 56
8 *8= 64
8 *9= 72
8 *10= 80
8 *11= 88
8 *12= 96
8 *13= 104
8 *14= 112
8 *15= 120
8 *16= 128
8 *17= 136
8 *18= 144
8 *19= 152
8 *20= 160
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No : 04(A)
Date : PYTHON PROGRAM TO DEMONSTRATE STACK
IMPLEMENTATION USING LIST
Aim:
To write a python program to demonstrate stack implementation using list.
Algorithm:
Step 1: Start the Program.
Step 2: Initialize an empty list called stack. Print the initial state of the stack.
Step 3: Push elements onto the stack and Print the state of the stack after inserting elements.
a. Append elements to the end of the stack list using the append() method.
Step 4: Perform pop operations and Print the state of the stack after removing elements.
a. Remove the last item from the stack list using the pop() method.
Step 5: Stop the Program.
Program:
Stack.py
#Python code to demonstrate Implementing
# stack using list
stack=["SENGUNTHAR","ARTS","AND"]
print(stack)
stack.append("SCIENCE ")
stack.append("COLLEGE")
print("AfterInsertingelementstheStackis:")
print(stack)
print("StackPOPoperations:")
# Removes the last item
stack.pop()
print("AfterRemovinglastelementtheStackis:")
print(stack)
#Removes the last item
stack.pop()
print("AfterRemovinglastelementtheStackis:")
print(stack)
Output:
==============================
['SENGUNTHAR', 'ARTS', 'AND']
AfterInsertingelementstheStackis:
['SENGUNTHAR', 'ARTS', 'AND', 'SCIENCE ', 'COLLEGE']
StackPOPoperations:
AfterRemovinglastelementtheStackis:
['SENGUNTHAR', 'ARTS', 'AND', 'SCIENCE ']
AfterRemovinglastelementtheStackis:
['SENGUNTHAR', 'ARTS', 'AND']
Ex. No : 04(B)
Date : PYTHON PROGRAM TO DEMONSTRATE QUEUE
IMPLEMENTATION USING LIST
Aim:
To write a data python program to demonstrate queue implementation using list.
Algorithm:
Step 1: Start the Program.
Step 2: Add elements to the queue using the append() method:
Append "SENGUNTHAR" to the queue.
Append "ARTS" to the queue.
Append "AND" to the queue.
Append "SCIENCE" to the queue.
Append "COLLEGE" to the queue.
Step 3: Perform dequeue operation on the queue:
Step 4: Remove and print the first item in the queue using the pop(0) method.
Step 5: Print the final state of the queue.
Step 6: Stop the Program.
Program:
Queue.py
#Python code to demonstrate Implementing
# Queue using list
queue=["SENGUNTHAR","ARTS","AND"]
queue.append("SCIENCE ")
queue.append("COLLEGE")
print("Queue elements are:")
print(queue)
print("Deleted elements are:")
# Removes the first item
print(queue.pop(0))
print(queue)
# Removes the first item
print(queue.pop(0))
print("Queue elements are:")
print(queue)
Output:
==============================
= RESTART: D:/Queue.py
Queue elements are:
['SENGUNTHAR', 'ARTS', 'AND', 'SCIENCE ', 'COLLEGE']
Deleted elements are:
SENGUNTHAR
['ARTS', 'AND', 'SCIENCE ', 'COLLEGE']
ARTS
Queue elements are:
['AND', 'SCIENCE ', 'COLLEGE']
Ex. No : 04(C)
Date : PYTHON PROGRAM TO DEMONSTRATE TUPLE & SEQUENCE
IMPLEMENTATION
Aim:
To write a python program to Demonstrate Tuple & Sequence Implementation
Algorithm:
Step 1: Start the Program.
Step 2: Create a tuple tuple_1 containing three string elements: "PythonGeeks", "Sequences", and
Tutorial". Create an empty tuple tuple_2.
Step 3: Create a tuple tuple_3 containing different types of elements: an integer (2021), a tuple
("hello", 2020), and a float (2.0).
Step 4: Create a tuple tuple_4 containing a dictionary {'language': 'Python'} and a list [1, 2].
Step 5: Print all the tuples.
Step 6: Create a sequence using the range() function with a start value of 1, stop value of 10, and
step size of 2, and store it in the variable sequence.
Step 7: Iterate through the sequence using a loop. Print each element of the sequence.
Step 8: Stop the Program.
Program:
Tuple.py
print("Tuple creation in python")
tuple_1=("PythonGeeks","Sequences","Tutorial")
#[all string tuple]
print(f'tuple 1: {tuple_1}')
tuple_2=tuple()
#[empty tuple]
print(f'tuple 2: {tuple_2}')
tuple_3=[2021,('hello',2020),2.0]
#[integer,tuple, float]
print(f'tuple 3: {tuple_3}')
tuple_4=[{'language':'Python'},[1,2]]
#[dictionary,list]
print(f'tuple 4: {tuple_4}')
print("Exampleforsequences:")
sequence= range(1, 10, 2)
for i in sequence:
print(i)
Output:
=============================
Tuple creation in python
tuple 1: ('Python Geeks', 'Sequences', 'Tutorial')
tuple 2: ()
tuple 3: [2021, ('hello', 2020), 2.0]
tuple 4: [{'language': 'Python'}, [1, 2]]
Example for sequences:
1
3
5
7
9
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No :05 CREATION OF NEW MODULE FOR MATHEMATICAL OPERATIONS
Date :
Aim:
To write a python program to create new module for mathematical operations.
Algorithm:
Step 1: Start the program.
Step 2: Define a function addition, subtraction, multiplication (a,b): take two
parameter a and b return the product of a and b.
Step 3: Define a function division (a,b): Takes two parameters a (numerator) and b
(denominator) returns the result of dividing a by b.
Step 4: Import the Calci module.
Step 5: Print the result of addition, subtraction, multiplication and division.
Step 6: Calling the add(), sub(), mul() and div() function from the Calci module with
arguments 10 and 5.
Step 7: Stop the program.
Program:
Calci.py
#Module for arithmetic operations
def add(a, b):
return a + b
def sub(a, b):
return a-b
def mul(a,b):
return a *b
def div(a, b):
return a /b
Mathmod.py
import Calci
print("10+5={}".format(Calci.add(10, 5)))
print("10-5={}".format(Calci.sub(10,5)))
print("10*5={}".format(Calci.mul(10,5)))
print("10/5={}".format(Calci.div(10,5)))
Output:
==============================
10+5=15
10-5=5
10*5=50
10/5=2.0
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No : 06 CREATION AND DELETION OF NEW DIRECTORIES AND FILES
Date :
Aim:
To write a program to read and write files, create and delete directories.
Algorithm:
Step 1: Start the program.
Step 2: Import the os module.
Step 3: Use os.getcwd() to get the current working directory and store it in the variable path.
Step 4: Print the current working directory.
Step 5: Print the contents of the file.
Step 6: Run the process.
Step 7: Stop the program.
Program:
Dir.py
#import the os module
import os
#detectthecurrentworkingdirectory and print it
path = os.getcwd()
print("Thecurrentworkingdirectoryis%s" %path) # define the name of the directory to be created
path="D:/Temp"
try:
os.makedirs(path)
except OSError:
print ("Creationofthedirectory%sfailed"%path)
else:
print("Successfullycreatedthedirectory%s"%path)
with open("file.doc", "xt") as f:
f.write("ThisisaNewFile.JustCreated!")
f.close()
with open("file.doc","rt")as f:
data = f.read()
f.close()
print(data)
os.remove("file.doc")
os.rmdir(path)
Output:
==============================
ThecurrentworkingdirectoryisD:\Python Programs
SuccessfullycreatedthedirectoryD:/Temp
This is a New File .Just Created!
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No : 07 EXCEPTION HANDLING
Date :
Aim:
To write a python program with exception handling.
Algorithm:
Step 1: Start the program.
Step 2: Define a function fun(a) that takes one parameter a.
Step 3: Calculate the value of b using the formula b = a / (a - 3).
Step 4: Print the value of b.
Step 5: Using handle expression.
Step 6: Print the content.
Step 7: Stop the program.
Program:
Ex.py
def fun(a):
if a < 4:
b = a / (a - 3)
print("Value of b=", b)
try:
a = int(input("Enter a Number: "))
fun(a)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
finally:
print('This is always executed')
fun(2)
Output:
==============================
Value of b= -2.0
Enter a Number: 3
ZeroDivisionError Occurred and Handled
This is always executed
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No :08 PROGRAM USING CLASSES
Date :
Aim:
To write a python program using classes.
Algorithm:
Step 1: Start the program.
Step 2: Define a class Dog with:
Step 3: A class variable animal initialized to 'dog'.
Step 4: An initializer method _init_() to initialize instance variables breed and color.
Step 5: Create objects Rodger and Buzo of the Dog class with different breed and
color attributes.
Step 6: Access class variable animal using class name and print it.
Step 7: Stop the program.
Program:
Dog.py
animal = 'dog'
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
# Class variables can be accessed using class name also
print("\nAccessing class variable using class name")
print(Dog.animal)
Output:
==============================
Rodger details:
Rodger is a dog
Breed: Pug
Color: brown
Buzo details:
Buzo is a dog
Breed: Bulldog
Color: black
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No : 09 INSERT, UPDATE AND DELETE A RECORD IN TABLE OF A GIVEN
Date : DATABASE USING MYSQL SEVER
Aim:
To create table under database to perform sql operations using back end tool and front end tool.
Algorithm:
step 1: Start the process.
step 2: Create database using mysql server
step 3: Open msql workbench 8.0 ce
step 4: Create new connection (give connection name, user name ,password etc)
step 5: Create database schema (example emp_db_schema) using dialog window
step 6: Create table (example emp_table) under database schema
step 7: Create data fields in emp_table.
step 8: Using insert sql coding in python to insert record in a table.
step 9: Using update sql coding in python to update the record in a table.
step 10: Using delete sql coding in python to delete the record from the table.
step 11: To see the result through backend tool(mysql server),
step 12: Stop the process.
Program:
Open command prompt
c:users\aaasc>pip install mysql-connector-python
Python Editor ver 3.12.2 or 3.13
1.Program(Insert a record in emp_table)
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="root",
password="2021",
database="emp_db_schema"
)
mycursor = mydb.cursor()
sql = "insert into emp_table(emp_no,emp_name,salary)) values (%s, %s,%s)"
val = (100 ,"kumar", 5000.00)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Output
100 employee record is inserted in emp_table
1 record inserted
2.Program(update a record in emp_table)
import mysql.connector
mydb = mysql.connector.connect
(
host="127.0.0.1",
user="root",
password="2021",
database="emp_db_schema"
)
mycursor = mydb.cursor()
sql = "update emp_tabele set emp_name = 'sureshkumar' where emp_name = 'kumar'
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
Output
100 employee record is updated in emp_table
1 record affected
3. Program (Delete a record from emp_table)
import mysql.connector
mydb = mysql.connector.connect
(
host="127.0.0.1",
user="root",
password="2021",
database="emp_db_schema"
)
sql = "delete from emp_table where emp_no=100”
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
Output
100 employee number is removed from emp_table
1 record deleted
Result:
Thus the above python program is successfully executed and output is verified.
Ex. No :10 PROGRAM USING STRING HANDLING AND REGULAR EXPRESSIONS
Date :
Aim:
To write a python program using string handling and regular expressions.
Algorithm:
Step 1: Start the program.
Step 2: Import the re module for regular expressions.
Step 3: Print a message indicating the start of string handling using regular
expressions.
Step 4: Define a string txt as "The rain in Spain".
Step 5: Use regular expressions to perform the following operations:
a. Check if the string starts with "The" and ends with "Spain".
b. Find all lowercase characters alphabetically between "a" and "m".
c. Check if the string starts with "The".
d. Return a match at every white-space character.
e. Split the string at every white-space character.
f. Replace all white-space characters with the digit "9".
Step 6: Stop the program.
Program:
StringHandling.py
import re
print("\nSTRING HANDLING USING REGULAR EXPRESSIONS\n")
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
x = re.findall("[a-m]", txt)
print(x)
x = re.findall("\AThe", txt)
print(x)
if x:
print("Yes, there is a match!")
else:
print("No match")
x = re.findall("\s", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
x = re.split("\s", txt)
print(x)
==============================
= RESTART: D:/Python Programs/StringHandling.py
Result:
Thus the above python program is successfully executed and output is verified.