Python Programming Lab Record 2025-26
Python Programming Lab Record 2025-26
LABORATORY RECORD
2025-2026
NAME : ………………………………………………
[Link] : ………………………………………………
BRANCH : …………………………...…………………
BONAFIDE CERTIFICATE
PAGE FACULTY
[Link] DATE NAME OF THE EXPERIMENT NUMBER MARK SIGNATURE
EX. NO:
DATE : SWAPPING VALUES OF TWO VARIABLES
AIM :
ALGORITHM :
Two numbers (a, b) 1. Store value of ‘a’ in temp Values of variables after
2. Assign value of ‘b’ to ‘a’ swapping
3. Assign value of ‘temp’ to
‘b’
SOURCE CODE :
RESULT:
Thus the Python program for swapping two variables was executed successfully.
EX. NO :
DATE : SUM OF TWO NUMBERS
AIM:
To write a program for find the sum of two numbers using python.
ALGORITHM:
Two numbers (a, b) Add the two numbers using the Display the result of the
addition operator (+) addition
c = a + b
SOURCE CODE:
RESULT:
Thus the Sum of two numbers program has been written and executed successfully.
[Link] :
DATE : EVEN OR ODD NUMBER
AIM:
To write a program to find the given number is even or odd using python.
ALGORITHM:
A number entered by the user(a) - Find the remainder when the Displays whether the number is
number is divided by 2 even or odd
- If remainder = 0 → number is
Even
- Else → number is Odd
SOURCE CODE:
RESULT:
Thus the program to find the given number even or odd has been written and executed
Successfully.
EX. NO :
GREATEST OF THREE NUMBERS
DATE :
AIM:
To write a program to find the greatest of three number using python.
ALGORITHM:
Three numbers (e.g., a, b, c) Compare the three numbers using Displays the greatest number
entered by the user conditional statements: among the three
• If a ≥ b and a ≥ c, then a is
greatest
• Else if b ≥ a and b ≥ c, then b
is greatest
• Else, c is greatest
SOURCE CODE:
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))
if a > b and a > c:
print("%d is Greatest" % a)
elif b > a and b > c:
print("%d is Greatest" % b)
else:
print("%d is Greatest" % c)
.
OUTPUT:
RESULT:
Thus the program to find the greatest of three numbers has been written and executed successfully.
EX. NO :
DATE : FIBONACCI SERIES
AIM:
To write a Python program to find the Fibonacci series of a number
ALGORITHM:
Number of terms (nterms) 1. If nterms <= 0, print an error Fibonacci series up to the
entered by the user message. entered number of terms
2. If nterms == 1, print only the
first term (0).
3. Else, initialize n1 = 0, n2 = 1,
and use a while loop to generate
the next Fibonacci term (nth =
n1 + n2).
4. Update n1 and n2 in each
iteration and print the sequence
until count < nterms.
SOURCE CODE:
RESULT:
Thus the Fibonacci series program in Python is written and executed successfully.
EX. NO:
DATE : FIRST N PRIME NUMBER
AIM:
To write a program to find the first N Prime number using python.
ALGORITHM:
i=1
while i <= x:
c=0
if i % j == 0:
c += 1
if c == 2:
print(i)
i += 1
OUTPUT:
11
13
17
19
23
29
31
37
41
43
47
RESULT:
Thus the Program to find first N prime number is written and executed successfully.
EX. NO :
FACTORIAL OF A NUMBER USING RECURSION
DATE :
AIM:
To write a program to find the factorial of a number using recursion in python.
ALGORITHM:
Step 1: Start the program.
A positive integer (n) Recursive Process: The factorial value of the given
- If n <= 1, return 1 (base case) number
- Else, return n * factorial(n
- 1)
- Function keeps calling itself until
the base case is reached
SOURCE CODE:
def factorial(n):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print(factorial(n))
OUTPUT:
Enter number: 7
Factorial of 7 is:
5040
RESULT:
Thus the Program to find factorial of a number using recursion has been written and executed
successfully.
.
[Link] :
SCIENTIFIC CALCULATOR
DATE :
AIM:
To write a program to design a scientific calculator using switch-case logic (match-case).
ALGORITHM:
Step 1: Start the program.
Step 5: Use a match–case statement to perform the operation based on the user’s choice:
Case 1:
o Input two numbers a and b.
o Compute result = a + b.
o Display the result.
Case 2:
o Input two numbers a and b.
o Compute result = a - b.
o Display the result.
Case 3:
o Input two numbers a and b.
o Compute result = a * b.
o Display the result.
Case 4:
o Input two numbers a (numerator) and b (denominator).
o If b!= 0, compute result = a / b.
o Else, display an error message (“Division by zero not allowed”).
Case 5:
o Input a number a.
o If a >= 0, compute result = sqrt(a) using [Link]().
o Else, display an error message (“Square root of negative number is not real”).
Case 6:
o Input base and exponent.
o Compute result = [Link](base, exponent).
o Display the result.
Case 7:
o Input angle in degrees.
o Convert it to radians using [Link](angle).
o Compute and display sin, cos, and tan using respective math functions.
Case 8:
o Input a number a.
o If a > 0, compute result = [Link](a).
o Else, display an error message (“Logarithm undefined for non-positive numbers”).
import math
print("Scientific Calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Square Root")
print("6. Power")
print("7. Trigonometric Functions (sin, cos, tan)")
print("8. Logarithm")
case 2:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result =", a - b)
case 3:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result =", a * b)
case 4:
a = float(input("Enter numerator: "))
b = float(input("Enter denominator: "))
if b != 0:
print("Result =", a / b)
else:
print("Error! Division by zero not allowed.")
case 5:
a = float(input("Enter number: "))
if a >= 0:
print("Square Root =", [Link](a))
else:
print("Error! Square root of negative number is not real.")
case 6:
base = float(input("Enter base: "))
exp = float(input("Enter exponent: "))
print("Result =", [Link](base, exp))
case 7:
angle = float(input("Enter angle in degrees: "))
rad = [Link](angle)
print("sin =", [Link](rad))
print("cos =", [Link](rad))
print("tan =", [Link](rad))
case 8:
a = float(input("Enter number (>0): "))
if a > 0:
print("Logarithm =", [Link](a))
else:
print("Error! Logarithm undefined for non-positive numbers.")
case _:
print("Invalid choice!")
OUTPUT:
Scientific Calculator
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square Root
6. Power
7. Trigonometric Functions (sin, cos, tan)
8. Logarithm
Enter your choice (1-8): 5
Enter number: 86
Square Root = 9.273618495495704
Scientific Calculator
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square Root
6. Power
7. Trigonometric Functions (sin, cos, tan)
8. Logarithm
Enter your choice (1-8): 7
Enter angle in degrees: 30
sin = 0.49999999999999994
cos = 0.8660254037844387
tan = 0.5773502691896257
RESULT:
Thus program to design a scientific calculator using switch-case (match-case) was successfully written and
executed.
.
EX. NO:
SWAPPING TWO NUMBERS USING CALL BY VALUE
DATE : AND CALL BY REFERENCE
AIM:
To write a program to swap two numbers using Call by Value and Call by Reference.
ALGORITHM:
Read two numbers from -Define swap_val(a, b) Show that original values are
user(x,y) -Swap using temporary variable changed
- Define swap_ref(lst)
- Inside swap_ref, swap and
print new list values
SOURCE CODE
RESULT:
Thus the program demonstrates the difference between Call by Value and Call by Reference is written and executed
successfully.
.
[Link]:
AIM:
To write a program to generate Pascal’s Triangle using functions.
.
ALGORITHM:
Read number of rows from - Define factorial(n) function to Display Pascal’s Triangle
user (rows) find factorial recursively pattern with computed values
• Define nCr(n, r) function to
calculate combination using
factorials
• Define
pascal_triangle(rows)
function
• Use nested loops to compute and
print values using nCr(i, j) for
each row
SOURCE CODE:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
def pascal_triangle(rows):
for i in range(rows):
# Main Program
pascal_triangle(rows)
OUTPUT:
Enter number of rows: 10
11
121
1331
14641
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
RESULT:
Thus the Program to generates Pascal’s Triangle is written and executed successfully
EX. NO:
AIM:
To write a program to perform various string manipulation operations in Python using different string
functions and techniques.
ALGORITHM:
1. Start
2. Accept a string input from the user.
3. Perform basic operations:
o Access characters using indexing.
o Extract substrings using slicing.
o Concatenate and repeat strings.
4. Perform string functions:
o Convert to upper/lower case, title case.
o Strip spaces.
o Replace substrings.
5. Search and count specific characters or substrings.
6. Split the string into a list and join it back.
7. Check content (alphabetic, numeric, alphanumeric, whitespace).
8. Display all results.
9. End
Read a string from the user Access characters using indexing Display first, last, and sliced
( s) and slicing (s[0], s[-1], s[1:5]) characters
• Perform concatenation (s + " • Show concatenated and
Python") and repetition (s * 2) repeated strings
• Apply string functions: upper(), • Display results of string
lower(), title(), strip(), functions and transformations
replace() • Show positions/counts of
• Use search and count functions: characters
find(), count() • Display split and joined strings
• Apply split() and join() for word • Show Boolean results for
manipulation string property checks
• Check string properties:
isalpha(), isdigit(),
isalnum(), isspace()
SOURCE CODE:
# Input string
s = input("Enter a string: ")
# String functions
print("Upper case:", [Link]())
print("Lower case:", [Link]())
print("Title case:", [Link]())
print("Strip spaces:", [Link]())
print("Replace:", [Link]("Python", "Java"))
# Checking content
print("Is alphabetic?", [Link]())
print("Is numeric?", [Link]())
print("Is alphanumeric?", [Link]())
print("Is space?", [Link]())
OUTPUT:
Enter a string: HelloPython1234
First character: H
Last character: 4
Repetition: HelloPython1234HelloPython1234
Find 'a': -1
Count 'a': 0
Is alphabetic? False
Is numeric? False
Is alphanumeric? True
Is space? False
RESULT:
Thus, the various string manipulation techniques in Python, such as indexing, slicing, concatenation,
repetition, searching, replacing, and checking successfully.
EX. NO:
DATE:
LIST OPERATIONS
AIM:
To write a Python program to perform various list manipulation operations at runtime using built-in list
functions.
ALGORITHM:
1. Start
2. Create a list or accept list input from the user.
3. Access elements using indexing and slicing.
4. Add elements using append(), insert(), or extend().
5. Remove elements using remove(), pop(), or del.
6. Update elements by assigning new values to specific indices.
7. Perform operations:
o Sort the list using sort()
o Reverse the list using reverse()
o Search for an element using index() or in
8. Display results after each operation.
9. End
my_list.insert(index, value)
my_list.extend(extra_elements)
# Removing an element
if remove_value in my_list:
my_list.remove(remove_value)
else:
popped = my_list.pop()
del my_list[del_index]
print("Invalid index!")
# Updating an element
my_list[update_index] = new_value
else:
print("Invalid index!")
my_list.sort()
my_list.reverse()
if search_value in my_list:
else:
# Membership check
After insert: [90, 40, 20, 10, 50, 20, 80, 30]
After extend: [90, 40, 20, 10, 50, 20, 80, 30, 70, 60, 100]
After remove: [90, 40, 10, 50, 20, 80, 30, 70, 60, 100]
After pop: [90, 40, 10, 50, 20, 80, 30, 70, 60] | Popped element: 100
After delete: [40, 10, 50, 20, 80, 30, 70, 60]
After update: [40, 10, 50, 20, 85, 30, 70, 60]
After sorting: [10, 20, 30, 40, 50, 60, 70, 85]
After reversing: [85, 70, 60, 50, 40, 30, 20, 10]
Is 30 in list? True
RESULT:
DATE:
TUPLE OPERATIONS
AIM:
To write a Python program to perform various Tuple operations at runtime using built-in list functions.
ALGORITHM:
1. Start
2. Create a tuple or accept tuple input from the user.
3. Access elements using indexing and slicing.
4. Concatenate or repeat tuples as needed.
5. Use built-in functions:
o len() to get the number of elements
o count() to count occurrences of an element
o index() to find the position of an element
6. Display results after each operation.
7. End
Enter tuple elements - Create a tuple from user input. Display the original tuple.
-Access first, last, and sliced elements • Display selected elements
using indexing and slicing. • Show concatenated and repeated
-Concatenate and repeat tuples. tuples
-Find the length of the tuple using len(). • Display length of tuple
-Use count() to find occurrences • Display count of the entered
-Use index() to find position value.
• Display index or “value not
found” message
SOURCE CODE:
# Tuple functions
print("Length of tuple:", len(my_tuple))
value_to_count = int(input("Enter a value to count: "))
print(f"Count of {value_to_count}:", my_tuple.count(value_to_count))
value_to_find = int(input("Enter a value to find its index: "))
if value_to_find in my_tuple:
print(f"Index of {value_to_find}:", my_tuple.index(value_to_find))
else:
print(f"{value_to_find} not found in the tuple!")
OUTPUT:
First element: 65
Last element: 35
Concatenated Tuple: (65, 15, 75, 85, 35, 105, 115, 145)
Repeated Tuple: (65, 15, 75, 85, 35, 65, 15, 75, 85, 35)
Length of tuple: 5
Count of 105: 0
Index of 75: 2
RESULT:
DATE:
SET OPERATIONS
AIM:
To write a Python program to perform various set operations at runtime using built-in list functions.
ALGORITHM:
1. Start
2. Create sets or accept set input from the user.
3. Add elements using add() or update().
4. Remove elements using remove(), discard(), or pop().
5. Perform set operations:
o Union (| or union())
o Intersection (& or intersection())
o Difference (- or difference())
o Symmetric Difference (^ or symmetric_difference())
6. Check membership using in or not in.
7. Display results after each operation.
8. End
Elements of Set1 and 1. Create two sets from user input. Displays results of all operations
Set2 entered by the 2. Add and update elements in Set1. on the sets.
user. 3. Remove or discard elements.
4. Perform pop operation.
5. Display union, intersection, difference,
and symmetric difference.
6. Check membership of an element in the
sets.
SOURCE CODE:
# Creating sets at runtime
set1 = set(map(int, input("Enter elements for Set1 (separated by spaces): ").split()))
set2 = set(map(int, input("Enter elements for Set2 (separated by spaces): ").split()))
print("Set1:", set1)
print("Set2:", set2)
# Adding elements
value_to_add = int(input("Enter a value to add to Set1: "))
[Link](value_to_add)
print("After add:", set1)
values_to_update = list(map(int, input("Enter multiple values to update Set1 (separated by spaces):
").split()))
[Link](values_to_update)
print("After update:", set1)
# Removing elements
value_to_remove = int(input("Enter a value to remove from Set1: "))
try:
[Link](value_to_remove)
except KeyError:
print(f"{value_to_remove} not found in Set1")
value_to_discard = int(input("Enter a value to discard from Set1: "))
[Link](value_to_discard)
print("After removing/discarding:", set1)
# Pop operation
if set1:
popped = [Link]()
print("After pop:", set1, "| Popped element:", popped)
else:
print("Set1 is empty, cannot pop.")
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference (Set1 - Set2):", set1 - set2)
print("Symmetric Difference:", set1 ^ set2)
# Membership checking
value_check = int(input("Enter a value to check in Set1: "))
print(f"Is {value_check} in Set1?", value_check in set1)
value_not_check = int(input("Enter a value to check not in Set2: "))
print(f"Is {value_not_check} not in Set2?", value_not_check not in set2)
OUTPUT:
RESULT:
DATE:
FILE OPERATIONS
AIM:
To understand and demonstrate file operations in Python, including opening, closing, reading, writing
in a formatted manner, and sorting data stored in a file.
ALGORITHM:
1. Start
2. Open a file in write mode to store data.
3. Write formatted data into the file (e.g., name, roll number, marks).
4. Close the file after writing.
5. Open the file in read mode to read the data.
6. Read all lines and store data in a suitable structure (list of dictionaries or tuples).
7. Sort the data based on a specific field (e.g., marks or name).
8. Display the sorted data in a formatted way.
9. Close the file.
10. End
Student details (Name, 1. Write formatted student data to a file. Displays student records sorted by
Roll, Marks) written 2. Read data line by line (skipping header). marks in descending order.
into a file. 3. Store data in a list of dictionaries.
4. Sort the list based on marks in
descending order.
5. Display sorted records.
SOURCE CODE:
# Step 1: Open file in write mode and write formatted data
with open("[Link]", "w") as f:
[Link]("Name,Roll,Marks\n")
[Link]("Alice,101,85\n")
[Link]("Bob,102,92\n")
[Link]("Charlie,103,78\n")
[Link]("David,104,90\n")
Bob 102 92
David 104 90
Alice 101 85
Charlie 103 78
RESULT:
Thus, the file operation using python program executed successfully.
EX. NO:
DATE: NUMPY
AIM:
To understand and demonstrate how the NumPy module in Python can be used to perform efficient
numerical computations, array operations, and data analysis to solve problems.
ALGORITHM:
1. Start
2. Import the NumPy module using import numpy as np.
3. Create NumPy arrays from lists or using built-in functions ([Link](), [Link](),
[Link](), [Link]()).
4. Perform array operations:
o Arithmetic operations (+, -, *, /)
o Statistical operations (mean(), sum(), max(), min())
o Sorting arrays ([Link]())
5. Use NumPy functions for specific tasks:
o Reshape arrays (reshape())
o Generate random numbers ([Link])
o Perform matrix operations (dot(), transpose())
6. Display results.
7. End
import numpy as np
#Step 1: Create a NumPy array
data = [Link]([10, 20, 15, 30, 25])
print("Original Array:", data)
# Step 2: Perform arithmetic operations
print("Array + 5:", data + 5)
print("Array * 2:", data * 2)
RESULT:
DATE: PANDA
AIM:
To understand and demonstrate how the Pandas library in Python can be used for data
manipulation, analysis, and solving problems using Series and DataFrames.
ALGORITHM:
1. Start
2. Import the pandas module using import pandas as pd.
3. Create a Series or DataFrame from lists, dictionaries, or CSV/Excel files.
4. Perform basic operations:
o Accessing rows and columns
o Selecting specific data using loc and iloc
o Adding, updating, or deleting columns
5. Perform data analysis:
o Descriptive statistics (mean(), sum(), min(), max())
o Sorting (sort_values())
o Filtering data based on conditions
6. Display results in tabular or formatted form.
7. End
Student details such as 1. Create a DataFrame from a dictionary. Displays the DataFrame after each
Name, Age, and Marks. 2. Access specific rows and columns. operation and analysis results.
3. Add, update, and delete columns.
4. Perform basic data analysis (mean, max,
sort).
5. Filter data based on conditions.
SOURCE CODE:
import pandas as pd
data = {
df = [Link](data)
AIM:
To understand and demonstrate the usage of Python’s built-in modules for performing
common tasks efficiently, without the need to install external packages.
ALGORITHM:
1. Start
2. Identify the task to solve (math calculations, random numbers, date/time operations, etc.)
3. Import the required built-in module (import module_name)
4. Use the module’s functions or classes to perform the task
5. Display the results
6. End
Predefined values (e.g., 1. Create a DataFrame from a dictionary. Displays the DataFrame after each
numbers and lists) used 2. Access specific rows and columns. operation and analysis results.
within the program. 3. Add, update, and delete columns.
4. Perform basic data analysis (mean, max,
sort).
5. Filter data based on conditions.
SOURCE CODE:
import math
import random
import datetime
import statistics
import os
# Math module
num = float(input("Enter a number to find its square root: "))
print("Square root:", [Link](num))
# Datetime module
now = [Link]()
print("Current date and time:", now)
# Statistics module
data = [10, 20, 30, 40, 50]
print("Mean:", [Link](data))
print("Median:", [Link](data))
# OS module
print("Current working directory:", [Link]())
print("List of files in directory:", [Link]())
OUTPUT:
RESULT:
AIM:
To develop a Python program that manages student records, allowing the user to add,
display, search, update, and delete student details efficiently.
ALGORITHM:
1. Start
2. Initialize an empty list or dictionary to store student records.
3. Display menu options:
o Add student
o Display all students
o Search student
o Update student
o Delete student
o Exit
4. Take user choice as input.
5. Perform the corresponding operation.
6. Repeat until user chooses Exit.
7. End
SOURCE CODE:
# List to store student records
students = []
# Function to add student
def add_student():
name = input("Enter Name: ")
roll = input("Enter Roll Number: ")
age = input("Enter Age: ")
marks = input("Enter Marks: ")
student = {"Name": name, "Roll": roll, "Age": age, "Marks": marks}
[Link](student)
print("Student added successfully!\n")
RESULT:
This project demonstrates the use of lists/dictionaries, loops, and functions in Python. It
provides a basic CRUD (Create, Read, Update, Delete) functionality for managing data.
EX. NO:
AIM:
To develop a Python program that simulates basic bank account operations like creating
accounts, depositing money, withdrawing money, and viewing account details.
ALGORITHM:
1. Start
2. Initialize an empty dictionary to store accounts
3. Display menu:
o Create Account
o Deposit Money
o Withdraw Money
o Display Account Details
o Exit
4. Take user choice
5. Perform corresponding operation using functions
6. Repeat until user chooses Exit
7. End
SOURCE CODE:
accounts = {}
# Withdraw money
def withdraw():
acc_no = input("Enter account number: ")
if acc_no in accounts:
amount = float(input("Enter amount to withdraw: "))
if amount <= accounts[acc_no]["Balance"]:
accounts[acc_no]["Balance"] -= amount
print(f"Withdrawn {amount}. New balance: {accounts[acc_no]['Balance']}\n")
else:
print("Insufficient balance!\n")
else:
print("Account not found!\n")
if choice == '1':
create_account()
elif choice == '2':
deposit()
elif choice == '3':
withdraw()
elif choice == '4':
display_account()
elif choice == '5':
print("Exiting program...")
break
else:
print("Invalid choice! Please try again.\n")
OUTPUT:
RESULT:
This project demonstrates the use of lists/dictionaries, loops, and functions in Python. It provides a
basic CRUD (Create, Read, Update, and Delete) functionality for managing data,