PANIMALAR ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
(A CHRISITIAN MINORITY INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST
ACCREDITED BY NATIONAL BOARD OF ACCREDITATION(NBA)
AN ISO9001:2000 CERTIFIED INSTITUTION
Bangalore Trunk Road, Varadharajapuram, Nasarathpettai,
Poonamallee, Chennai – 600 123.
DEPARTMENT
OF
INFORMATION TECHNOLOGY
23ES1215-PYTHON PROGRAMMING
LABORATORY
I YEAR –II SEMESTER
Name :
Roll No : [Link]:
PANIMALAR ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
(A CHRISITIAN MINORITY INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST
ACCREDITED BY NATIONAL BOARD OF ACCREDITATION(NBA)
AN ISO9001:2000 CERTIFIED INSTITUTION
Bangalore Trunk Road, Varadharajapuram,
Nasarathpettai,Poonamallee, Chennai –600 123
DEPARTMENT
OF
INFORMATION TECHNOLOGY
BONAFIDE CERTIFICATE
This is a Certified Bonafide Record Book of Mr./Ms.
…..………………………… Register Number ..................................... Submitted
for Anna University Practical Examination held on........................... in 23ES1211
- Python Programming Laboratory during May-June 2025 .
Staff In-charge
Internal Examiner External Examiner
Table of Contents
Sl. Date Name of the Program Page Mark Faculty
No sign
A. Program To Compute Distance Between Two Points
Taking Input From The User
1.
B. Program To Perform Arithmetic Operations
Program To Demonstrate Different Number Data types
2.
In Python
Develop a python program to demonstrate various
3.
Conditional statements
4. Implement User Defined Functions Using Python
Demonstrate Built-in Functions
5.
Program To Perform Various String Operations Like
6.
Slicing, Indexing &Formatting
Develop Python Program To Perform Operation On List
7.
& Tuple
Demonstrate the concept to Dictionary with python
8.
program
9. Develop Python Program to Perform Operations on Sets
Develop For Python Codes To perform Matrix Addition
10.
and Subtraction and Transpose
Develop Python Codes To Demonstrate the Concept of
11.
Function Composition And Anonymous Functions
Demonstrate A Python Codes To Print Try, Except And
12.
Finally Block Statements
Implement Python Program To Perform File Operations
13.
A. Program To Handle And Raises A Value Error
Exception If The InputIs Not A Valid Integer
B. Program To Handle And Raise A File not found Error
Exception If The File Does Not Exist
14.
C. Program To Handles And Raise A Type Error
Exception If The Input Are Not Numerical
D. Program To Handles An Index error Except If The
Index Is Out Of Range
Develop A Python Programs Using Packages Numpy
15.
And Pandas
Develop a python program using tkinter
16.
Additional Program
1. Python Program To Find the Biggest of Three Numbers
Program to check the Given number is odd or
2. even
3. Python program to find the factorial of a number Using
While loop
Python program to find the factorial of a number Using
4.
For loop
5. Program to Print Reverse of A Number
Python Program To Check The Given Stings is
6.
Palindrome or not
7. Python Program to Check Given Number is Prime or Not
8. Program to Generate Fibonacci Series
9. Program for Floyds Triangle
10. Program for Bubble Sort
11. Program to Find Sum of ‘N’ Natural Numbers
12. Program Using Break and Continue Statement
13. Program to Find Leap Year or Not
14. Program to Find the Circumference of A Circle
EXNO:1 (A) PROGRAM TO COMPUTE DISTANCE BETWEEN TWO
POINTS TAKING INPUT FROM THE USER
Date:
Aim:
Algorithm:
Register Number: 211424205 Page |1
Program:
import math
a=int(input("enter a value:"))
b=int(input("enterb value:"))
c=int(input("enter c value:"))
d=int(input("enter d value:"))
distance = [Link](((a-c)**2)+((b-d)**2))
print("distance =",distance)
OUTPUT:
Result:
Register Number: 211424205 Page |2
EX NO 1(B) PROGRAM TO PERFORM ARITHMETIC OPERATIONS
Date:
Aim:
Algorithm:
Register Number: 211424205 Page |3
Program:
num1=float(input("please enter the first number 1:"))
num2=float(input("please enter the second number 2:"))
add=num1+num2
sub=num1-num2
multi=num1*num2
div=num1/num2
mod=num1%num2
expo=num1**num2
print(" sum=",add)
print("difference=",sub)
print("product=",multi)
print("quotient=",div)
print("remainder=",mod)
print("exponential value=",expo)
Output:
Result:
Register Number: 211424205 Page |4
EXNO:2 PROGRAM TO DEMONSTARTE DIFFERENT NUMBER DATATYPES
IN PYTHON
Date:
Aim:
Algorithm:
Register Number: 211424205 Page |5
Program:
#numbers x=20
print(x)
print(type(x))
x=20.5
print(x)
print(type(x))
x=1
print(x)
print(type(x))
#string
x="[Link]"
print(x)
print(type(x)) #list
x=["Go","Edu","Hub"]
print(x)
print(type(x)) #tuple
x=("Python","from","[Link]")
print(x)
print(type(x))
#boolean
x=True
print(x)
print(type(x))
x=b"Hello"
print(x)
print(type(x))
Output:
Result:
Register Number: 211424205 Page |6
EXNO:3 DEVELOP A PYTHON PROGRAM TO DEMONSTRATE VARIOUS
CONDITIONAL STAEMENTS
Date:
Aim:
Algorithm:
Register Number: 211424205 Page |7
Program:
#number is even or not
a=int(input())
if(a%2==0):
print("even")
else:
print("odd")
# Printing all prime numbers between an interval
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Result:
Register Number: 211424205 Page |8
EXNO:4 IMPLEMENT USER DEFINED FUNCTIONS USING PYTHON
Date:
Aim:
Algorithm:
Register Number: 211424205 Page |9
Program 1:
def plus(a,b):
sum=a+b
return(sum,a)
sum,a=plus(3,4)
print("the sum is",sum)
Output:
Program 2:
#Function to calculate the area of a circle
def area_of_circle(radius):
import math
return [Link]*radius**2
#Function to calculate the area of a rectangle
def area_of_rectangle(length,width):
return length*width
#Function to calculate the area of a circle
def area_of_triangle(base, height):
return 0.5*base*height
def main():
print("Choose the shape to calculate area: ")
print("[Link]")
print("[Link]")
print("[Link]")
choice=int(input("Enter the number corresponding to the shape:"))
if choice==1:
radius=float(input("Enter radius of the circle:"))
area=area_of_circle(radius)
print(f"The area of circle is:{area:.2f}")
elif choice==2:
length=float(input("Enter the length of the rectangle:"))
width=float(input("Enter the width of the rectangle:"))
area=area_of_rectangle(length,width)
print(f"The area of the rectangle is:{area:.2f}")
elif choice==3:
base=float(input("Enter the base of the triangle:"))
height=float(input("Enter the height of the triangle:"))
area=area_of_triangle(base,height)
print(f"The area of the traingle is:{area:.2f}")
else:
print("Invalid Choice. Please Select a valid shape")
main()
Register Number: 211424205 P a g e | 10
Output:
Choose the shape to calculate area:
[Link]
[Link]
[Link]
Enter the number corresponding to the shape:1
Enter radius of the circle: 5
Choose the shape to calculate area:
[Link]
[Link]
[Link]
Enter the number corresponding to the shape:2
Enter the length of the rectangle:4
Enter the width of the rectangle:6
The area of the rectangle is:24.00
The area of circle is: 78.54
Program 3:
#Calculator
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
if b==0:
return "Error! Division by Zero."
else:
return a/b
def main():
print("Simple Calculator")
num1=float(input("Enter the first number:"))
num2=float(input("Enter the second number:"))
print(f"{num1}+{num2}={add(num1,num2)}")
print(f"{num1}-{num2}={subtract(num1,num2)}")
print(f"{num1}*{num2}={multiply(num1,num2)}")
print(f"{num1}/{num2}={divide(num1,num2)}")
if__name__=="__main__":
main()
Output:
Simple Calculator
Enter the first number:12
Enter the second number:45
12.0+45.0=57.0
12.0-45.0=-33.0
12.0*45.0=540.0
Register Number: 211424205 P a g e | 11
12.0/45.0=0.26666666666666666
Result:
Register Number: 211424205 P a g e | 12
EXNO:5 DEMONSTRATE BUILT-IN FUNCTIONS
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 13
Program:
for i in range(10):
print(i,end="")
print()
l=[10,20,30,40]
for i in range(len(l)):
print(l[i],end=“ ”)
print()
sum=0
for i in range(1,11):
sum=sum+i
print("sum of first 10 natural numbers:",sum)
Output:
PROGRAMS
1. () Function: Returns the length of n object (e.g., string, list).
# Demonstrating len() function
my_string = "Hello, Python!"
my_list=[1, 2, 3, 4, 5]
#Printing the length of the string and the string and the list
print(f"Length of string: {len(my_string)}")
print(f"Length of list: {len(my_list)}")
Output
Length of string: 14
Length of list: 5
2. max() and min() Functions: Returns the maximum and minimum values from a sequence.
# Demonstrating max() and min() functions
numbers = [10, 20, 4, 45, 99]
print(f"Maximum value: (max(numbers)}")
print(f"Minimum value: {min(numbers)}")
Output:
Maximum value: 99
Minimum value: 4
Register Number: 211424205 P a g e | 14
3. sum() Function: Returns the sum of all elements in an iterable.
#Demonstrating sum() function numbers [1, 2, 3, 4, 5]
print("Sum of numbers: (sum(numbers)}")
Output:
Sum of numbers: 15
4. sorted() Function: Returns a sorted list of the specified iterable.
#Demonstrating sorted() function
my_list=[4, 1, 8, 2, 5]
sorted_list = sorted(my_list)
print(f'Original list: {my_list)")
print(f"Sorted list: (sorted_list}")
Output:
Original list: [4, 1, 8, 2, 5]
Sorted list: [1, 2, 4, 5, 8]
5. type() Function: Returns the type of an object.
#Demonstrating type() function
print(f"Type of 'Hello': {type('Hello')}")
print(f"Type of 42: {type(42))")
print(f"Type of [1, 2, 3]: {type([1, 2, 3])}")
Output:
Type of 'Hello': <class 'str'>
Type of 42: <class 'int'>
Type of [1, 2, 3]: <class 'list'>
6. abs() Function: Returns the absolute value of a number.
# Demonstrating abs() function
num = -5
print(f"Absolute value of (num): (abs(num)}")
Output:
Absolute value of -5: 5
7. input() Function: Reads a line of input from the user.
# Demonstrating input() function
user_name = input("Enter your name: ")
print(f"Hello, {user_name}!")
Output:
Enter your name: KUMAR
Hello, KUMAR!
8. round() Function: Rounds a floating point number to a specified number of decimal places.
#Demonstrating round() function
pi_value3.141592653589793
print(f"Rounded value of pi to 2 decimal places: {round(pi value, 2)}")
Register Number: 211424205 P a g e | 15
Output:
Rounded value of pi to 2 decimal places: 3.14
9. enumerate() Function: Adds a counter to an iterable and returns it as an enumerate object.
#Demonstrating enumerate() function
my list['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(f"Index (index): {value}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
10. all() and any() Functions: all() returns True if all elements in the iterable are true any() returns
True if any element in the iterable is true.
# Demonstrating all() and any() functions
my_list=[True, True, False]
print(f"All elements are True: {all(my_list)}")
print(f"Any element is True: {any(my_list)}")
Output:
All elements are True: False
Any element is True: True
Result :
Register Number: 211424205 P a g e | 16
EXNO:6 PROGRAM TO PERFORM VARIOUS STRING OPERATIONS LIKE SLICING,
INDEXING & FORMATTING
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 17
Program:
str="panimalar engineering college"
print("op of string slicing:")
print(str[3:18])
print(str[2:14:2])
print(str[ :8])
print(str[8:-1:1])
print(str[-9:-15])
print(str[0:9:3])
print(str[9: 29:2])
print(str[-6:-9:- 3])
print(str[-9:-9:-1])
print(str[8:25:3])
def remove_char(str,n):
first=str[:n]
last=str[n+1:]
return first+last
print("output indexing")
print(remove_char('python',0))
print(remove_char('python',3))
print(remove_char('python',5))
txt1="my name is {fname},I'm {age}".format(fname="john",age=36)
txt2="my name is {0},I'm {1}".format("john",36)
txt3="my name is{},I'm {}".format("john",36)
print(txt1)
print(txt2)
print(txt3)
Output:
Result:
Register Number: 211424205 P a g e | 18
EXNO: 7 DEVELOP PYTHON PROGRAM TO PERFORM OPERATION ON
LIST & TUPLE
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 19
Program:
list=[10,30,50,20,40]
tuple=(10,50,30,40,20)
print("length of list:",len(list))
print("length of tuple:",len(tuple))
print(" max of list:",max(list))
print( "max of tuple:",max(tuple))
print("min of list",min(list))
print("min of tuple",min(tuple))
print("sum of list",sum(list))
print("sum of tuple",sum(tuple))
print("list in sorted order",sorted(list))
print("tuple in sorted order",sorted(tuple))
Output:
Program 2: #List operations
my_list=[10,20,30,40,50]
print("Element at index 2:",my_list[2])
my_list.append(60)
print("List after append:",my_list)
my_list.insert(2,25)
print("List after insert:",my_list)
my_list.remove(40)
print("List after removing 40:",my_list)
popped_element=my_list.pop(3)
print(f"Popped element:{popped_element}")
print("List after pop:",my_list)
sliced_list=my_list[1:4]
print("SLiced List:",sliced_list)
print("Length of the list:",len(my_list))
new_list=my_list+[70,80,90]
print("List after concatenation:",new_list)
repeated_list=my_list*2
print("List after repeatition:",repeated_list)
is_present=30 in my_list
print("Is 30 in the list?",is_present)
my_list.sort()
print("Sorted List:",my_list)
Register Number: 211424205 P a g e | 20
Output:
Element at index 2: 30
List after append: [10, 20, 30, 40, 50, 60]
List after insert: [10, 20, 25, 30, 40, 50, 60]
List after removing 40: [10, 20, 25, 30, 50, 60]
Popped element:30
List after pop: [10, 20, 25, 50, 60]
SLiced List: [20, 25, 50]
Length of the list: 5
List after concatenation: [10, 20, 25, 50, 60, 70, 80, 90]
List after repeatition: [10, 20, 25, 50, 60, 10, 20, 25, 50, 60]
Is 30 in the list? False
Sorted List: [10, 20, 25, 50, 60]
Program 3:
my_tuple=(10,20,30,40,50)
print("Element at index 2:",my_tuple[2])
count_20=my_tuple.count(20)
print("Count of 20 in the tuple:",count_20)
index_of_30=my_tuple.index(30)
print("Index of 30 in the tuple:",index_of_30)
new_tuple=my_tuple+(70,80,90)
print("Tuple after concatenation:",new_tuple)
repeated_tuple=my_tuple*2
print("List after repeatition:",repeated_tuple)
print("Length of the tuple:",len(my_tuple))
is_present=30 in my_tuple
print("Is 30 in the tuple?",is_present)
sliced_tuple=my_tuple[1:4]
print("Sliced Tuple:",sliced_tuple)
nested_tuple=(1,(2,3),4)
print("Nested Tuple:",nested_tuple)
a,b,c,d,e=my_tuple
print("Tuple Unpacking:",a,b,c,d,e)
Output:
Element at index 2: 30
Count of 20 in the tuple: 1
Index of 30 in the tuple: 2
Tuple after concatenation: (10, 20, 30, 40, 50, 70, 80, 90)
List after repeatition: (10, 20, 30, 40, 50, 10, 20, 30, 40, 50)
Length of the tuple: 5
Is 30 in the tuple? True
Sliced Tuple: (20, 30, 40)
Nested Tuple: (1, (2, 3), 4)
Register Number: 211424205 P a g e | 21
Tuple Unpacking: 10 20 30 40 50
Result:
Register Number: 211424205 P a g e | 22
EXNO: 8 DEMONSTRATE THE CONCEPT OF DICTIONARY WITH
PYTHON PROGRAM
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 23
Program 1:
dict_a= {1: "India", 2: "USA", 3: "UK", 4: "Canada"}
print("Dictionary 'dict_a' is...")
print(dict_a)
print("Dictionary 'dict_a' keys...")
for x in dict_a:
print(x)
print("Dictionary 'dict_a' values...")
for x in dict_a.values():
print(x)
print("Dictionary 'dict_a' keys & values...")
for x, y in dict_a.items():
print(x, ":", y)
Output:
Dictionary 'dict_a' is...
{1: 'India', 2: 'USA', 3: 'UK', 4: 'Canada'}
Dictionary 'dict_a' keys...
1
2
3
4
Dictionary 'dict_a' values...
India
USA
UK
Canada
Dictionary 'dict_ PROGRAM 2:
a' keys & values...
1 : India
2 : USA
3 : UK
4 : Canada
Program 2:
#Define a dictionary
student = {
"name": "Alice",
"age": 22,
"department": "Computer Science",
"grades": [85, 90, 92]
}
# Accessing dictionary elements
print("Name:", student["name"])
print("Age:", student["age"])
print("Department:", student["department"])
print("Grades:", student["grades"])
#Adding a new key-value pair
Register Number: 211424205 P a g e | 24
student["graduation_year"] = 2024
print("\nAfter adding graduation year:", student)
#Updating an existing key
student["age"] = 23
print("\nAfter updating age:", student)
#Removing a key-value pair
del student["grades"]
print("\nAfter removing grades:", student)
# Iterating over the dictionary
print("\nIterating through the dictionary:")
for key, value in [Link]():
print(f"{key}: {value}")
#Checking if a key exists
if "department" in student:
print("\nThe key 'department' exists in the dictionary.")
#Get method to fetch a value with a default print("Hometown:", [Link]("hometown", "Not
specified"))
Output:
Name: Alice
Age: 22
Department: Computer Science
Grades: [85, 90, 92]
After adding graduation year: {'name': 'Alice', 'age': 22, 'department': 'Computer Science', 'grades': [85, 90,
92], 'graduation_year': 2024}
After updating age: {'name': 'Alice', 'age': 23, 'department': 'Computer Science', 'grades': [85, 90, 92],
'graduation_year': 2024}
After removing grades: {'name': 'Alice', 'age': 23, 'department': 'Computer Science', 'graduation_year': 2024}
Iterating through the dictionary:
name: Alice
age: 23
department: Computer Science
graduation_year: 2024
The key 'department' exists in the dictionary
Result:
Register Number: 211424205 P a g e | 25
EXNO: 9 DEMONSTRATE THE CONCEPT OF SET WITH PYTHON
PROGRAM
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 26
Program:
set1={1,2,3,4,5}
set2={4,5,6,7,8}
print("Set 1:",set1)
print("Set 2:",set2)
union_set=[Link](set2)
print("Union:",union_set)
intersection_set=[Link](set2)
print("Intersection:",intersection_set)
difference_set=[Link](set2)
print("Difference(Set 1- Set 2):",difference_set)
symmetric_difference_set=set1.symmetric_difference(set2)
print("Symmetric Difference:",symmetric_difference_set)
[Link](6)
print("Set 1 after adding 6:",set1)
[Link](8)
print("Set 2 after removing 8:",set2)
print("Is 3 in Set 1?",3 in set1)
print("Is 10 in Set 2?",10 in set2)
Output:
Set 1: {1, 2, 3, 4, 5}
Set 2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference(Set 1- Set 2): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Set 1 after adding 6: {1, 2, 3, 4, 5, 6}
Set 2 after removing 8: {4, 5, 6, 7}
Is 3 in Set 1? True
Is 10 in Set 2? False
Result:
Register Number: 211424205 P a g e | 27
Ex No: 10 PERFORM MATRIX OPERATIONS
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 28
Program:
MATRIX ADDITION AND SUBTRACTION
matrix1=[[1,2],[3,4]]
matrix2=[[4,5],[6,7]] print("printing
elements of first matrix:") for row in
matrix1: for element in row:
print(element,end="")
print() print("printing elements of second
matrix:") for row in matrix2: for elementin
row:
print(element,end="")
print() result1=[[0,0],[0,0]] for i in
range(len(matrix1)): for j in
range(len(matrix1[0])): result1[i][j]=
matrix1[i][j]+matrix2[i][j]
result=[[0,0],[0,0]] for i in
range(len(matrix1)): for j in
range(len(matrix1[0])): result[i][j]=
matrix1[i][j]-matrix2[i][j] print("subtraction
of two matrix") for row in result: for
element in row:
print(element,end="")
print() print("addition of two
matrix") for row in result1:
for element in row:
print(element,end="")
print()
Output:
MATRIX TRANSPOSE
Algorithm:
Register Number: 211424205 P a g e | 29
Program:
matrix1 = [[1, 2], [3, 4]]
print("Printing elements of first matrix:")
for row in matrix1:
for element in row:
print(element, end=" ")
print()
# Creating a result matrix with transposed dimensions
result = [[0, 0], [0, 0]]
# Performing the transpose
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result[j][i] = matrix1[i][j] # Notice: result[j][i] instead of result[i][j]
print("Transpose of matrix:")
for row in result:
for element in row:
print(element, end=" ")
print()
Output:
MATRIX DETERMINANT:
Algorithm:
Register Number: 211424205 P a g e | 30
Program :
def determinant_of_matrix(matrix):
a=matrix[0][0]
b=matrix[0][1]
c=matrix[1][0]
d=matrix[1][1]
determinant=(a*d)-(b*c)
return determinant
if_name=="main_":
matrix=[[1,2],[3,4]]
result=determinant_of_matrix(matrix)
print(f"The determinant of the matrix is:{result}")
Output:
The determinant of the matrix is:-2
Result:
Register Number: 211424205 P a g e | 31
EXNO: 11 DEVELOP PYTHON CODES TO DEMONSTRATE THE
CONCEPT OF COMPOSITION AND ANONYMOUS
FUNCTIONS
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 32
Program:1
def composite_function(f,g):
return lambda x:f(g(x)) def
add(x): return x+2 def
multiply(x): return x*2
add_multiply=composite_function(multiply,add)
print("result:",add_multiply(5))
Output:
Program:2
# Function composition using regular functions
def square(x):
return x ** 2
def increment(x):
return x + 1
def composed_function(x):
return square(increment(x))
# Testing function composition
print("Composed function (square(increment(3))):", composed_function(3))
# Function composition using anonymous (lambda) functions
increment_lambda = lambda x: x + 1
square_lambda = lambda x: x ** 2
composed_lambda = lambda x: square_lambda(increment_lambda(x))
# Testing the composed lambda function
print("Composed lambda (square(increment(3))):", composed_lambda(3))
# Another example with function composition
multiply_by_two = lambda x: x * 2
add_three = lambda x: x + 3
# Composing two lambda functions
composed_operation = lambda x: multiply_by_two(add_three(x))
# Testing composed operation
print("Composed operation (multiply_by_two(add_three(4))):", composed_operation(4))
Register Number: 211424205 P a g e | 33
Output:
Result:
Register Number: 211424205 P a g e | 34
EXNO:12 DEMONSTRATE A PYTHON CODES TO PRINT TRY, EXCEPT
AND FINALLY BLOCK STATEMENTS
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 35
Program 1:
try:
num1,num2= eval(input("enter 2 numbers,seperated by a comma:"))
result = num1/num2 print("result is",result) except
ZeroDivisionError:
print("division by zero is error!!") except SyntaxError: print(" comma is
missing. Enter numbers seperated by comma like this 1,2") except:
print("wrong input") else:
print("no exceptions") finally:
print("this will execute no matter what")
Output:
Program 2:
def divide_numbers(a, b):
try:
# Attempt to divide two numbers
print(f" Trying to divide {a} by {b}")
result = a / b
except ZeroDivisionError as e:
# Handle division by zero
print("Exception: Division by zero is not allowed.")
result = None
except TypeError as e:
# Handle invalid data types
print(f" Exception: Invalid data type encountered: {e}")
result = None
else:
# Executes if no exception occurs
print("Division successful!")
print(f" Result: {result}")
finally:
# Always executes regardless of an exception
print("Execution of the try-except block is complete.")
Register Number: 211424205 P a g e | 36
return result
def main():
divide_numbers(10, 2) # Valid input
print("\n")
divide_numbers(10, 0) # Division by zero
print("\n")
divide_numbers(10, "five") # Invalid data type
if __name__ == "__main__":
main()
Output:
Result:
Register Number: 211424205 P a g e | 37
EXNO:13 IMPLEMENT PYTHON PROGRAM TO PERFORM FILE
OPERATIONS
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 38
Program:
# Create a new file
my_file = open("D:\\[Link]", "x")
print("File created successfully.")
# Write to the file
with open("D:\\[Link]", 'w', encoding='utf-8') as f:
[Link]("My first file\n")
[Link]("This file\n")
[Link]("Contains 3 lines\n")
print("Successfully inserted.")
# Read the entire content
my_file = open("D:\\[Link]", "r", encoding='utf-8')
print(my_file.read())
my_file.close()
# Read specific number of characters
my_file = open("D:\\[Link]", "r", encoding='utf-8')
print("Readline (first 10 characters):")
print(my_file.readline(10))
my_file.close()
# Append to the file
with open("D:\\[Link]", 'a', encoding='utf-8') as f:
[Link]("Jaisakthi\n")
print("Successfully appended.")
Output:
Result:
Register Number: 211424205 P a g e | 39
EXNO:14 (A) PROGRAM TO HANDLE AND RAISES A VALUE ERROR
EXCEPTION IF THE INPUT IS NOT A VALID INTEGER
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 40
Program:
def get_integer_input(prompt):
try:
value=int(input(prompt))
return value except ValueError:
print("error:invalidinput,input an integer")
n=get_integer_input("input an integer:")
print("input value:",n)
Output:
Result:
Register Number: 211424205 P a g e | 41
EXNO:14 (B) PROGRAM TO HANDLE AND RAISE A FILE NOT FOUND ERROR
EXCEPTION IF THE FILE DOES NOT EXIST
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 42
Program:
def open_file(filename):
try:
file = open(filename, 'r')
contents = [Link]()
print("File contents:")
print(contents)
[Link]()
except FileNotFoundError:
print("Error: File not found")
file_name = input("Input a file name: ")
open_file(file_name)
Output:
Result:
Register Number: 211424205 P a g e | 43
EXNO:14 (C) PROGRAM TO HANDLES AND RAISE A TYPE ERROR EXCEPTION
IF THE INPUT ARE NOT NUMERICAL
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 44
Program:
def get_numeric_input(prompt):
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("Error: Invalid input, please input a valid number.")
n1 = get_numeric_input("Input first number: ")
n2 = get_numeric_input("Input second number: ")
result = n1 + n2
print("Sum of the said two numbers:", result)
Output:
Result:
Register Number: 211424205 P a g e | 45
EXNO:14(D) PROGRAM TO HANDLES AN INDEX ERROR EXCEPT IF THE
INDEX IS OUT OF RANGE
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 46
Program:
def testindex(data, index):
try:
result = data[index]
print("Result:", result)
except IndexError:
print("Error: Index out of range.")
nums = [1, 2, 3, 4, 5, 6, 7]
index = int(input("Input the index: "))
testindex(nums, index)
Output:
Result:
Register Number: 211424205 P a g e | 47
EXNO:15 DEVELOP A PYTHON PROGRAMS USING PACKAGES NUMPY AND
PANDAS
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 48
Program 1:
import numpy as np
import pandas as pd
# Creating a numpy array
numpyArray = [Link]([[5, 22, 3], [13, 24, 6]])
# Defining column labels
columns = ['x', 'y', 'z']
# Creating a pandas DataFrame
panda_df = [Link](data=numpyArray, index=["A", "B"], columns=columns)
print(panda_df)
Output:
Program 2:
import numpy as np
import pandas as pd
# Create a NumPy array with random data
data = [Link](10, 100, size=(10, 3)) # 10 rows, 3 columns
# Define columns
columns = ['Math', 'Science', 'English'] # Subjects
# Convert the NumPy array to a Pandas DataFrame
df = [Link](data, columns=columns)
# Add a new column for the total score
df['Total'] = df[['Math', 'Science', 'English']].sum(axis=1)
# Add a new column for the average score
df['Average'] = df[['Math', 'Science', 'English']].mean(axis=1)
# Display the DataFrame
print("Student Scores DataFrame:")
print(df)
print("\nSummary Statistics:") # Statistical Analysis
print([Link]())
# Filter: Students with an average score above 80
high_achievers = df[df['Average'] > 80]
print("\nStudents with Average Score > 80:")
print(high_achievers)
Register Number: 211424205 P a g e | 49
Output:
Student Scores DataFrame:
Math Science English Total Average
0 59 24 65 148 49.333333
1 88 29 77 194 64.666667
2 72 44 31 147 49.000000
...
9 55 66 58 179 59.666667
Summary Statistics:
Math Science English Total Average
count 10.00000 10.000000 10.000000 10.00000 10.000000
mean 64.50000 53.300000 54.100000 171.90000 57.300000
std 14.52282 20.558973 20.365203 31.05842 10.352807
min 43.00000 24.000000 31.000000 123.00000 41.000000
25% 55.75000 43.250000 44.750000 153.25000 51.083333
50% 64.50000 58.500000 55.000000 178.00000 59.666667
75% 73.25000 67.500000 65.750000 194.50000 64.666667
max 88.00000 83.000000 90.000000 250.00000 83.333333
Students with Average Score > 80:
Math Science English Total Average
4 88 83 90 261 87.000000
Result:
Register Number: 211424205 P a g e | 50
EXNO: 16 DEVELOP PYTHON PROGRAMS USING TKINTER
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 51
Program:
import tkinter as tk
master = [Link]()
[Link]("MARKSHEET")
[Link]("700x400")
# Entry fields for input
e1 = [Link](master)
e2 = [Link](master)
e3 = [Link](master)
e4 = [Link](master)
e5 = [Link](master)
e6 = [Link](master)
e7 = [Link](master)
def display():
tot = 0
# Assigning grades to marks
grade_mapping = {"A": 40, "B": 36, "C": 32, "D": 28, "P": 24, "F": 0}
# Calculate total based on entered grades for each subject
for idx, entry in enumerate([e4, e5, e6, e7], start=3):
grade = [Link]()
if grade in grade_mapping:
mark = grade_mapping[grade]
[Link](master, text=str(mark)).grid(row=idx, column=4)
tot += mark
else:
[Link](master, text="Invalid Grade").grid(row=idx, column=4)
# Display total marks and SGPA
[Link](master, text="Total Marks").grid(row=7, column=3)
[Link](master, text=str(tot)).grid(row=7, column=4)
[Link](master, text="SGPA").grid(row=8, column=3)
[Link](master, text=str(round(tot/15, 2))).grid(row=8, column=4) # rounded to 2 decimals
# Labels and grid layout
[Link](master, text="Name").grid(row=0, column=0)
[Link](master, text="Reg. No").grid(row=0, column=3)
[Link](master, text="Roll. No").grid(row=1, column=0)
[Link](master, text="Srl No").grid(row=2, column=0)
[Link](master, text="1").grid(row=3, column=0)
[Link](master, text="2").grid(row=4, column=0)
[Link](master, text="3").grid(row=5, column=0)
[Link](master, text="4").grid(row=6, column=0)
[Link](master, text="Subject").grid(row=2, column=1)
[Link](master, text="PYTHON").grid(row=3, column=1)
[Link](master, text="JAVA").grid(row=4, column=1)
[Link](master, text="HTML").grid(row=5, column=1)
[Link](master, text="OOPS").grid(row=6, column=1)
[Link](master, text="Grade").grid(row=2, column=2)
[Link](row=3, column=2)
[Link](row=4, column=2)
[Link](row=5, column=2)
[Link](row=6, column=2)
[Link](master, text="Sub Credit").grid(row=2, column=3)
Register Number: 211424205 P a g e | 52
[Link](master, text="4").grid(row=3, column=3)
[Link](master, text="4").grid(row=4, column=3)
[Link](master, text="3").grid(row=5, column=3)
[Link](master, text="4").grid(row=6, column=3)
[Link](master, text="Credit Obtained").grid(row=2, column=4)
# Name, Reg, Roll number entries
[Link](row=0, column=1)
[Link](row=0, column=4)
[Link](row=1, column=1)
# Submit button to calculate the result
button1 = [Link](master, text="Submit", bg="green", command=display)
[Link](row=8, column=1)
[Link]()
Output:
Result:
Register Number: 211424205 P a g e | 53
Additional Programs
[Link]:A 1. Program To find the Biggest of the The Numbers
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 54
Program:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if num1 >= num2 and num1 >= num3:
biggest = num1
elif num2 >= num1 and num2 >= num3:
biggest = num2
else:
biggest = num3
print(f"The biggest number is: {biggest}")
Output:
Enter first number: 45
Enter second number: 67
Enter third number: 12
The biggest number is: 67.0
Result:
Register Number: 211424205 P a g e | 55
[Link]:A2. Program to Check the Given Number is Odd or Even
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 56
Program:
num = int(input("Enter any number to test whether it is odd or even:"))
if (num % 2) == 0:
print ("The number is even")
else:
print ("The provided number is odd")
Output:
Result:
Register Number: 211424205 P a g e | 57
EX NO:A3. Program to Find Factorial of a Number Using While Loop
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 58
Program:
num = int(input("Enter a number: "))
if num < 0:
print("Factorial doesn't exist for negative numbers, dude!")
elif num == 0:
print("The factorial of 0 is 1.")
else:
factorial = 1
temp = num
while temp > 0:
factorial *= temp
temp -= 1
print(f"The factorial of {num} is {factorial}.")
Output:
Enter a number: 5
The factorial of 5 is 120.
Result:
Register Number: 211424205 P a g e | 59
EX NO: A 4. Program to Find Factorial of a Number Using For Loop
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 60
Program:
num = int(input("Enter a number: "))
fact = 1
if num < 0:
print("Factorial doesn't exist for negative numbers, dude!")
elif num == 0:
print("The factorial of 0 is 1.")
else:
for i in range(1, num + 1):
fact *= i # fact = fact * i at every step
print(f"The factorial of {num} is {fact}.")
Output:
Enter a number: 4
The factorial of 4 is 24.
Result:
Register Number: 211424205 P a g e | 61
EX NO: A5. Program to Print Reverse of A Number
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 62
Program:
num = int(input("Enter a number: "))
Reverse = 0
while num > 0:
Remainder = num % 10
Reverse = (Reverse * 10) + Remainder
num = num // 10
print(f"The reversed number is: {Reverse}")
Output:
Enter a number: 1234
The reversed number is: 4321
Result:
Register Number: 211424205 P a g e | 63
EX NO:A6. Python Program To Check The Given Stings is Palindrome or Not
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 64
Program:
def is_palindrome(n):
index = 0
while index < len(n) // 2:
if n[index] != n[-1 - index]:
return False
index += 1
return True
n = input("Enter a string: ")
if is_palindrome(n):
print("The given string is a Palindrome.")
else:
print("The given string is NOT a Palindrome.")
Output:
Enter a string: racecar
The given string is a Palindrome.
Result:
Register Number: 211424205 P a g e | 65
EX NO: A7. Program to Check Given Number is Prime or Not
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 66
Program:
def PrimeChecker(a):
if a > 1:
for j in range(2, int(a/2) + 1):
if (a % j) == 0:
print(a, "is not a prime number")
break
else:
print(a, "is a prime number")
else:
print(a, "is not a prime number")
a = int(input("Enter an input number: "))
PrimeChecker(a)
Output:
Result:
Register Number: 211424205 P a g e | 67
[Link]: A8. Program To Generate Fibonacci Series
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 68
Program:
# Program for Fibonacci series
rangel = int(input("Enter the number of elements of the series: "))
n1 = 0
n2 = 1
if rangel <= 0:
print("Enter a positive integer..")
elif rangel == 1:
print("Fibonacci series up to", rangel, ":")
print(n1)
else:
print("Fibonacci series up to", rangel, ":")
print(n1)
print(n2)
i=2
while i < rangel:
n3 = n1 + n2
print(n3)
n1 = n2
n2 = n3
i += 1
Output:
Result:
Register Number: 211424205 P a g e | 69
[Link]: A9. Program For Floyds Triangle
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 70
Program:
# Program for Floyd's Triangle
count = 0
for i in range(1, 6): # Rows of Floyd's triangle
for i in range(1, i + 1): # Elements in each row
count += 1
print(count, end=" ")
print() # Newline after each row
Output:
Result:
Register Number: 211424205 P a g e | 71
[Link]: A10. Program For Bubble Sort
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 72
Program:
# Program for Bubble Sort
def bubbleSort(nlist):
for passnum in range(len(nlist) - 1, 0, -1):
for i in range(passnum):
if nlist[i] > nlist[i + 1]:
# Swap the elements
temp = nlist[i]
nlist[i] = nlist[i + 1]
nlist[i + 1] = temp
# List to be sorted
nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
# Sorting the list
bubbleSort(nlist)
# Print the sorted list
print("Sorted list is:", nlist)
Output:
Result:
Register Number: 211424205 P a g e | 73
[Link]: A11. Program To Find Sum Of ‘N’ Natural Numbers
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 74
Program:
# Python program to find the sum of natural numbers up to n
# Change this value for a different result
num = 18
# Uncomment the line below to take input from the user
# num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# Use while loop to iterate until zero
while num > 0:
sum += num
num -= 1
print("The sum is", sum)
Output:
Result:
Register Number: 211424205 P a g e | 75
[Link]: A12 . Program Using Break And Continue Statements
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 76
Program:
# Break Statement
number = 0
for number in range(10):
number = number + 1
if number == 5:
break # Breaks the loop when number equals 5
print('Number is ' + str(number))
print('Out of loop (break section)\n')
# Continue Statement
number = 0
for number in range(10):
number = number + 1
if number == 5:
continue # Skips the rest of the loop when number equals 5
print('Number is ' + str(number))
print('Out of loop (continue section)')
Output:
Result
Register Number: 211424205 P a g e | 77
[Link]:[Link] To Find Leap Year Or Not
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 78
Program:
# Python program to check if a year is a leap year
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:
Result:
Register Number: 211424205 P a g e | 79
[Link]:[Link] To Find The Area And Circumference Of A Circle
Date:
Aim:
Algorithm:
Register Number: 211424205 P a g e | 80
Program:
import math
# Function to calculate area and circumference
def circle_properties(radius):
# Calculate area and circumference
area = [Link] * (radius ** 2)
circumference = 2 * [Link] * radius
return area, circumference
# Input radius from user
radius = float(input("Enter the radius of the circle: "))
# Get area and circumference
area, circumference = circle_properties(radius)
# Display the results
print(f"The area of the circle is: {area:.2f}")
print(f"The circumference of the circle is: {circumference:.2f}")
Output:
Result:
Register Number: 211424205 P a g e | 81