0% found this document useful (0 votes)
8 views65 pages

Python Programming Lab Record 2025-26

This document is a laboratory record for Anna University, specifically for the Department of Mechanical Engineering, covering practical exercises in Python programming for the academic year 2025-2026. It includes various programming tasks such as swapping values, calculating sums, determining even or odd numbers, finding the greatest of three numbers, generating Fibonacci series, identifying prime numbers, calculating factorials using recursion, and designing a scientific calculator. Each task contains the aim, algorithm, source code, output, and results confirming successful execution.

Uploaded by

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

Python Programming Lab Record 2025-26

This document is a laboratory record for Anna University, specifically for the Department of Mechanical Engineering, covering practical exercises in Python programming for the academic year 2025-2026. It includes various programming tasks such as swapping values, calculating sums, determining even or odd numbers, finding the greatest of three numbers, generating Fibonacci series, identifying prime numbers, calculating factorials using recursion, and designing a scientific calculator. Each task contains the aim, algorithm, source code, output, and results confirming successful execution.

Uploaded by

Tamizharasan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ANNA UNIVERSITY

REGIONAL CAMPUS, COIMBATORE- 641046

LABORATORY RECORD
2025-2026

NAME : ………………………………………………

[Link] : ………………………………………………

BRANCH : …………………………...…………………

SUBJECT CODE : ………………...……………………………

SUBJECT TITLE : …………………………………...………….

DEPARTMENT OF MECHANICAL ENGINEERING


ANNA UNIVERSITY REGIONAL CAMPUS
COIMBATORE- 641 046.
ANNA UNIVERSITY,

REGIONAL CAMPUS COIMBATORE - 641046

DEPARTMENT OF MECHANICAL ENGINEERING

BONAFIDE CERTIFICATE

Certified that this is the bonafide record of Practical done in CS25C02-


COMPUTER PROGRAMMING: PYTHON by
………………………………..……………………… Register Number
…………………………………..in the First Year/First semester during
2025-2026.

Staff in Charge Head of the Department

University Register No: …………………………………………………….

Submitted for the University Practical Examination held on ………………..

Internal Examiner External Examiner


INDEX

PAGE FACULTY
[Link] DATE NAME OF THE EXPERIMENT NUMBER MARK SIGNATURE
EX. NO:
DATE : SWAPPING VALUES OF TWO VARIABLES

AIM :

To write a Python program to exchange the values of two variables.

ALGORITHM :

Step 1: Start the program.


Step 2: Get the values from the user.
Step 3: Swap both the values using temporary variables.
Step 4: Print the swapped output.
Step 5: Stop the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

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 :

a=int(input("Enter the value for A:"))


b=int(input("Enter the value for B:"))
print("Before Exchanging the values")
print("A=",a, B =",b)
temp=a
a=b
b=temp
print("After Exchanging the values of variables")
print("A=",a," B=",b)
OUTPUT:

Enter the value for A: 567


Enter the value for B: 23
Before exchanging the values
A= 567 B= 23
After exchanging the values of variables
A= 23 B= 567

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:

Step 1: Start the program.


Step 2: Read the value of a and b
Step 3: Calculate the sum c=a+b
Step 4: Print c
Step 5: Stop the program

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

Two numbers (a, b) Add the two numbers using the Display the result of the
addition operator (+) addition
c = a + b

SOURCE CODE:

a=int(input("Enter the number1: "))


b=int(input("Enter the number2: "))
c=a+b
print("The sum of two numbers is",c)
OUTPUT:

Enter the number1: 987


Enter the number2: 123
The sum of two numbers is 1110

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:

Step 1: Start the program.


Step 2: Read the value of a
Step 3: if a%2 == 0
Step3.1: print(“Even Number”)
else
Step3.2: print(“Odd Number”)
Step 5: Stop the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

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:

a=int(input("Enter the number:"))


if a%2==0:
print("%d is even number" %(a))
else:
print("%d is odd number" %(a))
OUTPUT:

Enter the number: 6584650


6584650 is even number

Enter the number: 6775


6775 is odd number

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:

Step 1: Start the program.


Step 2: Read the value of a,b,c
Step 3: if (a>b) & (a>c)
Step 3.1: print(“a is big”)
Step 4: elif (b>a) & (b>c)
Step 4.1: print(“b is big”)
else
Step 4.2: print(“c is big”)
Step 5: Stop the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

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:

Enter the first number: 565


Enter the second number: 66545
Enter the third number: 221
66545 is Greatest

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:

Step 1: Start the program.


Step 2: Read the input number nterms.
Step 3: Initialize variables:
n1 = 0, n2 = 1, count = 0.
Step 4: If nterms <= 0, display "Please enter a positive integer".
Step 5: Else if nterms == 1, print only n1.
Step 6: Otherwise,
a. Print “Fibonacci sequence up to nterms”.
b. While count < nterms:
– Print n1.
– Compute nth = n1 + n2.
– Update n1 = n2, n2 = nth.
– Increment count by 1.
Step 7: End the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

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:

nterms = int(input("Enter the number of Fibonacci terms to generate: "))


n1 = 0
n2 = 1
count = 0
If nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto", nterms, ":")
print(n1)
else:
print("Fibonacci sequence upto", nterms, ":")
while count < nterms:
print(n1, end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
OUTPUT:

Enter the number of Fibonacci terms to generate: 10


Fibonacci sequence up to 10:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

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:

Step 1: Start the program.


Step 2: Read the input number x.
Step 3: Initialize i = 1.
Step 4: Repeat the following steps while i <= x:
a. Set c = 0.
b. For each number j from 1 to i:
If i % j == 0, increment c by 1.
c. If c == 2, print i (since it has exactly two factors → 1 and itself).
d. Increment i by 1.
Step 5: End the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

A positive integer x entered 1. Initialize i = 1 All prime numbers from 1 to x


by the user 2. Repeat while i <= x
3. For each i, count its divisors
using a for loop
4. If the count of divisors (c)
equals 2 → print i (it’s prime)
5. Increment i and repeat
SOURCE CODE:
x = int(input("Enter the number: "))

i=1

while i <= x:

c=0

for j in range(1, i + 1):

if i % j == 0:

c += 1

if c == 2:

print(i)

i += 1
OUTPUT:

Enter the number: 50

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.

Step 2: Read the input number n.

Step 3: Define a function factorial(n) that performs the following:


a. If n <= 1, return 1.
b. Else, return n * factorial(n - 1).

Step 4: Call the function factorial(n) and store/print the result.

Step 5: Display the factorial value of the given number.

Step 6: Stop the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

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

if(n <= 1):

return 1

else:

return(n*factorial(n-1))

n = int(input("Enter number:"))

print("Factorial of", n, "is:")

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 2: Import the math module to access mathematical functions.


Step 3: Display the calculator menu:
Step 4: Ask the user to enter a choice (1–8).

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

 Default Case (_):


o Display “Invalid choice!” if the user enters a number outside 1–8.
Step 6: End the program.
SOURCE CODE:

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

choice = int(input("Enter your choice (1-8): "))


match choice:
case 1:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result =", a + b)

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:

1. Start the program.


2. Define a function swap_val(a, b) for Call by Value:
o Swap a and b inside the function.
o Print swapped values (changes are local, original variables remain
unchanged).
3. Define a function swap_ref(lst) for Call by Reference:
o Take a list with two elements.
o Swap the elements inside the list.
o Since the list is mutable, changes reflect outside the function.
4. In main program:
o Input two numbers.
o Demonstrate swapping using Call by Value.
o Demonstrate swapping using Call by Reference.
5. Stop the program.

PROBLEM ANALYSIS CHART

INPUT PROCESS OUTPUT

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

# Swap using Call by Value


def swap_val(a, b):
temp = a
a=b
b = temp
print("Inside function (Call by Value):", a, b)
# Swap using Call by Reference
def swap_ref(lst):
temp = lst[0]
lst[0] = lst[1]
lst[1] = temp
print("Inside function (Call by Reference):", lst[0], lst[1])
# Main Program
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

print("\n--- Call by Value Demonstration ---")


swap_val(x, y)
print("Outside after Call by Value:", x, y)

print("\n--- Call by Reference Demonstration ---")


nums = [x, y]
swap_ref(nums)
print("Outside after Call by Reference:", nums[0], nums[1])
OUTPUT:

Enter first number: 5453


Enter second number: 9821

--- Call by Value Demonstration ---


Inside function (Call by Value): 9821 5453
Outside after Call by Value: 5453 9821

--- Call by Reference Demonstration ---


Inside function (Call by Reference): 9821 5453
Outside after Call by Reference: 9821 5453

RESULT:
Thus the program demonstrates the difference between Call by Value and Call by Reference is written and executed
successfully.
.
[Link]:

DATE: PASCAL’S TRIANGLE

AIM:
To write a program to generate Pascal’s Triangle using functions.

.
ALGORITHM:

Step 1: Start the program.


Step 2: Define a function factorial(n) that returns the factorial of a number.
Step 3: Define a function nCr(n, r) that calculates the binomial coefficient using
factorials: nCr=n!r!(n−r)!nCr = \frac{n!}{r!(n-r)!}nCr=r!(n−r)!n!
Step 4: Define a function pascal_triangle(rows) to print Pascal’s Triangle:
o Loop through rows 0 to rows-1.
o For each row, print spaces for alignment.
o Compute and print each binomial coefficient using nCr.
Step 5: Input the number of rows.
Step 6: Call the pascal_triangle function.
Step 7: Stop the program.

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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:

# Recursive factorial function

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

# Function to compute nCr

def nCr(n, r):

return factorial(n) // (factorial(r) * factorial(n - r))

# Function to print Pascal's Triangle

def pascal_triangle(rows):

for i in range(rows):

# Print leading spaces for formatting

print(" " * (rows - i), end="")

for j in range(i + 1):

print(nCr(i, j), end=" ")

print() # Newline after each row

# Main Program

rows = int(input("Enter number of rows: "))

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:

DATE: STRING MANIPULATIONS

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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

# Indexing & slicing


print("First character:", s[0])
print("Last character:", s[-1])
print("Substring [1:5]:", s[1:5])

# Concatenation & repetition


concatenated = s + " Python"
print("Concatenation:", concatenated)
print("Repetition:", s * 2)

# String functions
print("Upper case:", [Link]())
print("Lower case:", [Link]())
print("Title case:", [Link]())
print("Strip spaces:", [Link]())
print("Replace:", [Link]("Python", "Java"))

# Searching & counting


print("Find 'a':", [Link]("a"))
print("Count 'a':", [Link]("a"))

# Split & join


words = [Link]()
print("Split string:", words)
print("Joined string:", "-".join(words))

# 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

Substring [1:5]: ello

Concatenation: HelloPython1234 Python

Repetition: HelloPython1234HelloPython1234

Upper case: HELLOPYTHON1234

Lower case: hellopython1234

Title case: Hellopython1234

Strip spaces: HelloPython1234

Replace: HelloJava1234 Java

Find 'a': -1

Count 'a': 0

Split string: ['HelloPython1234']

Joined string: HelloPython1234

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

Enter list elements and Use list methods like insert(),


perform actions (insert, extend(), remove(), pop(), sort(), Display the updated, sorted,
remove, update, search). and reverse()to modify the list. and reversed lists with search
and membership results.
SOURCE CODE:
# Creating a list at runtime

my_list = list(map(int, input("Enter list elements separated by spaces: ").split()))

print("Original list:", my_list)

# Inserting an element at a specific index

index = int(input("Enter index to insert at: "))

value = int(input("Enter value to insert: "))

my_list.insert(index, value)

print("After insert:", my_list)

# Extending the list with multiple elements

extra_elements = list(map(int, input("Enter elements to extend (space-separated): ").split()))

my_list.extend(extra_elements)

print("After extend:", my_list)

# Removing an element

remove_value = int(input("Enter value to remove: "))

if remove_value in my_list:

my_list.remove(remove_value)

print("After remove:", my_list)

else:

print(f"{remove_value} not found in list!")

# Popping the last element

popped = my_list.pop()

print("After pop:", my_list, "| Popped element:", popped)

# Deleting an element by index

del_index = int(input("Enter index to delete: "))

if 0 <= del_index < len(my_list):

del my_list[del_index]

print("After delete:", my_list)


else:

print("Invalid index!")

# Updating an element

update_index = int(input("Enter index to update: "))

if 0 <= update_index < len(my_list):

new_value = int(input("Enter new value: "))

my_list[update_index] = new_value

print("After update:", my_list)

else:

print("Invalid index!")

# Sorting & reversing

my_list.sort()

print("After sorting:", my_list)

my_list.reverse()

print("After reversing:", my_list)

# Searching for an element

search_value = int(input("Enter value to search: "))

if search_value in my_list:

print(f"Index of {search_value}:", my_list.index(search_value))

else:

print(f"{search_value} not found in list!")

# Membership check

check_value = int(input("Enter value to check if it exists in list: "))

print(f"Is {check_value} in list?", check_value in my_list)


OUTPUT:
Enter list elements separated by spaces: 90 40 20 10 20 80 30

Original list: [90, 40, 20, 10, 20, 80, 30]

Enter index to insert at: 4

Enter value to insert: 50

After insert: [90, 40, 20, 10, 50, 20, 80, 30]

Enter elements to extend (space-separated): 70 60 100

After extend: [90, 40, 20, 10, 50, 20, 80, 30, 70, 60, 100]

Enter value to remove: 20

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

Enter index to delete: 0

After delete: [40, 10, 50, 20, 80, 30, 70, 60]

Enter index to update: 4

Enter new value: 85

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]

Enter value to search: 100

100 not found in list!

Enter value to check if it exists in list: 30

Is 30 in list? True

RESULT:

Thus, the list operation using python program executed successfully.


EX. NO:

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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:

# Creating a tuple at runtime


elements = input("Enter tuple elements separated by spaces: ").split()
my_tuple = tuple(map(int, elements))
print("Original Tuple:", my_tuple)

# Indexing & Slicing


print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
print("Slicing [1:4]:", my_tuple[1:4])

# Concatenation & Repetition


tuple2 = tuple(map(int, input("Enter another tuple (space-separated): ").split()))
print("Concatenated Tuple:", my_tuple + tuple2)
print("Repeated Tuple:", my_tuple * 2)

# 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:

Enter tuple elements separated by spaces: 65 15 75 85 35

Original Tuple: (65, 15, 75, 85, 35)

First element: 65

Last element: 35

Slicing [1:4]: (15, 75, 85)

Enter another tuple (space-separated): 105 115 145

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

Enter a value to count: 105

Count of 105: 0

Enter a value to find its index: 75

Index of 75: 2

RESULT:

Thus, the tuples operation using python program executed successfully.


EX. NO:

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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:

Enter elements for Set1 (separated by spaces): 98 76 23 19 80 34


Enter elements for Set2 (separated by spaces): 100 70 30 40
Set1: {98, 34, 76, 80, 19, 23}
Set2: {40, 100, 70, 30}
Enter a value to add to Set1: 100
After add: {98, 34, 100, 76, 80, 19, 23}
Enter multiple values to update Set1 (separated by spaces): 100 34 98
After update: {98, 34, 100, 76, 80, 19, 23}
Enter a value to remove from Set1: 34
Enter a value to discard from Set1: 23
After removing/discarding: {98, 100, 76, 80, 19}
After pop: {100, 76, 80, 19} | Popped element: 98
Union: {100, 70, 40, 76, 80, 19, 30}
Intersection: {100}
Difference (Set1 - Set2): {80, 19, 76}
Symmetric Difference: {70, 40, 76, 80, 19, 30}
Enter a value to check in Set1: 11
Is 11 in Set1? False
Enter a value to check not in Set2: 30
Is 30 not in Set2? False

RESULT:

Thus, the set operation using python program executed successfully.


EX. NO:

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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

# Step 2: Read data from file


students = []
with open("[Link]", "r") as f:
next(f) # Skip header line
for line in f:
name, roll, marks = [Link]().split(",")
[Link]({"Name": name, "Roll": int(roll), "Marks": int(marks)})

# Step 3: Sort data by Marks descending


sorted_students = sorted(students, key=lambda x: x["Marks"], reverse=True)

# Step 4: Display sorted data


print("Name\tRoll\tMarks")
for s in sorted_students:
print(f"{s['Name']}\t{s['Roll']}\t{s['Marks']}")
OUTPUT:

Name Roll Marks

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

Predefined numeric 1. Create a NumPy array. Displays results of all operations


data array and random 2. Perform arithmetic and statistical on arrays and matrices.
values generated by operations.
NumPy.. 3. Sort and reshape the array.
4. Generate random numbers.
5. Perform matrix multiplication using
[Link]().
SOURCE CODE:

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)

# Step 3: Statistical operations


print("Sum:", [Link](data))
print("Mean:", [Link](data))
print("Maximum:", [Link](data))
print("Minimum:", [Link](data))

# Step 4: Sorting array


sorted_data = [Link](data)
print("Sorted Array:", sorted_data)

# Step 5: Reshape array


reshaped_data = [Link](1, 5)
print("Reshaped Array (1x5):\n", reshaped_data)

# Step 6: Random numbers


rand_array = [Link](1, 100, 5)
print("Random Array:", rand_array)

# Step 7: Matrix operations


matrix1 = [Link]([[1, 2], [3, 4]])
matrix2 = [Link]([[5, 6], [7, 8]])
product = [Link](matrix1, matrix2)
print("Matrix Product:\n", product)
OUTPUT:

Original Array: [10 20 15 30 25]


Array + 5: [15 25 20 35 30]
Array * 2: [20 40 30 60 50]
Sum: 100
Mean: 20.0
Maximum: 30
Minimum: 10
Sorted Array: [10 15 20 25 30]
Reshaped Array (1x5):
[[10 20 15 30 25]]
Random Array: [42 87 23 65 19] ← (Values will vary)
Matrix Product:
[[19 22]
[43 50]]

RESULT:

Thus, the NumPy module using python program executed successfully.


EX. NO:

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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

# Step 1: Create DataFrame

data = {

"Name": ["Alice", "Bob", "Charlie", "David"],

"Age": [25, 30, 22, 28],

"Marks": [85, 92, 78, 90]

df = [Link](data)

print("Original DataFrame:\n", df)

# Step 2: Access rows and columns

print("\nNames Column:\n", df["Name"])

print("\nFirst 2 rows:\n", [Link](2))

# Step 3: Add/Update/Delete columns

df["Grade"] = ["A", "A+", "B", "A"]

df["Age"] = df["Age"] + 1 # Update Age

[Link]("Grade", axis=1, inplace=True) # Delete Grade column

print("\nUpdated DataFrame:\n", df)

# Step 4: Data analysis

print("\nMean Marks:", df["Marks"].mean())

print("Maximum Marks:", df["Marks"].max())

print("Sorted by Marks descending:\n", df.sort_values(by="Marks", ascending=False))

# Step 5: Filtering data

high_scorers = df[df["Marks"] > 80]

print("\nStudents with Marks > 80:\n", high_scorers)


OUTPUT:
Original DataFrame
Name Age Marks
0 Alice 25 85
1 Bob 30 92
2 Charlie 22 78
3 David 28 90
Names Column:
0 Alice
1 Bob
2 Charlie
3 David
Name: Name, dtype: object
First 2 rows:
Name Age Marks
0 Alice 25 85
1 Bob 30 92
Updated DataFrame:
Name Age Marks
0 Alice 26 85
1 Bob 31 92
2 Charlie 23 78
3 David 29 90
Mean Marks: 86.25
Maximum Marks: 92
Sorted by Marks descending:
Name Age Marks
1 Bob 31 92
3 David 29 90
0 Alice 26 85
2 Charlie 23 78
Students with Marks > 80:
Name Age Marks
0 Alice 26 85
1 Bob 31 92
3 David 29 90
RESULT:
Thus, the Pandas module using python program executed successfully.
EX. NO:

DATE: BUILT-IN MODULES

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

PROGRAM ANALYSIS CHART:

INPUT PROCESS OUTPUT

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

fact_num = int(input("Enter a number to find its factorial: "))


print("Factorial of", fact_num, "is:", [Link](fact_num))
# Random module
print("Random integer between 1 and 10:", [Link](1, 10))
print("Random choice from list:", [Link]([10, 20, 30, 40]))

# 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:

Enter a number to find its square root: 49


Square root: 7.0
Enter a number to find its factorial: 10
Factorial of 10 is: 3628800
Random integer between 1 and 10: 6
Random choice from list: 30
Current date and time: 2025-11-08 21:48:52.304693
Mean: 30
Median: 30
Current working directory: C:\Users\ADMIN\AppData\Local\Programs\Python\Python313
List of files in directory: ['[Link]', 'DLLs', 'Doc', 'include', 'Lib', 'libs', '[Link]', '[Link]',
'[Link]', '[Link]', '[Link]', '[Link]', 'Scripts', '[Link]', 'tcl', '[Link]',
'vcruntime140_1.dll']

RESULT:

Thus, the Built-in modules using python program executed successfully.


MINI - PROJECT
EX. NO:

DATE: STUDENT RECORD MANAGEMENT

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

# Function to display all students


def display_students():
if students:
print("\nStudent Records:")
for s in students:
print(s)
else:
print("No student records found.\n")

# Function to search student by Roll Number


def search_student():
roll = input("Enter Roll Number to search: ")
for s in students:
if s["Roll"] == roll:
print("Student found:", s)
return
print("Student not found!\n")

# Function to update student


def update_student():
roll = input("Enter Roll Number to update: ")
for s in students:
if s["Roll"] == roll:
s["Name"] = input("Enter new Name: ")
s["Age"] = input("Enter new Age: ")
s["Marks"] = input("Enter new Marks: ")
print("Student updated successfully!\n")
return
print("Student not found!\n")

# Function to delete student


def delete_student():
roll = input("Enter Roll Number to delete: ")
for s in students:
if s["Roll"] == roll:
[Link](s)
print("Student deleted successfully!\n")
return
print("Student not found!\n")
# Main program loop
while True:
print("\n--- Student Record Management ---")
print("1. Add Student")
print("2. Display Students")
print("3. Search Student")
print("4. Update Student")
print("5. Delete Student")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_student()
elif choice == '2':
display_students()
elif choice == '3':
search_student()
elif choice == '4':
update_student()
elif choice == '5':
delete_student()
elif choice == '6':
print("Exiting program...")
break
else:
print("Invalid choice! Please try again.")
OUTPUT:

--- Student Record Management ---


1. Add Student
2. Display Students
3. Search Student
4. Update Student
5. Delete Student
6. Exit
Enter your choice: 1
Enter Name: Raj
Enter Roll Number: 45
Enter Age: 13
Enter Marks: 90
Student added successfully!
--- Student Record Management ---
1. Add Student
2. Display Students
3. Search Student
4. Update Student
5. Delete Student
6. Exit
Enter your choice: 1
Enter Name: Sindhu
Enter Roll Number: 56
Enter Age: 13
Enter Marks: 78
Student added successfully!
--- Student Record Management ---
1. Add Student
2. Display Students
3. Search Student
4. Update Student
5. Delete Student
6. Exit
Enter your choice: 1
Enter Name: Arun
Enter Roll Number: 9
Enter Age: 13
Enter Marks: 89
Student added successfully!
--- Student Record Management ---
1. Add Student
2. Display Students
3. Search Student
4. Update Student
5. Delete Student
6. Exit
Enter your choice: 2
Student Records:
{'Name': 'Raj', 'Roll': '45', 'Age': '13', 'Marks': '90'}
{'Name': 'Sindhu', 'Roll': '56', 'Age': '13', 'Marks': '78'}
{'Name': 'Arun', 'Roll': '9', 'Age': '13', 'Marks': '89'}
--- Student Record Management ---
1. Add Student
2. Display Students
3. Search Student
4. Update Student
5. Delete Student
6. Exit
Enter your choice: 3
Enter Roll Number to search: 56
Student found: {'Name': 'Sindhu', 'Roll': '56', 'Age': '13', 'Marks': '78'}

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:

DATE: BANK MANAGEMENT SYSTEM

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 = {}

# Create a new account


def create_account():
name = input("Enter your name: ")
acc_no = input("Enter account number: ")
balance = float(input("Enter initial deposit: "))
accounts[acc_no] = {"Name": name, "Balance": balance}
print("Account created successfully!\n")
# Deposit money
def deposit():
acc_no = input("Enter account number: ")
if acc_no in accounts:
amount = float(input("Enter amount to deposit: "))
accounts[acc_no]["Balance"] += amount
print(f"Deposited {amount}. New balance: {accounts[acc_no]['Balance']}\n")
else:
print("Account not found!\n")

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

# Display account details


def display_account():
acc_no = input("Enter account number: ")
if acc_no in accounts:
print(f"Account Number: {acc_no}")
print(f"Name: {accounts[acc_no]['Name']}")
print(f"Balance: {accounts[acc_no]['Balance']}\n")
else:
print("Account not found!\n")
# Main program loop
while True:
print("--- Bank Management System ---")
print("1. Create Account")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Display Account Details")
print("5. Exit")

choice = input("Enter your choice: ")

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:

--- Bank Management System ---


1. Create Account
2. Deposit Money
3. Withdraw Money
4. Display Account Details
5. Exit
Enter your choice: 1
Enter your name: Kumar
Enter account number: 3432
Enter initial deposit: 10000
Account created successfully!
--- Bank Management System ---
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Display Account Details
5. Exit
Enter your choice: 1
Enter your name: Keerthi
Enter account number: 3234
Enter initial deposit: 12000
Account created successfully!
--- Bank Management System ---
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Display Account Details
5. Exit
Enter your choice: 4
Enter account number: 3234
Account Number: 3234
Name: Keerthi
Balance: 12000.0
--- Bank Management System ---
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Display Account Details
5. Exit
Enter your choice: 2
Enter account number: 3432
Enter amount to deposit: 2000
Deposited 2000.0. New balance: 12000.0

--- Bank Management System ---


1. Create Account
2. Deposit Money
3. Withdraw Money
4. Display Account Details
5. Exit
Enter your choice:

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,

You might also like