Python Programming Lab Manual
Python Programming Lab Manual
5 Practical: Opening, closing, reading and writing in formatted file format and
sort data. (Minimum three)
AIM
To write and execute a Python program to find the sum of two numbers entered by the user.
ALGORITHM:
Find the Sum of Two Numbers
1. Start
2. Input two numbers, say a and b.
3. Compute the sum using the formula: sum = a + b.
4. Output the value of sum.
5. Stop
FLOWCHART
PSEUDOCODE
START
INPUT number1, number2
sum ← number1 + number2
PRINT sum
STOP
PROGRAM:
# Program to find the sum of two numbers
# Input
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
# Process
sum = a + b
# Output
print("The sum of", a, "and", b, "is:", sum)
OUTPUT:
Enter the first number: 12
Enter the second number: 20
The sum of 12 and 20 is: 32
RESULT:
The program to find the sum of two numbers was successfully written and executed in
Python.
2
PROBLEM ANALYSIS CHART, FLOWCHART AND PSEUDOCODE PRACTICES
EX.NO DATE
1B TO PRINT MULTIPLICATION TABLE OF A NUMBER
AIM
To write and execute a Python program to print the multiplication table of a given number.
ALGORITHM: Print Multiplication Table of a Number
1. Start
2. Read the number n from the user.
3. Initialize counter i = 1.
4. Repeat the following steps until i ≤ 10:
o Calculate product = n × i.
o Print the result in the form n × i = product.
o Increment i by 1.
5. Stop
FLOWCHART
3
PSEUDOCODE
START
INPUT number n
FOR i = 1 TO 10
product ← n * i
PRINT n, "x", i, "=", product
END FOR
STOP
PROGRAM:
# Program to print multiplication table of a number
# Input
n = int(input("Enter a number: "))
# Process & Output
print("Multiplication Table of", n)
for i in range(1, 11):
print(n, "x", i, "=", n * i)
OUTPUT:
Enter a number: 5
Multiplication Table of 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
RESULT
The program to print the multiplication table of a number was successfully written
and executed in Python.
4
PROBLEM ANALYSIS CHART, FLOWCHART AND PSEUDOCODE PRACTICES
EX.NO DATE
1C TO FIND GCD AND LCM OF TWO NUMBERS
AIM
To write and execute a Python program to find the Greatest Common Divisor (GCD)
and Least Common Multiple (LCM) of two numbers entered by the user.
ALGORITHM: To Find GCD and LCM of Two Numbers
1. Start
2. Read two numbers a and b.
3. Store the original values of a and b in variables x and y.
4. Find GCD using Euclidean Algorithm:
o Repeat while b ≠ 0:
temp ← b
b ← a mod b
a ← temp
o When loop ends, a contains the GCD.
5. Find LCM using formula:
o LCM = (x × y) / GCD
6. Print GCD and LCM.
7. Stop
FLOWCHART
5
PSEUDOCODE
START
INPUT a, b
SET x = a, y = b
WHILE b ≠ 0
temp ← b
b ← a mod b
a ← temp
END WHILE
GCD ← a
LCM ← (x * y) / GCD
PRINT GCD, LCM
STOP
PROGRAM
# Program to find GCD and LCM of two numbers
# Input
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
# Store original values
x, y = a, b
# Process: Euclidean Algorithm for GCD
while b != 0:
a, b = b, a % b
gcd = a
lcm = (x * y) // gcd
# Output
print("GCD of", x, "and", y, "is:", gcd)
print("LCM of", x, "and", y, "is:", lcm)
OUTPUT
Enter first number: 20
Enter second number: 25
GCD of 20 and 25 is: 5
LCM of 20 and 25 is: 100
RESULT:
The program to find the GCD and LCM of two numbers was successfully written and
executed in Python
6
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO DATE
2A TO GENERATE FIRST N FIBONACCI TERMS 0,1,1,2,3,5…N (N>2)
USING CONDITIONAL STATEMENTS
AIM
To write and execute a Python program to generate the first N terms of the Fibonacci
sequence using conditional statements.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
If N == 1, print 0
Value of N
If N == 2, print 0, 1 First N Fibonacci
(number of
Else: use loop and conditional logic to generate terms: term
terms)
next = first + second
7
PSEUDOCODE
START
INPUT N
IF N == 1 THEN
PRINT 0
ELSE IF N == 2 THEN
PRINT 0, 1
ELSE
PRINT 0, 1
first ← 0
second ← 1
FOR i = 3 TO N
next ← first + second
PRINT next
first ← second
second ← next
END FOR
END IF
STOP
PROGRAM
# Program to generate first N Fibonacci terms using conditional statements
# Input
N = int(input("Enter the number of terms (N > 2): "))
OUTPUT
Enter the number of terms (N > 2): 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
RESULT:
The program to generate the first N Fibonacci terms was successfully written and
executed in Python using conditional statements.
8
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO TO FIND EVEN NUMBER BETWEEN 1 TO 50 USING DATE
2B CONDITIONAL STATEMENTS
AIM
To write and execute a Python program to find and display all even numbers between 1 and 50.
ALGORITHM
1. Start
2. Set the range from 1 to 50.
3. For each number i in the range 1 to 50:
o If i % 2 == 0 (number is divisible by 2), then print i.
4. End loop.
5. Stop
FLOWCHART
PSEUDOCODE
START
FOR i = 1 TO 50
IF i % 2 == 0 THEN
PRINT i
END IF
END FOR
STOP
9
PROGRAM
# Program to print even numbers between 1 and 50
OUTPUT
Even numbers between 1 and 50 are:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
RESULT
The program to find even numbers between 1 and 50 was successfully written and executed in
Python
10
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO TO FIND ROOTS OF QUADRATIC EQUATIONS AX2+BX+C=0 DATE
2C USING CONDITIONAL STATEMENTS
AIM
To write and execute a Python program to find the roots of a quadratic equation
ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0 using conditional statements.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Compute discriminant D = b² - 4ac
Coefficients a, Roots of the
Check condition of D
b, c quadratic equation
Calculate roots accordingly
ALGORITHM
1.Start
2.Input coefficients a, b, and c.
3.Compute discriminant: d = b² - 4ac.
4.If d > 0 → roots are real and distinct:
o Root1 = (-b + √d) / (2a)
o Root2 = (-b - √d) / (2a)
5. Else if d == 0 → roots are real and equal:
o Root1 = root2 = -b / (2a)
6. Else → roots are complex:
o Realpart = -b / (2a)
o Imaginarypart = √(-d) / (2a)
o Roots = realpart ± imaginarypart * i
7. Print the roots.
8. Stop
FLOWCHART
11
PSEUDOCODE
START
INPUT a, b, c
D ← b^2 - 4ac
IF D > 0 THEN
root1 ← (-b + sqrt(D)) / (2a)
root2 ← (-b - sqrt(D)) / (2a)
PRINT "Real and distinct roots", root1, root2
ELSE IF D == 0 THEN
root1 ← root2 ← -b / (2a)
PRINT "Real and equal roots", root1
ELSE
realPart ← -b / (2a)
imaginaryPart ← sqrt(-D) / (2a)
PRINT "Complex roots", realPart ± imaginaryPart i
END IF
STOP
PROGRAM
# Program to find roots of a quadratic equation using conditional statements
Import math
# Input
A = float(input("Enter coefficient a: "))
B = float(input("Enter coefficient b: "))
C = float(input("Enter coefficient c: "))
# Discriminant
D = b**2 - 4*a*c
# Conditions
If D > 0:
Root1 = (-b + math.sqrt(D)) / (2*a)
Root2 = (-b - math.sqrt(D)) / (2*a)
Print("Roots are real and distinct:")
Print("Root 1 =", root1, ", Root 2 =", root2)
Elif D == 0:
Root = -b / (2*a)
Print("Roots are real and equal:")
Print("Root =", root)
Else:
Realpart = -b / (2*a)
Imaginarypart = math.sqrt(-D) / (2*a)
Print("Roots are complex:")
Print(f"Root 1 = {realpart} + {imaginarypart}i")
Print(f"Root 2 = {realpart} - {imaginarypart}i")
12
OUTPUT
Enter coefficient a: 4
Enter coefficient b: 6
Enter coefficient c: 8
Roots are complex:
Root 1 = -0.75 + 1.1989578808281798i
Root 2 = -0.75 - 1.1989578808281798i
RESULT:
The program to find the roots of a quadratic equation was successfully written and
executed in Python using conditional statements.
13
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO TO DESIGN A SCIENTIFIC CALCULATOR USING DATE
2D
SWITCH CASE IN PYTHON
AIM
To write and execute a Python program to design a scientific calculator using switch-case
logic (match-case) in Python.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Use match-case to select the operation:
1 → Addition (a+b)
User’s choice
2 → Subtraction (a-b)
of operation
3 → Multiplication (a*b) Display result of the
(1–8)
4 → Division (a/b if b≠0) chosen mathematical
and required
5 → Square root (√a) operation
numbers
6 → Power (a^b)
(operands)
7 → Trigonometric functions (sin, cos, tan)
8 → Logarithm (log(a))
ALGORITHM
1. Start
2. Display menu of operations:
Addition
Subtraction
Multiplication
Division
Square Root
Power
Sine, Cosine, Tangent
Logarithm
3. Input choice from user.
4. Use match-case (switch-case) to handle the choice:
o If choice = 1 → Add two numbers.
o If choice = 2 → Subtract two numbers.
o If choice = 3 → Multiply two numbers.
o If choice = 4 → Divide two numbers (check denominator ≠ 0).
o If choice = 5 → Find square root of a number.
o If choice = 6 → Find power (x^y).
o If choice = 7 → Find trigonometric values.
o If choice = 8 → Find log of a number.
o Else → Invalid choice.
5. Print the result.
6. Stop
14
FLOWCHART
PSEUDOCODE
BEGIN
DISPLAY "Scientific Calculator"
DISPLAY "Choose operation:"
DISPLAY "1. Addition"
DISPLAY "2. Subtraction"
DISPLAY "3. Multiplication"
DISPLAY "4. Division"
DISPLAY "5. Power (x^y)"
DISPLAY "6. Square Root"
DISPLAY "7. Sine"
DISPLAY "8. Cosine"
DISPLAY "9. Tangent"
DISPLAY "10. Logarithm"
DISPLAY "11. Exit"
INPUT choice
SWITCH choice
CASE 1:
INPUT a, b
result ← a + b
PRINT result
BREAK
CASE 2:
INPUT a, b
15
result ← a - b
PRINT result
BREAK
CASE 3:
INPUT a, b
result ← a * b
PRINT result
BREAK
CASE 4:
INPUT a, b
IF b ≠ 0 THEN
result ← a / b
PRINT result
ELSE
PRINT "Error: Division by zero"
ENDIF
BREAK
CASE 5:
INPUT base, exponent
result ← base ^ exponent
PRINT result
BREAK
CASE 6:
INPUT x
result ← SQRT(x)
PRINT result
BREAK
CASE 7:
INPUT angle
result ← SIN(angle)
PRINT result
BREAK
CASE 8:
INPUT angle
result ← COS(angle)
PRINT result
BREAK
CASE 9:
INPUT angle
result ← TAN(angle)
PRINT result
BREAK
16
CASE 10:
INPUT x
result ← LOG(x)
PRINT result
BREAK
CASE 11:
PRINT "Exiting Calculator"
EXIT
BREAK
DEFAULT:
PRINT "Invalid Choice"
ENDSWITCH
END
PROGRAM
# Scientific Calculator using match-case (Python 3.10+)
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:
17
print("Error! Division by zero not allowed.")
case 5:
a = float(input("Enter number: "))
print("Square Root =", math.sqrt(a))
case 6:
base = float(input("Enter base: "))
exp = float(input("Enter exponent: "))
print("Result =", math.pow(base, exp))
case 7:
angle = float(input("Enter angle in degrees: "))
rad = math.radians(angle)
print("sin =", math.sin(rad))
print("cos =", math.cos(rad))
print("tan =", math.tan(rad))
case 8:
a = float(input("Enter number (>0): "))
if a > 0:
print("Logarithm =", math.log(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): 1
Enter first number: 15
Enter second number: 15
Result = 30.0
RESULT
The program to design a scientific calculator using switch-case (match-case) was successfully
written and executed in Python
18
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO DATE
2E CHECK LEAP YEAR USING WHILE LOOP
AIM
To write and execute a Python program to determine whether a given year is a leap year or
not using a while loop.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Check divisibility:
- Year % 400 == 0 → Leap Year
"Leap Year" or "Not
Year - Else if Year % 4 == 0 and Year % 100 != 0 → Leap
Leap Year"
Year
- Else → Not Leap Year
ALGORITHM
1. Start the program.
2. Input a year from the user.
3. Use a while loop to process the input (run once for the entered year).
4. Check the leap year condition:
o If the year is divisible by 400 → it is a leap year.
o Else if the year is divisible by 4 but not by 100 → it is a leap year.
o Otherwise → not a leap year.
5. Display the result.
6. Stop the program.
FLOWCHART
PSEUDOCODE
BEGIN
INPUT year
SET flag ← 1
WHILE flag = 1 DO
IF (year MOD 400 = 0) THEN
PRINT "Leap Year"
19
ELSE IF (year MOD 4 = 0 AND year MOD 100 ≠ 0) THEN
PRINT "Leap Year"
ELSE
PRINT "Not a Leap Year"
ENDIF
PROGRAM:
# Program to check leap year using while loop
flag = 1
while flag == 1:
if (year % 400 == 0):
print(year, "is a Leap Year")
elif (year % 4 == 0 and year % 100 != 0):
print(year, "is a Leap Year")
else:
print(year, "is Not a Leap Year")
flag = 0 # Exit loop after one check
OUTPUT
Enter a year: 2024
2024 is a Leap Year
RESULT
Thus, the program successfully checks whether a given year is a Leap Year or Not a Leap
Year using a while loop.
20
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO DATE
2F FIND FACTORIAL OF A NUMBER USING FOR LOOP
AIM
To write and execute a program to find the factorial of a given number using a for loop.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Number (n) Multiply numbers from 1 to n (fact = fact × i) Factorial of n
ALGORITHM
1. Start the program.
2. Input a number n from the user.
3. Initialize fact = 1.
4. Use a for loop from 1 to n:
o Multiply fact = fact × i for each value of i.
5. After the loop ends, print the value of fact.
6. Stop the program.
FLOWCHART
PSEUDOCODE
BEGIN
INPUT n
SET fact ← 1
FOR i ← 1 TO n DO
fact ← fact × i
21
ENDFOR
PROGRAM
# Program to find factorial of a number using for loop
OUTPUT
Enter a number: 5
Factorial of 5 is 120
RESULT
Thus, the program successfully calculates the factorial of a number using a for loop.
22
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO DATE
2G FIND PRIME NUMBERS USING NESTED LOOP
AIM
To write and execute a program to find all the prime numbers within a given range using
nested loops.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
For each number from 2 to n, check divisibility by
Range (n) List of prime numbers
numbers from 2 to num-1
ALGORITHM
1. Start the program.
2. Input the range limit n.
3. Use an outer loop to iterate through numbers from 2 to n.
4. For each number, use an inner loop to check divisibility from 2 to (number-1).
5. If the number is divisible by any value in the inner loop, it is not prime.
6. If no divisor is found, then the number is prime.
7. Print all prime numbers.
8. Stop the program.
FLOWCHART
PSEUDOCODE
BEGIN
INPUT n
FOR num ← 2 TO n DO
SET isPrime ← true
FOR i ← 2 TO num - 1 DO
IF (num MOD i = 0) THEN
isPrime ← false
BREAK
ENDIF
ENDFOR
23
IF isPrime = true THEN
PRINT num
ENDIF
ENDFOR
END
PROGRAM
# Program to find prime numbers using nested loop
OUTPUT
Enter the range: 10
Prime numbers up to 10 are:
2357
RESULT
Thus, the program successfully finds and displays all prime numbers within a given range
using nested loops.
24
USAGE OF CONDITIONAL LOGICS IN PROGRAMS
EX.NO CHECK ARMSTRONG NUMBER USING PASS DATE
2H
STATEMENT
AIM
To write and execute a program to check whether a given number is an Armstrong Number
using the pass statement in Python.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Sum of each digit raised to the power of total digits → Armstrong / Not
Number (n)
Compare with original number Armstrong
ALGORITHM
1. Start the program.
2. Input a number n.
3. Find the number of digits in n.
4. Initialize sum = 0 and store a copy of n in temp.
5. Use a while loop:
o Extract the last digit of temp.
o Compute digit ^ (number of digits) and add to sum.
o Reduce temp by removing the last digit.
o Use pass statement inside loop (to satisfy requirement, though it does
nothing).
6. After loop ends, compare sum with n:
o If equal → Armstrong number.
o Else → Not Armstrong number.
7. Display the result.
8. Stop the program.
FLOWCHART
25
PSEUDOCODE
BEGIN
INPUT n
SET temp ← n
SET sum ← 0
SET digits ← number of digits in n
IF sum = n THEN
PRINT "Armstrong Number"
ELSE
PRINT "Not an Armstrong Number"
ENDIF
END
PROGRAM
# Program to check Armstrong number using pass statement
if sum == n:
print(n, "is an Armstrong Number")
else:
print(n, "is Not an Armstrong Number")
OUTPUT
Enter a number: 153
153 is an Armstrong Number
RESULT
Thus, the program successfully checks whether a given number is an Armstrong
Number using the pass statement in Python.
26
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
3A PASCAL’S TRIANGLE USING FUNCTIONS IN PYTHON
AIM
To write and execute a Python program to generate Pascal’s Triangle using functions.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Number of
Use factorial and binomial coefficient formula Pascal’s Triangle
rows
ALGORITHM
1. Start the program.
2. Define a function factorial(n) that returns the factorial of a number.
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!
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.
5. Input the number of rows.
6. Call the pascal_triangle function.
7. Stop the program.
FLOWCHART
27
PSEUDOCODE
BEGIN
FUNCTION factorial(n)
IF n = 0 OR n = 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n-1)
ENDFUNCTION
FUNCTION nCr(n, r)
RETURN factorial(n) / (factorial(r) * factorial(n-r))
ENDFUNCTION
FUNCTION pascal_triangle(rows)
FOR i ← 0 TO rows-1 DO
PRINT spaces (rows - i)
FOR j ← 0 TO i DO
PRINT nCr(i, j)
ENDFOR
PRINT newline
ENDFOR
ENDFUNCTION
INPUT rows
CALL pascal_triangle(rows)
END
PROGRAM
# Pascal's Triangle using functions in Python
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):
print(" " * (rows - i), end="") # spaces for alignment
for j in range(i + 1):
print(nCr(i, j), end=" ")
print()
# Main Program
rows = int(input("Enter number of rows: "))
pascal_triangle(rows)
28
OUTPUT
Enter number of rows: 10
1
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 successfully generates Pascal’s Triangle using functions in Python.
29
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
3B TOWER OF HANOI USING RECURSIVE FUNCTIONS IN PYTHON
AIM
To write and execute a program to solve the Tower of Hanoi problem using recursive
functions in Python.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Number of Recursively move disks from source to destination Steps to solve Tower of
disks (n) using auxiliary as helper Hanoi
ALGORITHM
1. Start the program.
2. Define a function tower_of_hanoi(n, source, auxiliary, destination).
3. If n == 1:
o Move disk from source to destination.
o Return.
4. Else:
o Move n-1 disks from source to auxiliary using destination as helper.
o Move 1 disk from source to destination.
o Move n-1 disks from auxiliary to destination using source as helper.
5. Input the number of disks n.
6. Call the function with source = 'A', auxiliary = 'B', destination = 'C'.
7. Display the sequence of moves.
8. Stop the program.
FLOWCHART
30
PSEUDOCODE
BEGIN
FUNCTION tower_of_hanoi(n, source, auxiliary, destination)
IF n = 1 THEN
PRINT "Move disk 1 from source to destination"
RETURN
ENDIF
INPUT n
CALL tower_of_hanoi(n, 'A', 'B', 'C')
END
PROGRAM
# Tower of Hanoi using functions (recursion)
# Main Program
n = int(input("Enter number of disks: "))
print("Steps to solve Tower of Hanoi:")
tower_of_hanoi(n, 'A', 'B', 'C')
OUTPUT
Enter number of disks: 3
Steps to solve Tower of Hanoi:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
RESULT
Thus, the program successfully solves the Tower of Hanoi problem using recursive
functions in Python and displays the sequence of moves.
31
USAGE OF FUNCTIONS IN PROGRAMS
EX.NO DATE
3C SWAPPING TWO NUMBERS USING CALL BY VALUE AND CALL
BY REFERENCE
AIM
To write and execute a Python program to swap two numbers using Call by Value and Call by
Reference.
PROBLEM ANALYSIS CHART (PAC)
METHOD INPUT PROCESS OUTPUT
CALL BY VALUE a b (numbers) Swap inside function Original numbers
(local variables) unchanged
CALL BY REFERENCE list [a, b] Original list
Swap list elements
modified (swapped)
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.
32
FLOWCHART
PSEUDOCODE
BEGIN
FUNCTION swap_val(a, b)
temp ← a
a←b
b ← temp
PRINT "Inside function (Call by Value):", a, b
ENDFUNCTION
FUNCTION swap_ref(lst)
temp ← lst[0]
lst[0] ← lst[1]
lst[1] ← temp
PRINT "Inside function (Call by Reference):", lst[0], lst[1]
ENDFUNCTION
INPUT x, y
CALL swap_val(x, y)
PRINT "Outside after Call by Value:", x, y
PROGRAM
# Swap using Call by Value
def swap_val(a, b):
temp = a
33
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)
OUTPUT
Enter first number: 45
Enter second number: 92
RESULT
Thus, the program clearly demonstrates the difference between Call by Value and Call
by Reference in Python.
34
STRING MANIPULATIONS AND OPERATIONS ON LISTS, TUPLES, SETS,
AND DICTIONARIES.
EX.NO DATE
4A STRING MANIPULATIONS
AIM
To understand and demonstrate various string manipulation techniques in Python,
such as indexing, slicing, concatenation, repetition, searching, replacing, and checking
content.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Indexed and sliced parts of the string
Indexing & slicing Concatenated and repeated string
String concatenation & Modified string (upper, lower, title)
repetition Result of search, count, replace
A string entered
Built-in string functions operations
by the user
Searching and counting Split and joined strings
Splitting & joining Content checks (isalpha, isdigit,
Content checking isalnum, isspace)
ALGORITHM
Algorithm to perform string manipulations:
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
# STRING MANIPULATIONS IN PYTHON
# 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
35
print("Concatenation:", s + " Python")
print("Repetition:", s * 2)
# String functions
print("Upper case:", s.upper())
print("Lower case:", s.lower())
print("Title case:", s.title())
print("Strip spaces:", s.strip())
print("Replace:", s.replace("Python", "Java"))
# Searching & counting
print("Find 'a':", s.find("a"))
print("Count 'a':", s.count("a"))
# Split & join
words = s.split()
print("Split string:", words)
print("Joined string:", "-".join(words))
# Checking content
print("Is alphabetic?", s.isalpha())
print("Is numeric?", s.isdigit())
print("Is alphanumeric?", s.isalnum())
print("Is space?", s.isspace())
OUTPUT
Enter a string: COMPUTER SCIENCE
First character: C
Last character:
Substring [1:5]: OMPU
Concatenation: COMPUTER SCIENCE Python
Repetition: COMPUTER SCIENCE COMPUTER SCIENCE
Upper case: COMPUTER SCIENCE
Lower case: computer science
Title case: Computer Science
Strip spaces: COMPUTER SCIENCE
Replace: COMPUTER SCIENCE
Find 'a': -1
Count 'a': 0
Split string: ['COMPUTER', 'SCIENCE']
Joined string: COMPUTER-SCIENCE
Is alphabetic? False
Is numeric? False
Is alphanumeric? False
Is space? False
RESULT
Thus, the various string manipulation techniques in Python, such as indexing, slicing,
concatenation, repetition, searching, replacing, and checking successfully.
36
STRING MANIPULATIONS AND OPERATIONS ON LISTS, TUPLES, SETS,
AND DICTIONARIES.
EX.NO DATE
4B LISTS OPERATIONS
AIM
To understand and demonstrate various operations on Python lists, such as creation,
indexing, slicing, adding, removing, updating elements, and performing built-in list
operations like sorting, reversing, and searching.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Indexing & slicing
Adding elements (append, insert,
extend) Results of various list
A list of elements
Removing elements (remove, pop, operations including access,
(numbers, strings, or
del) update, addition, deletion,
mixed)
Updating elements sorting, and searching.
Sorting & reversing
Searching elements
ALGORITHM
Algorithm for performing list operations in Python:
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 Find length using len()
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
# LIST OPERATIONS IN PYTHON
# Creating a list
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)
# Indexing & Slicing
print("First element:", my_list[0])
print("Last element:", my_list[-1])
print("Slicing [1:4]:", my_list[1:4])
# Adding elements
my_list.append(60)
print("After append:", my_list)
37
my_list.insert(2, 25)
print("After insert at index 2:", my_list)
my_list.extend([70, 80])
print("After extend:", my_list)
# Removing elements
my_list.remove(25)
print("After remove 25:", my_list)
popped = my_list.pop()
print("After pop:", my_list, "Popped element:", popped)
del my_list[0]
print("After delete first element:", my_list)
# Updating elements
my_list[1] = 35
print("After updating index 1:", my_list)
# Sorting & reversing
my_list.sort()
print("After sorting:", my_list)
my_list.reverse()
print("After reversing:", my_list)
# Searching elements
print("Index of 40:", my_list.index(40))
print("Is 50 in list?", 50 in my_list)
OUTPUT
Original List: [10, 20, 30, 40, 50]
First element: 10
Last element: 50
Slicing [1:4]: [20, 30, 40]
After append: [10, 20, 30, 40, 50, 60]
After insert at index 2: [10, 20, 25, 30, 40, 50, 60]
After extend: [10, 20, 25, 30, 40, 50, 60, 70, 80]
After remove 25: [10, 20, 30, 40, 50, 60, 70, 80]
After pop: [10, 20, 30, 40, 50, 60, 70] Popped element: 80
After delete first element: [20, 30, 40, 50, 60, 70]
After updating index 1: [20, 35, 40, 50, 60, 70]
After sorting: [20, 35, 40, 50, 60, 70]
After reversing: [70, 60, 50, 40, 35, 20]
Index of 40: 3
Is 50 in list? True
RESULT
Thus, the list operation using python program executed successfully.
38
STRING MANIPULATIONS AND OPERATIONS ON LISTS, TUPLES, SETS,
AND DICTIONARIES.
EX.NO DATE
4C TUPLES OPERATIONS
AIM
To understand and demonstrate various tuple operations in Python, including creation,
indexing, slicing, concatenation, repetition, and use of built-in tuple functions for searching
and counting elements.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Indexing & slicing
Concatenation & repetition Results of tuple operations
A tuple of elements
Counting elements using count() including access,
(numbers, strings, or
Finding index using index() concatenation, repetition,
mixed)
Accessing tuple length using len() searching, and counting.
ALGORITHM
Algorithm for performing tuple operations in Python:
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
# TUPLE OPERATIONS IN PYTHON
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)
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 = (60, 70)
print("Concatenated Tuple:", my_tuple + tuple2)
print("Repeated Tuple:", my_tuple * 2)
# Tuple functions
print("Length of tuple:", len(my_tuple))
print("Count of 20:", my_tuple.count(20))
print("Index of 40:", my_tuple.index(40))
39
OUTPUT
Original Tuple: (10, 20, 30, 40, 50)
First element: 10
Last element: 50
Slicing [1:4]: (20, 30, 40)
Concatenated Tuple: (10, 20, 30, 40, 50, 60, 70)
Repeated Tuple: (10, 20, 30, 40, 50, 10, 20, 30, 40, 50)
Length of tuple: 5
Count of 20: 1
Index of 40: 3
RESULT
Thus, the tuples operation using python program executed successfully.
40
STRING MANIPULATIONS AND OPERATIONS ON LISTS, TUPLES, SETS,
AND DICTIONARIES.
EX.NO DATE
4D SETS OPERATIONS
AIM
To understand and demonstrate various set operations in Python, such as creation,
addition, removal, union, intersection, difference, and checking membership.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Adding & removing elements
Results of various set
Union, intersection, difference,
Two or more sets of operations including
symmetric difference
elements (numbers, addition, removal, union,
Membership checking
strings, etc.) intersection, difference, and
Iterating through sets
membership checks..
ALGORITHM
Algorithm for performing set operations in Python:
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
# SET OPERATIONS IN PYTHON
# Creating sets
set1 = {10, 20, 30, 40}
set2 = {30, 40, 50, 60}
print("Set1:", set1)
print("Set2:", set2)
# Adding elements
set1.add(70)
print("After add 70 to Set1:", set1)
set1.update([80, 90])
print("After update Set1 with [80, 90]:", set1)
# Removing elements
41
set1.remove(10) # raises error if element not present
set1.discard(20) # no error if element not present
print("After removing elements:", set1)
popped = set1.pop()
print("After pop:", set1, "Popped element:", popped)
# Set operations
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference (set1 - set2):", set1 - set2)
print("Symmetric Difference:", set1 ^ set2)
# Membership checking
print("Is 30 in Set1?", 30 in set1)
print("Is 100 not in Set2?", 100 not in set2)
OUTPUT
Set1: {40, 10, 20, 30}
Set2: {40, 50, 60, 30}
After add 70 to Set1: {70, 40, 10, 20, 30}
After update Set1 with [80, 90]: {70, 40, 10, 80, 20, 90, 30}
After removing elements: {70, 40, 80, 90, 30}
After pop: {40, 80, 90, 30} Popped element: 70
Union: {40, 80, 50, 90, 60, 30}
Intersection: {40, 30}
Difference (set1 - set2): {80, 90}
Symmetric Difference: {80, 50, 90, 60}
Is 30 in Set1? True
Is 100 not in Set2? True
RESULT
Thus, the set operation using python program executed successfully.
42
STRING MANIPULATIONS AND OPERATIONS ON LISTS, TUPLES, SETS,
AND DICTIONARIES.
EX.NO DATE
4E DICTIONARIES OPERATIONS
AIM
To understand and demonstrate various operations on dictionaries in Python,
including creation, accessing, updating, adding, removing items, and using built-in dictionary
methods.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Accessing values by keys
Adding/updating key-value pairs Results of dictionary
A dictionary with keys Removing items (del, pop, popitem) operations including
and values (numbers, Retrieving keys, values, and items accessing, updating, adding,
strings, or mixed) Checking key existence removing, and retrieving
Iterating over dictionary keys and values.
ALGORITHM
Algorithm for performing dictionary operations in Python:
1. Start
2. Create a dictionary or accept dictionary input from the user.
3. Access elements using keys.
4. Add or update key-value pairs.
5. Remove items using del, pop(), or popitem().
6. Use built-in dictionary methods:
o keys()
o values()
o items()
o get()
o update()
7. Check existence of keys using in.
8. Display results after each operation.
9. End
PROGRAM
# DICTIONARY OPERATIONS IN PYTHON
# Creating a dictionary
my_dict = {'Name': 'Alice', 'Age': 25, 'City': 'New York'}
print("Original Dictionary:", my_dict)
# Accessing elements
print("Name:", my_dict['Name'])
print("Age using get():", my_dict.get('Age'))
# Adding/updating elements
my_dict['Country'] = 'USA' # Add new key-value
43
my_dict['Age'] = 26 # Update existing key
print("After adding/updating:", my_dict)
# Removing elements
my_dict.pop('City') # Remove by key
print("After pop City:", my_dict)
popped_item = my_dict.popitem() # Remove last inserted item
print("After popitem:", my_dict, "Popped item:", popped_item)
print("After del Country:", my_dict)
# Dictionary methods
print("Keys:", my_dict.keys())
print("Values:", my_dict.values())
print("Items:", my_dict.items())
OUTPUT
Original Dictionary: {'Name': 'Alice', 'Age': 25, 'City': 'New York'}
Name: Alice
Age using get(): 25
After adding/updating: {'Name': 'Alice', 'Age': 26, 'City': 'New York', 'Country': 'USA'}
After pop City: {'Name': 'Alice', 'Age': 26, 'Country': 'USA'}
After popitem: {'Name': 'Alice', 'Age': 26} Popped item: ('Country', 'USA')
After del Country: {'Name': 'Alice', 'Age': 26}
Keys: dict_keys(['Name', 'Age'])
Values: dict_values(['Alice', 26])
Items: dict_items([('Name', 'Alice'), ('Age', 26)])
Is 'Name' in dictionary? True
Is 'City' in dictionary? False
RESULT
Thus, the dictionary operation using python program executed successfully.
44
OPENING, CLOSING, READING AND WRITING IN FORMATTED FILE
FORMAT AND SORT DATA.
EX.NO DATE
5 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.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Opening and closing files (open(),
close())
Writing data in formatted manner
(write(), f-string)
Formatted file containing
Student data (name, roll Reading data from file (read(),
student data and a display of
number, marks) readlines())
sorted data
Parsing data into a list or dictionary
Sorting data using sorted() with key
function
ALGORITHM
Algorithm for file operations and sorting:
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
# FILE HANDLING AND SORTING DATA IN PYTHON
45
next(f) # Skip header line
for line in f:
name, roll, marks = line.strip().split(",")
students.append({"Name": name, "Roll": int(roll), "Marks": int(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.
46
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
EX.NO DATE
6A 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.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Importing the numpy module
Creating arrays from data
Performing arithmetic, statistical,
Computed results, processed
Numerical data (lists, and sorting operations
arrays, sorted data, or
sequences, or matrices) Using built-in NumPy functions for
statistical measures
numerical computations
ALGORITHM
Algorithm for solving problems using NumPy:
1. Start
2. Import the NumPy module using import numpy as np.
3. Create NumPy arrays from lists or using built-in functions (np.array(), np.arange(),
np.zeros(), np.ones()).
4. Perform array operations:
o Arithmetic operations (+, -, *, /)
o Statistical operations (mean(), sum(), max(), min())
o Sorting arrays (np.sort())
5. Use NumPy functions for specific tasks:
o Reshape arrays (reshape())
o Generate random numbers (np.random)
o Perform matrix operations (dot(), transpose())
6. Display results.
7. End
PROGRAM
# USAGE OF NUMPY TO SOLVE PROBLEMS
import numpy as np
47
# Step 1: Create a NumPy array
data = np.array([10, 20, 15, 30, 25])
print("Original Array:", data)
48
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: [74 7 79 64 53]
Matrix Product:
[[19 22]
[43 50]]
RESULT
Thus, the NumPy module using python program executed successfully.
49
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
EX.NO DATE
6B SCIPY
AIM
To understand and demonstrate the usage of the SciPy library in Python for performing
scientific and numerical computations, such as integration, differentiation, interpolation, and
solving linear algebra problems.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Importing SciPy modules
Defining functions or matrices
Performing numerical computations: Computed results such as
Numerical data (lists, integration, differentiation, integrals, solutions to
sequences, or matrices) optimization, linear algebra equations, interpolated
Displaying results values, or optimized results
ALGORITHM
Algorithm for solving problems using SciPy:
1. Start
2. Import the required SciPy submodules, e.g., scipy.integrate, scipy.optimize,
scipy.linalg.
3. Define the function or data on which operations are to be performed.
4. Use the appropriate SciPy function for the task:
o quad() for integration
o solve() for linear equations
o interpolate() for data interpolation
o optimize() for root-finding or optimization
5. Compute the results.
6. Display the results.
7. End
PROGRAM
# SCIPY OPERATIONS IN PYTHON
50
# 1. Integration of a function
def f(x):
return x**2
result, error = integrate.quad(f, 0, 5) # integrate x^2 from 0 to 5
print("Integral of x^2 from 0 to 5:", result)
# 4. Interpolation example
from scipy.interpolate import interp1d
x_points = [0, 1, 2, 3, 4]
y_points = [0, 2, 4, 6, 8]
f_interp = interp1d(x_points, y_points)
y_new = f_interp(2.5)
print("Interpolated value at x=2.5:", y_new)
51
OUTPUT
Integral of x^2 from 0 to 5: 41.66666666666666
Solution of linear system: [2. 3.]
Root of x^3 - 4x - 9 = 2.706527954497935
Interpolated value at x=2.5: 5.0
RESULT
Thus, the SciPy module using python program executed successfully.
52
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
EX.NO DATE
6C PANDAS
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.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Creating Series and DataFrames
Accessing, adding, updating,
deleting data
Data in the form of Sorting and filtering data
Processed and analyzed data
lists, dictionaries, or Computing descriptive statistics
using Pandas operations
files (CSV/Excel) Reading/writing data from/to CSV or
Excel files
ALGORITHM
Algorithm for performing operations using Pandas:
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
53
PROGRAM
# PANDAS OPERATIONS IN PYTHON
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 = pd.DataFrame(data)
print("Original DataFrame:\n", df)
54
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
55
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.
56
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
EX.NO DATE
6D SCIKIT-LEARN
AIM
To understand and demonstrate how Scikit-learn (sklearn) can be used in Python for machine
learning tasks such as regression, classification, and model evaluation.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Importing datasets or creating
synthetic data
Data preprocessing and splitting
Dataset with features Selecting and training a model Predicted results and
(X) and labels (y) Making predictions evaluation metrics
Evaluating model performance
ALGORITHM
Algorithm for solving problems using Scikit-learn:
1. Start
2. Import required libraries: sklearn, numpy, pandas.
3. Load or create a dataset.
4. Preprocess data if necessary (handle missing values, encode categorical data).
5. Split dataset into training and testing sets using train_test_split.
6. Select a suitable machine learning model (e.g., LinearRegression,
DecisionTreeClassifier).
7. Train the model using fit() on training data.
8. Predict results on testing data using predict().
9. Evaluate the model using metrics like accuracy_score, mean_squared_error, etc.
10. Display results.
11. End
PROGRAM
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
57
# Sample dataset
X = np.array([[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]])
y = np.array([2,4,5,4,5,6,7,8,9,10])
# Predict
y_pred = model.predict(X_test)
# Evaluate
print("Mean Squared Error:", mean_squared_error(y_test, y_pred))
print("R2 Score:", r2_score(y_test, y_pred))
print("Predicted values:", y_pred)
OUTPUT
Mean Squared Error: 0.26652892561983493
R2 Score: 0.9601452073839499
Predicted values: [8.81818182 3.09090909 6.36363636 2.27272727]
RESULT
Thus, the sklearn module using python program executed successfully
58
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
EX.NO DATE
6E 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.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Mathematical operations (math)
Random number generation
Numbers, lists, (random) Computed results or
strings, or dates Date and time handling (datetime) processed data using built-in
depending on the task Statistical calculations (statistics) modules
File or directory operations (os)
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
# Demonstrating multiple Python built-in modules
import math
import random
import datetime
import statistics
import os
# Math module
num = 16
print("Square root:", math.sqrt(num))
print("Factorial of 5:", math.factorial(5))
59
# Random module
print("Random integer between 1 and 10:", random.randint(1, 10))
print("Random choice from list:", random.choice([10, 20, 30, 40]))
# Datetime module
now = datetime.datetime.now()
print("Current date and time:", now)
# Statistics module
data = [10, 20, 30, 40, 50]
print("Mean:", statistics.mean(data))
print("Median:", statistics.median(data))
# OS module
print("Current working directory:", os.getcwd())
print("List of files in directory:", os.listdir())
OUTPUT
Square root: 4.0
Factorial of 5: 120
Random integer between 1 and 10: 4
Random choice from list: 30
Current date and time: 2025-09-05 22:36:49.342000
Mean: 30
Median: 30
Current working directory: /drive
List of files in directory: ['PYTHON LAB.ipynb', 'Untitled1.ipynb', 'students.txt',
'README.md', 'data', 'notebooks']
RESULT
Thus, the Built-in modules using python program executed successfully.
60
USAGE OF MODULES AND PACKAGES TO SOLVE PROBLEMS
EX.NO DATE
6F BUILT-IN MODULES
AIM
To understand and demonstrate the creation and usage of user-defined modules in Python
to organize code into reusable components for solving problems efficiently.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Creating reusable functions or
classes
Importing the module in a main
Data (numbers, program Computed results using
strings, lists, etc.) to Calling module functions to functions defined in the
operate on perform tasks user-defined module
Organizing code for better
readability and maintainability
ALGORITHM
1. Start
2. Create a Python file (.py) containing functions, classes, or variables (this is the user-
defined module).
3. Save the module file in the same directory as the main program (or ensure it is in
Python path).
4. In the main program, import the module using:
o import module_name or
o from module_name import function_name
5. Use the functions or variables from the module to perform tasks.
6. Display the results.
7. End
PROGRAM
Step 1: Create module file mymath.py
# mymath.py - User-defined module
61
def subtract(a, b):
return a - b
RESULT
Thus, the User-Defined modules using python program executed successfully.
62
PROJECT
EX.NO DATE
7A 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.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
Using lists or dictionaries to store Store student data
student data. and display it in a
Student information Adding, updating, deleting, and formatted manner.
such as Name, Roll displaying records. Perform operations
Number, Age, Marks. Optionally, saving data to a file for like search, update,
persistence. and delete.
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
PROGRAM
# Python Mini Project: Student Record Management System
# List to store student records
students = []
63
marks = input("Enter Marks: ")
student = {"Name": name, "Roll": roll, "Age": age, "Marks": marks}
students.append(student)
print("Student added successfully!\n")
64
s["Marks"] = input("Enter new Marks: ")
print("Student updated successfully!\n")
return
print("Student not found!\n")
if choice == '1':
add_student()
elif choice == '2':
65
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: ARUN
Enter Roll Number: 104CSE001
Enter Age: 22
Enter Marks: 96 98 99
Student added successfully!
66
1. Add Student
2. Display Students
3. Search Student
4. Update Student
5. Delete Student
6. Exit
Enter your choice: 2
Student Records:
{'Name': 'ARUN', 'Roll': '104CSE001', 'Age': '22', 'Marks': '96 98 99'}
CONCLUSION
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.
Can be extended by adding file handling to make data persistent or using classes to
make it object-oriented.
67
PROJECT
EX.NO DATE
7B 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.
PROBLEM ANALYSIS CHART (PAC)
INPUT PROCESS OUTPUT
User details: Name, 1. Storing account information Updated account
Account Number, using dictionaries or lists balance
Balance 2. Using functions to
modularize operations Transaction
Transactions: Deposit confirmation
3. Taking user input for
amount, Withdraw
transactions Account details
amount 4. Updating balances and
. validating withdrawals
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
PROGRAM
# Python Mini Project: Bank Management System
accounts = {}
# Create a new account
def create_account():
name = input("Enter your name: ")
68
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")
69
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")
70
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: ARUN
Enter account number: 123654789
Enter initial deposit: 14785623
Account created successfully!
--- Bank Management System ---
1. Create Account
2. Deposit Money
3. Withdraw Money
4. Display Account Details
5. Exit
CONCLUSION
This mini project demonstrates Python basics like dictionaries, functions, loops, and
conditional statements.
Provides a simulation of real-world banking operations.
Helps beginners understand CRUD operations (Create, Read, Update, Delete) in
Python.
Can be extended by adding:
o File handling for persistent storage
o User authentication with passwords
o Interest calculation or multiple account types
71