PERIYAR UNIVERSITY , SALEM
KRISHNA ARTS AND SCIENCE COLLEGE, KATTINAYANAPALLI,
KRISHNAGIRI-635 001.
DEPARTMENT OF _________________________________________
NAME :________________________________________________
REG. NO :________________________________________________
CLASS :________________________________________________
SUBJECT :________________________________________________
NOVEMBER – 2023
KRISHNA ARTS AND SCIENCE COLLEGE, KATTINAYANAPALLI,
KRISHNAGIRI-635001.
CERTIFICATE
Title : _________________________________________________
Paper Code :_________________________________________________
Department:__________________________________________________
This is to certify that is a bonafide record of practical work done by
______________________________________ Reg.No. _________________of
______________________________________during the year 2023 – 2024.
Lecturer in Charge Head of the Department
Submit for the practical examination held on __________________ at
Krishna Arts and Science College, Kattinayanapalli, Krishnagiri – 635 001.
Internal External
INDEX
S.NO DATE TITLE PAGE NO.
Programs using elementary data items, lists, dictionaries,
and tuples depending upon user’s choice.
PROGRAM:
def perform_operations(data_structure):
if data_structure == 'elementary':
# Elementary data item (integer in this example)
number = int(input("Enter an integer: "))
print(f"You entered: {number}")
elif data_structure == 'list':
# List operations
my_list = []
while True:
print("\nList Operations:")
print("1. Add an element")
print("2. Remove an element")
print("3. Display the list")
print("4. Quit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
element = input("Enter the element to add: ")
my_list.append(element)
elif choice == 2:
element = input("Enter the element to remove: ")
if element in my_list:
my_list.remove(element)
else:
print("Element not found in the list.")
elif choice == 3:
print("List:", my_list)
elif choice == 4:
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
elif data_structure == 'dictionary':
# Dictionary operations
my_dict = {}
while True:
print("\nDictionary Operations:")
print("1. Add a key-value pair")
print("2. Remove a key-value pair")
print("3. Display the dictionary")
print("4. Quit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
key = input("Enter the key: ")
value = input("Enter the value: ")
my_dict[key] = value
elif choice == 2:
key = input("Enter the key to remove: ")
if key in my_dict:
del my_dict[key]
else:
print("Key not found in the dictionary.")
elif choice == 3:
print("Dictionary:", my_dict)
elif choice == 4:
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
elif data_structure == 'tuple':
# Tuple operations
my_tuple = tuple(input("Enter elements separated by commas: ").split(','))
print("Tuple:", my_tuple)
else:
print("Invalid choice. Please enter 'elementary', 'list', 'dictionary', or 'tuple'.")
if name == " main ":
user_choice = input("Enter the type of data structure (elementary, list, dictionary, tuple): ")
perform_operations(user_choice)
OUTPUT:
Enter the type of data structure (elementary, list, dictionary, tuple):
tuple Enter elements separated by commas: 4,6,7,8,9
Tuple: ('4', '6', '7', '8', '9')
RESULT:
Programs using conditional branches
2. Programs using conditional branches
PROGRAM:
# Function to check if a number is even or odd
def check_even_odd(num):
if num % 2 == 0:
return "even"
else:
return "odd"
# Input: Take a number as input
num = int(input("Enter a number: "))
# Check if the number is even or odd
result = check_even_odd(num)
# Output the result
print(f"The number {num} is {result}.")
OUTPUT:
Enter a number: 7
The number 7 is odd.
RESULT:
3. Programs using loops
Programs using loops
PROGRAM:
# Program 1: Sum of Numbers
n = int(input("Enter a number: "))
sum_result = 0
for i in range(1, n + 1):
sum_result += i
print(f"The sum of numbers from 1 to {n} is: {sum_result}")
OUTPUT:
Enter a number: 5
The sum of numbers from 1 to 5 is: 15
RESULT:
5. Programs using functions.
Programs using functions.
PROGRAM:
# Program: Calculate Area of a Circle using Functions
def calculate_area(radius):
"""
Calculate the area of a circle.
Formula: area = π * radius^2
"""
pi = 3.14159
area = pi * radius**2
return area
# Main program
radius = float(input("Enter the radius of the circle: "))
result = calculate_area(radius)
print(f"The area of the circle with radius {radius} is: {result}")
OUTPUT:
Enter the radius of the circle: 5
The area of the circle with radius 5.0 is: 78.53975
RESULT:
5. Programs using exception handling.
Programs using exception handling.
Program:
Read and Handle File I/O Errors
try:
filename = input("Enter the name of the file to read: ")
with open(filename, 'r') as file:
contents = file.read()
print(f"Contents of the file '{filename}':\n{contents}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except PermissionError:
print(f"Error: You don't have permission to access the file '{filename}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Enter the name of the file to read: non_existent_file.txt
Error: The file 'non_existent_file.txt' was not found.
RESULT:
6.Programs using inheritance
Programs using inheritance
Program:
import math
# Base class
class Shape:
def init (self, name):
self.name = name
def area(self):
pass
# Derived class 1
class Circle(Shape):
def init (self, name, radius):
super(). init (name)
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
# Derived class 2
class Rectangle(Shape):
def init (self, name, length, width):
super(). init (name)
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Function to calculate the total area of a list of shapes
def calculate_total_area(shapes):
total_area = 0
for shape in shapes:
total_area += shape.area()
return total_area
# Main program
if name == " main ":
# Creating instances of Circle and Rectangle
circle = Circle("Circle", 5)
rectangle = Rectangle("Rectangle", 4, 6)
# Displaying the area of each shape
print(f"Area of {circle.name}: {circle.area():.2f}")
print(f"Area of {rectangle.name}: {rectangle.area():.2f}")
# Creating a list of shapes and calculating the total area
shapes = [circle, rectangle]
total_area = calculate_total_area(shapes)
print(f"Total area of all shapes: {total_area:.2f}")
OUTPUT:
Area of Circle: 78.54
Area of Rectangle: 24.00
Total area of all shapes: 102.54
RESULT:
7. Programs using polymorphism.
Programs using polymorphism.
Program:
import math
# Base class
class Shape:
def init (self, name):
self.name = name
def area(self):
pass
# Derived class 1
class Circle(Shape):
def init (self, name, radius):
super(). init (name)
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
# Derived class 2
class Rectangle(Shape):
def init (self, name, length, width):
super(). init (name)
self.length = length
self.width = width
def area(self):
return self.length * self.width
# Function to calculate and print the area of each shape in a list
def print_areas(shapes):
for shape in shapes:
print(f"Area of {shape.name}: {shape.area():.2f}")
# Main program
if name == " main ":
# Creating instances of Circle and Rectangle
circle = Circle("Circle", 5)
rectangle = Rectangle("Rectangle", 4, 6)
# Creating a list of shapes
shapes = [circle, rectangle]
# Using polymorphism to calculate and print the area of each shape
print_areas(shapes)
Output:
Area of Circle: 78.54
Area of Rectangle: 24.00
RESULT:
8. Programs to implement file operations.
Programs to implement file operations.
Program:
# Appending to a file
file_path = "output.txt"
try:
with open(file_path, "a") as file:
content_to_append = "\nAppending more content to the file."
file.write(content_to_append)
print(f"Content appended to '{file_path}'.")
except Exception as e:
print(f"An error occurred: {str(e)}")
Output:
Content appended to 'output.txt'.
RESULT:
9.Programs using modules.
Programs using modules.
Program:
Module (bmi_calculator.py):
# bmi_calculator.py
def calculate_bmi(weight, height):
# BMI formula: weight (kg) / (height (m) ^ 2)
return weight / (height ** 2)
Main Program (main_program.py):
# main_program.py
import bmi_calculator
# Using the custom module to calculate BMI
weight = 70 # in kilograms
height = 1.75 # in meters
bmi = bmi_calculator.calculate_bmi(weight, height)
# Displaying the result
print(f"The BMI is: {bmi:.2f}")
Output:
The BMI is: 22.86
RESULT:
10.Programs for creating dynamic and interactive
web pages using forms.
Programs for creating dynamic and interactive
web pages using forms.
Program:
# app.py
from flask import Flask, render_template, request
app = Flask( name )
@app.route('/')
def index():
return render_template('index.html')
@app.route('/submit', methods=['POST'])
def submit():
name = request.form.get('name')
age = request.form.get('age')
return render_template('result.html', name=name, age=age)
if name == ' main ':
app.run(debug=True)
HTML
Index.Html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Web Page</title>
</head>
<body>
<h1>Dynamic Web Page</h1>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Result.Html
<!-- templates/result.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Result</title>
</head>
<body>
<h1>Result</h1>
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
<a href="/">Go back</a>
</body>
</html>
Output:
1. Save the provided Python code in the respective files (app.py,
templates/index.html, andtemplates/result.html).
2. Open a terminal or command prompt.
3. Navigate to the directory where the files are saved.
4. Run the Flask application by executing the command: python app.py.
RESULT: