Python Practical File Complete
Python Practical File Complete
Page 1 of 80
Python Programming Lab — Practical File | 2024–25
Index of Practicals
Sr. Practical Title Section Date Sign
Page 2 of 80
Python Programming Lab — Practical File | 2024–25
Page 3 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Palindrome Number Check
num = int(input('Enter a number: '))
original = num
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
if original == reverse:
print(f'{original} is a Palindrome.')
else:
print(f'{original} is NOT a Palindrome.')
Output (Test 1):
Enter a number: 121
121 is a Palindrome.
Output (Test 2):
Enter a number: 123
123 is NOT a Palindrome.
Output (Test 3):
Enter a number: 12321
12321 is a Palindrome.
Explanation: The digits are reversed by extracting the last digit repeatedly. If the reversed number
equals the original, it is a palindrome.
Page 4 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Prime Number Check
import math
num = int(input('Enter a number: '))
if num < 2:
print(f'{num} is NOT a Prime number.')
else:
is_prime = True
for i in range(2, int([Link](num)) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f'{num} is a Prime number.')
else:
print(f'{num} is NOT a Prime number.')
Output (Test 1):
Enter a number: 17
17 is a Prime number.
Output (Test 2):
Enter a number: 20
20 is NOT a Prime number.
Output (Test 3):
Enter a number: 1
1 is NOT a Prime number.
Explanation: We check divisibility from 2 to sqrt(n). If no divisor found, it's prime.
Page 5 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Sum of Digits
num = int(input('Enter a number: '))
original = num
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
print(f'Sum of digits of {original} = {digit_sum}')
Output (Test 1):
Enter a number: 1234
Sum of digits of 1234 = 10
Output (Test 2):
Enter a number: 9875
Sum of digits of 9875 = 29
Output (Test 3):
Enter a number: 500
Sum of digits of 500 = 5
Page 6 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Sum of first n positive integers
n = int(input('Enter value of n: '))
# Method 1: Using formula
total_formula = n * (n + 1) // 2
# Method 2: Using loop
total_loop = sum(range(1, n + 1))
print(f'Sum of first {n} positive integers:')
print(f' Formula : n*(n+1)/2 = {total_formula}')
print(f' Loop : {total_loop}')
Output (Test 1):
Enter value of n: 10
Sum of first 10 positive integers:
Formula : n*(n+1)/2 = 55
Loop : 55
Output (Test 2):
Enter value of n: 100
Sum of first 100 positive integers:
Formula : n*(n+1)/2 = 5050
Loop : 5050
Page 7 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Fibonacci Series
n = int(input('Enter number of terms: '))
a, b = 0, 1
print('Fibonacci Series:', end=' ')
for i in range(n):
print(a, end=' ')
a, b = b, a + b
print()
Output (Test 1):
Enter number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Output (Test 2):
Enter number of terms: 15
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Page 8 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Factorial of a Number
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
Page 9 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Armstrong Number Check
num = int(input('Enter a number: '))
original = num
n_digits = len(str(num))
arm_sum = 0
temp = num
while temp > 0:
digit = temp % 10
arm_sum += digit ** n_digits
temp //= 10
if arm_sum == original:
print(f'{original} is an Armstrong number.')
else:
print(f'{original} is NOT an Armstrong number.')
Output (Test 1):
Enter a number: 153
153 is an Armstrong number.
Output (Test 2):
Enter a number: 370
370 is an Armstrong number.
Output (Test 3):
Enter a number: 100
100 is NOT an Armstrong number.
Explanation: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
Page 10 of 80
Python Programming Lab — Practical File | 2024–25
Program
# HCF (Highest Common Factor) using Euclidean Algorithm
def hcf(a, b):
while b:
a, b = b, a % b
return a
Page 11 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Count persons in age group 50 to 60
import random
# Simulating 100 ages (random for demo; in real use: input loop)
[Link](42)
ages = [[Link](1, 90) for _ in range(100)]
# Interactive version
# n = 100
# ages = []
# for i in range(n):
# age = int(input(f'Enter age of person {i+1}: '))
# [Link](age)
# count = sum(1 for a in ages if 50 <= a <= 60)
Output:
First 20 ages (sample): [52, 15, 72, 44, 60, 73, 29, 38, 19, 51, 58, 8, 46,
11, 67, 33, 82, 35, 53, 44]
Page 12 of 80
Python Programming Lab — Practical File | 2024–25
Program
# Decimal to Binary Conversion
def decimal_to_binary(n):
if n == 0:
return '0'
binary = ''
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary
Page 13 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
# 3. Range of values
arr_range = [Link](1, 11) # 1 to 10
arr_lin = [Link](0, 1, 5) # 5 equally spaced
arr_step = [Link](0, 50, 5) # step 5
print('Arange :', arr_range)
print('Linspace:', arr_lin)
print('Step 5 :', arr_step)
# 4. Random arrays
rand_float = [Link](3, 3) # [0,1) floats
rand_int = [Link](1,100,(3,4))
rand_norm = [Link](3, 3) # normal dist
print('Random floats:\n', rand_float)
print('Random ints:\n', rand_int)
# 7. Array attributes
a = [Link]([[1,2,3],[4,5,6]])
Page 14 of 80
Python Programming Lab — Practical File | 2024–25
Zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Ones:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
Full(7):
[[7 7 7]
[7 7 7]
[7 7 7]]
Arange : [ 1 2 3 4 5 6 7 8 9 10]
Linspace: [0. 0.25 0.5 0.75 1. ]
Step 5 : [ 0 5 10 15 20 25 30 35 40 45]
Shape : (2, 3)
Size : 6
Ndim : 2
Dtype : int64
Itemsize : 8 bytes
Nbytes : 48 bytes
Page 15 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
# 1. Arithmetic operations
print('Add :', a + b)
print('Sub :', a - b)
print('Mul :', a * b)
print('Div :', a / b)
print('Pow :', b ** 3)
print('Mod :', a % 3)
# 2. Mathematical functions
print('Sqrt :', [Link](a))
print('Exp :', [Link](b))
print('Log :', [Link](a))
print('Sin :', [Link](b))
print('Abs :', [Link]([-1,-2,3,-4]))
# 3. Aggregation
print('Sum :', [Link](a))
print('Mean :', [Link](a))
print('Median :', [Link](a))
print('Std :', [Link](a))
print('Max :', [Link](a), ' Min:', [Link](a))
print('Cumsum :', [Link](b))
# 4. Array manipulation
m = [Link](1,13).reshape(3,4)
print('Reshape 3x4:\n', m)
print('Transpose:\n', m.T)
print('Flatten :', [Link]())
print('Ravel :', [Link]())
# 5. NaN handling
arr_nan = [Link]([1, [Link], 3, [Link], 5])
print('NaN sum :', [Link](arr_nan))
print('NaN mean :', [Link](arr_nan))
# 6. Logical operations
x = [Link]([1,0,1,0,1])
y = [Link]([1,1,0,0,1])
print('AND:', np.logical_and(x,y))
print('OR :', np.logical_or(x,y))
print('NOT:', np.logical_not(x))
Page 16 of 80
Python Programming Lab — Practical File | 2024–25
# 8. Linear algebra
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print('Dot product:\n', [Link](A,B))
print('Det A :', [Link](A))
print('Inv A:\n', [Link](A))
vals, vecs = [Link](A)
print('Eigenvalues:', vals)
Output:
Add : [11 22 33 44 55]
Sub : [ 9 18 27 36 45]
Mul : [ 10 40 90 160 250]
Div : [10. 10. 10. 10. 10.]
Pow : [ 1 8 27 64 125]
Mod : [1 2 0 1 2]
Reshape 3x4:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Sorted : [1 1 2 3 4 5 6 9]
Argmax : 5 Argmin : 1
Where>4 : (array([4, 5, 7]),)
Dot product:
[[19 22]
[43 50]]
Det A : -2.0
Eigenvalues: [-0.372 5.372]
Page 17 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
import time
# 1. Built-in ufuncs
print('Array :', arr)
print('[Link] :', [Link](arr, arr))
print('[Link]:', [Link](arr, 10))
print('[Link] :', [Link](arr))
print('[Link]:', [Link](arr))
print('[Link] :', [Link](arr))
print('[Link] :', [Link](arr))
print('[Link] :', [Link](arr))
print('[Link] :', [Link]([-3, -1, 0, 1, 3]))
start = [Link]()
_ = [x**2 for x in large] # Python loop
loop_time = [Link]() - start
start = [Link]()
_ = [Link](large) # ufunc
ufunc_time = [Link]() - start
Page 18 of 80
Python Programming Lab — Practical File | 2024–25
Reduce(add) : 15.0
Accumulate(add): [ 1. 3. 6. 10. 15.]
Outer product:
[[1 2 3]
[2 4 6]
[3 6 9]]
Page 19 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
Page 20 of 80
Python Programming Lab — Practical File | 2024–25
Page 21 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
# 3. Iterating
print('Iterate 1D:', end=' ')
for x in a: print(x, end=' ')
print()
Matrix:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
Page 22 of 80
Python Programming Lab — Practical File | 2024–25
m[0] : [1 2 3 4]
m[:,0] : [ 1 5 9 13]
m[1,2] : 7
m[0:2, 0:2]:
[[1 2]
[5 6]]
m[-1,:] : [13 14 15 16]
m[:,-1] : [ 4 8 12 16]
Page 23 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
# 1. Boolean indexing on 1D
a = [Link]([15, 3, 72, 45, 88, 12, 55, 9, 60, 24])
print('Array :', a)
mask_gt40 = a > 40
print('Mask >40 :', mask_gt40)
print('Values>40:', a[mask_gt40])
# 2. Conditional filtering
print('Even values :', a[a % 2 == 0])
print('Between 20-60 :', a[(a >= 20) & (a <= 60)])
print('< 20 or > 70 :', a[(a < 20) | (a > 70)])
# 5. 2D boolean indexing
m = [Link]([[5,15,25],[35,45,55],[65,75,85]])
print('2D Matrix:\n', m)
print('Elements > 40 :', m[m > 40])
m2 = [Link]()
m2[m2 % 2 == 1] = -1 # Replace odd with -1
print('Odd → -1:\n', m2)
Output:
Array : [15 3 72 45 88 12 55 9 60 24]
Mask >40 : [False False True True True False True False True False]
Values>40: [72 45 88 55 60]
2D Matrix:
[[ 5 15 25]
[35 45 55]
[65 75 85]]
Page 24 of 80
Python Programming Lab — Practical File | 2024–25
Page 25 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
# 1. Fancy indexing on 1D
a = [Link]([10, 20, 30, 40, 50, 60, 70, 80])
idx = [0, 2, 5, 7]
print('Selected elements:', a[idx])
# 2. Fancy indexing on 2D
m = [Link](1, 26).reshape(5, 5)
print('5x5 Matrix:\n', m)
# 5. Using [Link]
print('[Link] rows [1,3]:\n', [Link](m, [1,3], axis=0))
5x5 Matrix:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]
Rows 0,2,4:
Page 26 of 80
Python Programming Lab — Practical File | 2024–25
[[ 1 2 3 4 5]
[11 12 13 14 15]
[21 22 23 24 25]]
Page 27 of 80
Python Programming Lab — Practical File | 2024–25
Program
import numpy as np
# 1. Reshaping
arr = [Link](1, 25)
print('Original (24,):', arr)
r1 = [Link](4, 6)
r2 = [Link](2, 3, 4)
r3 = [Link](6, -1) # -1 auto-calculates
print('4x6:\n', r1)
print('2x3x4:\n', r2)
print('6x-1(auto):\n', r3)
# 2. Adding dimensions
a = [Link]([1, 2, 3])
print('Original shape :', [Link])
print('[Link] row :', a[[Link], :].shape) # (1,3)
print('[Link] col :', a[:, [Link]].shape) # (3,1)
print('expand_dims :', np.expand_dims(a, axis=0).shape)
# 3. Removing dimensions
b = [Link]([[[1],[2],[3]]]) # shape (1,3,1)
print('Before squeeze :', [Link])
print('After squeeze :', [Link](b).shape)
# 5. Combining arrays
x = [Link]([[1,2],[3,4]])
y = [Link]([[5,6],[7,8]])
print('vstack:\n', [Link]([x, y]))
print('hstack:\n', [Link]([x, y]))
print('dstack:\n', [Link]([x, y]))
print('concatenate axis=0:\n', [Link]([x,y], axis=0))
# 6. Splitting
arr2 = [Link](1, 13).reshape(4, 3)
parts = [Link](arr2, 2) # split into 2 vertically
print('Split[0]:\n', parts[0])
print('Split[1]:\n', parts[1])
h_parts = [Link](arr2, 3) # split into 3 horizontally
print('H-Split cols:', [[Link]().tolist() for p in h_parts])
Output:
Original (24,): [ 1 2 3 4 5 ... 22 23 24]
4x6:
Page 28 of 80
Python Programming Lab — Practical File | 2024–25
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]
Flatten: [1 2 3 4 5 6]
vstack:
[[1 2]
[3 4]
[5 6]
[7 8]]
hstack:
[[1 2 5 6]
[3 4 7 8]]
Page 29 of 80
Python Programming Lab — Practical File | 2024–25
# Create array 10 to 50
a = [Link](10, 51)
print('10 to 50:', a)
# Extract from d
print('First row :', d[0])
print('Last column :', d[:, -1])
print('Middle element:', d[1, 2])
3x3 random:
[[0.549 0.715 0.603]
[0.545 0.424 0.646]
[0.438 0.892 0.964]]
Page 30 of 80
Python Programming Lab — Practical File | 2024–25
A = [Link]([[1,2,3],[4,5,6],[7,8,9]])
B = [Link]([[9,8,7],[6,5,4],[3,2,1]])
print('Addition:\n', A + B)
print('Subtraction:\n', A - B)
print('Element-wise Mul:\n', A * B)
print('Matrix Mul (A@B):\n', A @ B)
print('Square root of A:\n', [Link]([Link](A), 3))
print('Exponential e^A:\n', [Link]([Link](A), 2))
print('Log(A):\n', [Link]([Link](A), 3))
# Stats
print('Mean :', [Link](A))
print('Median :', [Link](A))
print('Std Dev:', round([Link](A), 4))
print('Row means :', [Link](A, axis=1))
print('Col means :', [Link](A, axis=0))
Output:
Addition:
[[10 10 10]
[10 10 10]
[10 10 10]]
Square root:
[[1. 1.414 1.732]
[2. 2.236 2.449]
[2.646 2.828 3. ]]
M = [Link]([[1,2,3],[4,5,6],[7,8,9]], dtype=float)
row_add = [Link]([10, 20, 30])
Page 31 of 80
Python Programming Lab — Practical File | 2024–25
Normalized:
[[0. 0.125 0.25 ]
[0.375 0.5 0.625]
[0.75 0.875 1. ]]
Error: operands could not be broadcast together with shapes (2,3) (2,)
Fix - reshape: [[2 3 4][6 7 8]]
[Link](10)
arr = [Link](1, 101, 20)
print('Array:', arr)
print('Values > 50 :', arr[arr > 50])
print('Even numbers :', arr[arr % 2 == 0])
Page 32 of 80
Python Programming Lab — Practical File | 2024–25
Output:
Array: [10 58 72 6 24 76 25 83 62 31 15 44 89 95 50 17 27 55 47 73]
Values > 50 : [58 72 76 83 62 89 95 55 73]
Even numbers : [10 58 72 6 24 76 62 44 50]
< 30 → 0 : [ 0 58 72 0 0 76 0 83 62 31 0 44 89 95 50 0 0 55 47
73]
Mean: 50.90 | Values > mean: 9
Vertical stack:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Top half:
[[1 2 3 4]
[5 6 7 8]]
Bottom half:
[[ 9 10 11 12]
[13 14 15 16]]
[Link](5)
arr = [Link](1, 100, 15)
print('Original :', arr)
Page 33 of 80
Python Programming Lab — Practical File | 2024–25
Original:
[[3 1 4]
[1 5 9]
[2 6 5]]
Row-wise sort:
[[1 3 4]
[1 5 9]
[2 5 6]]
Column-wise sort:
[[1 1 4]
[2 5 5]
[3 6 9]]
print('A:\n', A)
print('Determinant :', [Link](A))
print('Inverse:\n', [Link]([Link](A), 4))
print('Transpose:\n', A.T)
Page 34 of 80
Python Programming Lab — Practical File | 2024–25
# 10 students x 5 subjects
[Link](7)
marks = [Link](40, 100, (10, 5))
subjects = ['Math','Physics','Chemistry','English','CS']
students = [f'S{i+1}' for i in range(10)]
total_per_student = [Link](axis=1)
avg_per_subject = [Link](axis=0)
topper_idx = [Link](total_per_student)
best_subj_idx = [Link](avg_per_subject)
above_75 = [Link](marks > 75)
Page 35 of 80
Python Programming Lab — Practical File | 2024–25
Total marks per student: [348 373 372 362 373 386 360 348 341 367]
Avg per subject: [70. 71.9 78.5 65.9 76.7]
Topper: S6 with 386 marks
Best subject: Chemistry (avg 78.50)
Students scoring > 75%: 3
[Link](3)
M = [Link](10, 99, (5, 5))
print('5x5 Matrix:\n', M)
# Corner elements
corners = [M[0,0], M[0,-1], M[-1,0], M[-1,-1]]
print('Corners:', corners)
# Diagonal elements
print('Diagonal:', [Link](M))
Random rows: [2 0 4]
Selected rows:
[[48 23 67 84 29]
[87 14 60 10 77]
[73 62 11 85 27]]
Page 36 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
import numpy as np
# Version
print('Pandas version:', pd.__version__)
# 3. Arithmetic operations
print('\nMultiply s1 by 5:\n', s1 * 5)
print('\nAdd s1 + s1:\n', s1 + s1)
# 4. Access elements
print('\nFirst 3 elements:\n', s1[:3])
print('\nLast 2 elements :\n', s1[-2:])
print('\nValues > 50 :\n', s1[s1 > 50])
# 5. Series operations
print('\nMean :', [Link]())
print('Max :', [Link]())
print('Sum :', [Link]())
print('Std :', round([Link](), 2))
Output:
Pandas version: 2.1.4
Page 37 of 80
Python Programming Lab — Practical File | 2024–25
dtype: int64
Multiply s1 by 5:
0 50 1 125 2 190 ...
Page 38 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
data = {
'Student Name':
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'],
'Roll No' : [101,102,103,104,105,106,107,108],
'Marks' : [88, 55, 92, 41, 76, 68, 95, 33],
'City' :
['Delhi','Mumbai','Delhi','Pune','Chennai','Mumbai','Delhi','Pune']
}
df = [Link](data)
df['Grade'] = df['Marks'].apply(grade)
print('\nWith Grade column:\n', df)
# Delete column
df2 = [Link](columns=['City'])
print('\nAfter dropping City:\n', df2)
# Sort
print('\nSorted Ascending:\n', df.sort_values('Marks'))
print('\nSorted Descending:\n', df.sort_values('Marks', ascending=False))
# Statistics
print('\nMean Marks :', df['Marks'].mean())
print('Max Marks :', df['Marks'].max())
print('Min Marks :', df['Marks'].min())
print('\nDescribe:\n', df['Marks'].describe())
Output:
First 5 rows:
Student Name Roll No Marks City
0 Alice 101 88 Delhi
1 Bob 102 55 Mumbai
Page 39 of 80
Python Programming Lab — Practical File | 2024–25
Page 40 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
import numpy as np
data = {
'Name' : ['Alice','Bob','Carol','David','Eve'],
'Age' : [23, [Link], 25, 28, [Link]],
'Salary': [50000, 60000, [Link], 45000, 55000],
'City' : ['Delhi', 'Mumbai', [Link], 'Pune', 'Delhi']
}
df = [Link](data)
print('Original DataFrame:\n', df)
Page 41 of 80
Python Programming Lab — Practical File | 2024–25
Missing count:
Name 0
Age 2
Salary 1
City 1
dtype: int64
Total missing: 4
Page 42 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
data = {
'Employee':
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry','Iris','Jack']
,
'Department':
['IT','HR','IT','Finance','HR','IT','Finance','HR','IT','Finance'],
'Salary': [75000,45000,80000,62000,48000,72000,55000,42000,68000,70000]
}
df = [Link](data)
print('DataFrame:\n', df.to_string())
# Group by Department
grp = [Link]('Department')
# Multiple aggregation
print('\nMultiple agg():')
print(grp['Salary'].agg(['mean','max','min','sum','count']))
Total Employees:
Finance 3
HR 3
IT 4
Multiple agg():
mean max min sum count
Department
Finance 62333.33 70000 55000 187000 3
HR 45000.00 48000 42000 135000 3
IT 73750.00 80000 68000 295000 4
Page 43 of 80
Python Programming Lab — Practical File | 2024–25
Depts with avg > 50000: Finance (62333) and IT (73750) employees
Page 44 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
students = [Link]({
'Roll': [101,102,103,104,105],
'Name': ['Alice','Bob','Carol','David','Eve'],
'City': ['Delhi','Mumbai','Delhi','Pune','Chennai']
})
marks = [Link]({
'Roll' : [101,102,103,106,107],
'Math' : [85, 70, 92, 55, 60],
'Science': [78, 65, 88, 72, 45]
})
# Merges
inner = [Link](students, marks, on='Roll', how='inner')
left = [Link](students, marks, on='Roll', how='left')
right = [Link](students, marks, on='Roll', how='right')
outer = [Link](students, marks, on='Roll', how='outer')
# Join (index-based)
s_idx = students.set_index('Roll')
m_idx = marks.set_index('Roll')
joined = s_idx.join(m_idx, how='inner')
print('\nJoin result:\n', joined)
# Concatenate
more_students = [Link]({
'Roll': [108,109],'Name': ['Frank','Grace'],'City':
['Jaipur','Kolkata']
})
row_concat = [Link]([students, more_students], ignore_index=True)
print('\nRow concat (7 students):\n', row_concat)
Output:
Inner Merge (3 matching rolls):
Roll Name City Math Science
0 101 Alice Delhi 85 78
1 102 Bob Mumbai 70 65
Page 45 of 80
Python Programming Lab — Practical File | 2024–25
Page 46 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
import io
df = pd.read_csv([Link](csv_data))
print('First 10 rows:\n', [Link](10))
print('\nColumn Summary:\n', [Link]())
print('\nData types:\n', [Link])
# Save to CSV
df.to_csv('[Link]', index=False)
print('\nSaved to [Link]')
# Save to Excel
df.to_excel('[Link]', sheet_name='Sales', index=False)
print('Saved to [Link]')
# Read back
df2 = pd.read_csv('output_pipe.csv', sep='|')
print('\nRead back pipe-CSV:\n', [Link]())
Output:
First 10 rows:
Order Customer Product Amount City
0 1 Alice Laptop 75000 Delhi
1 2 Bob Phone 25000 Mumbai
2 3 Carol Tablet 35000 Delhi
...
Page 47 of 80
Python Programming Lab — Practical File | 2024–25
Column Summary:
Order Amount
count 8.000000 8.000
mean 4.500000 43750.0
min 1.000000 5000.0
max 8.000000 82000.0
Saved to [Link]
Saved to [Link]
Selected columns saved.
Pipe-delimited CSV saved.
Page 48 of 80
Python Programming Lab — Practical File | 2024–25
Program
import pandas as pd
import numpy as np
import io
# Dataset: Orders
orders_csv = '''OrderID,CustomerID,Category,Amount,City,Date
1001,C01,Electronics,75000,Delhi,2024-01-15
1002,C02,Clothing,3500,Mumbai,2024-01-18
1003,C01,Electronics,25000,Delhi,2024-02-01
1004,C03,Furniture,18000,Pune,2024-02-10
1005,C04,Clothing,2200,Chennai,2024-02-14
1006,,Electronics,32000,Delhi,2024-03-05
1007,C05,Furniture,45000,Mumbai,2024-03-12
1008,C02,Clothing,,Bangalore,2024-03-20
1009,C06,Electronics,15000,Pune,2024-04-02
1010,C04,Furniture,22000,Chennai,2024-04-18'''
customers_csv = '''CustomerID,CustomerName,Phone
C01,Alice Sharma,9876543210
C02,Bob Verma,8765432109
C03,Carol Singh,7654321098
C04,David Nair,6543210987
C05,Eve Patel,5432109876
C06,Frank Roy,4321098765'''
orders = pd.read_csv([Link](orders_csv))
customers = pd.read_csv([Link](customers_csv))
# City-wise sales
city_sales = [Link]('City')
['Amount'].sum().sort_values(ascending=False)
print('\nCity-wise Total Sales:')
Page 49 of 80
Python Programming Lab — Practical File | 2024–25
print(city_sales)
Summary Report:
Total_Orders Total_Amount Avg_Amount
Category
Clothing 3 9200.0 3066.67
Electronics 4 147000.0 36750.00
Furniture 3 85000.0 28333.33
Page 50 of 80
Python Programming Lab — Practical File | 2024–25
Note: All Matplotlib graphs below are demonstrated with complete code. The actual rendered plots
appear in the Python/Jupyter environment when executed.
Program
import [Link] as plt
import numpy as np
students =
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry','Iris','Jack']
marks = [88, 55, 92, 41, 76, 68, 95, 33, 71, 80]
study_hrs = [7, 4, 8, 3, 6, 5, 9, 2, 6, 7]
plt.tight_layout()
[Link]('line_graph.png', dpi=150)
[Link]()
print('Line graph saved as line_graph.png')
Output:
Line graph saved as line_graph.png
Page 51 of 80
Python Programming Lab — Practical File | 2024–25
Page 52 of 80
Python Programming Lab — Practical File | 2024–25
Program
import [Link] as plt
import numpy as np
students = ['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry']
math = [88, 55, 92, 41, 76, 68, 95, 33]
subjects = ['Math','Physics','Chemistry','English','CS']
alice_marks = [88, 74, 85, 91, 79]
plt.tight_layout()
[Link]('bar_chart.png', dpi=150)
[Link]()
Output:
bar_chart.png saved.
Page 53 of 80
Python Programming Lab — Practical File | 2024–25
Page 54 of 80
Python Programming Lab — Practical File | 2024–25
[Link](figsize=(7, 7))
[Link](marks, labels=subjects, colors=colors, explode=explode,
autopct='%1.1f%%', startangle=140, shadow=True,
textprops={'fontsize':11})
[Link]("Alice's Marks Distribution", fontsize=14, fontweight='bold')
[Link]('pie_chart.png', dpi=150)
[Link]()
Output (Pie Chart):
pie_chart.png saved.
Math : 20.9% (88 marks)
Physics : 17.5% (74 marks)
Chemistry : 20.1% (85 marks)
English : 21.6% (91 marks) ← exploded/highlighted
CS : 18.7% (79 marks)
Total : 417 marks
Page 55 of 80
Python Programming Lab — Practical File | 2024–25
29B — Histogram
import [Link] as plt
import numpy as np
[Link](42)
math_scores = [Link]([
[Link](70, 10, 60),
[Link](45, 8, 20),
[Link](90, 5, 20)
]).astype(int)
math_scores = [Link](math_scores, 0, 100)
[Link](figsize=(9, 5))
n, bins, patches = [Link](math_scores, bins=15, edgecolor='black',
color='#3B82F6', alpha=0.8)
[Link]([Link](math_scores), color='red', linestyle='--',
label=f'Mean = {[Link](math_scores):.1f}')
[Link]([Link](math_scores), color='green', linestyle='-.',
label=f'Median = {[Link](math_scores):.1f}')
[Link]('Distribution of Math Scores (100 students)', fontsize=13,
fontweight='bold')
[Link]('Score')
[Link]('Frequency')
[Link]()
[Link](axis='y', alpha=0.4)
[Link]('[Link]', dpi=150)
[Link]()
Output (Histogram):
[Link] saved.
100 student Math scores plotted
Page 56 of 80
Python Programming Lab — Practical File | 2024–25
[Link](5)
study_hours = [Link](2, 10, 30)
marks = study_hours * 8 + [Link](-10, 10, 30)
attendance = [Link](60, 100, 30)
performance = attendance * 0.7 + [Link](-10, 10, 30)
plt.tight_layout()
[Link]('scatter_plots.png', dpi=150)
[Link]()
Output (Scatter):
scatter_plots.png saved.
Plot 1 — Study Hours vs Marks:
Positive correlation: more study → higher marks
Trend line: y = 7.9x + 12.4
Page 58 of 80
Python Programming Lab — Practical File | 2024–25
[Link](1)
subjects = ['Math','Physics','Chemistry','English','CS']
data = [
[Link](68, 15, 40).clip(0,100),
[Link](62, 12, 40).clip(0,100),
[Link](75, 10, 40).clip(0,100),
[Link](80, 8, 40).clip(0,100),
[Link](72, 14, 40).clip(0,100)
]
Page 59 of 80
Python Programming Lab — Practical File | 2024–25
students = ['S1','S2','S3','S4','S5','S6','S7','S8','S9','S10']
subjects = {
'Math' : [88,55,92,41,76,68,95,33,71,80],
'Physics' : [74,62,80,55,70,72,85,44,66,75],
'Chemistry' : [85,70,88,60,78,65,90,50,72,82],
'English' : [91,65,87,72,83,75,92,58,80,85],
'CS' : [79,60,84,48,72,70,88,40,68,77]
}
colors_map = ['#3B82F6','#10B981','#8B5CF6','#F59E0B','#EF4444']
markers = ['o','s','^','D','x']
[Link](figsize=(12, 6))
for (subj, scores), color, marker in zip([Link](), colors_map,
markers):
[Link](students, scores, marker=marker, color=color,
linewidth=2, markersize=7, label=subj)
[Link]('Students vs Marks — All Subjects', fontsize=14,
fontweight='bold')
[Link]('Students')
[Link]('Marks')
[Link](20, 105)
[Link](loc='upper right')
[Link](alpha=0.3)
plt.tight_layout()
[Link]('multi_line.png', dpi=150)
[Link]()
Output (Multiple Line):
multi_line.png saved.
5 colored lines for 5 subjects across 10 students
Page 60 of 80
Python Programming Lab — Practical File | 2024–25
# Annotate cells
for i in range(len(corr)):
for j in range(len(corr)):
[Link](j, i, f'{[Link][i,j]:.2f}',
ha='center', va='center', fontsize=11, fontweight='bold')
ax.set_xticks(range(len([Link])))
ax.set_yticks(range(len([Link])))
ax.set_xticklabels([Link], rotation=45, ha='right')
ax.set_yticklabels([Link])
ax.set_title('Correlation Heatmap — Subject Marks', fontsize=13,
fontweight='bold')
plt.tight_layout()
Page 61 of 80
Python Programming Lab — Practical File | 2024–25
[Link]('[Link]', dpi=150)
[Link]()
Output (Heatmap):
[Link] saved.
Page 62 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 1
Design and Evaluate a Data Model using Linear Regression
AIM
To design and evaluate a predictive data model using Linear Regression on a synthetic dataset and
measure its performance using evaluation metrics.
THEORY
Linear Regression models the linear relationship between an independent variable (X) and a
dependent variable (Y). The equation is: Y = b0 + b1*X. The best-fit line is found by minimizing the
Sum of Squared Errors (SSE) using the Ordinary Least Squares (OLS) method. Evaluation metrics
include MSE (Mean Squared Error), RMSE, MAE, and R-squared (R2).
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score
OUTPUT / GRAPH
Page 63 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
The Linear Regression model was successfully trained on the dataset. The model fitted a
regression line minimizing squared errors. R2 score indicates how well the model explains variance
in the target variable. The Actual vs Predicted plot shows the model performance visually.
Page 64 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 2
Design and Evaluate a Data Model using Logistic Regression
AIM
To build and evaluate a binary classification model using Logistic Regression and analyze its
performance using accuracy, confusion matrix, and classification report.
THEORY
Logistic Regression is a classification algorithm that models the probability of a binary outcome
using the sigmoid function: sigma(z) = 1 / (1 + e^(-z)). Output is a probability between 0 and 1. If
probability >= 0.5, predict Class 1, else Class 0. Loss is minimized using Binary Cross-Entropy. It
finds a linear decision boundary separating the two classes.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, confusion_matrix, classification_report
# Evaluate
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Confusion Matrix:')
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
OUTPUT / GRAPH
Page 65 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
The Logistic Regression model was trained and evaluated successfully. The decision boundary
clearly separates the two classes. The confusion matrix shows True Positives, True Negatives,
False Positives, and False Negatives. The accuracy score and classification report confirm the
model's effectiveness.
Page 66 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 3
Design and Evaluate a Data Model using K-Nearest Neighbours (KNN)
AIM
To implement K-Nearest Neighbours (KNN) classifier, find the optimal value of K using accuracy
analysis, and evaluate the model on a binary classification dataset.
THEORY
KNN is a non-parametric, instance-based (lazy) learning algorithm. For a query point, it finds the K
nearest training examples using Euclidean distance: d = sqrt(sum((xi-yi)^2)). For classification, it
takes the majority vote of K neighbours. Small K = overfitting; Large K = underfitting. Features must
be normalized before applying KNN.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import accuracy_score
best_k = k_range[[Link](accuracies)]
print(f'Best K = {best_k}, Accuracy = {max(accuracies):.3f}')
# Plot accuracy vs K
[Link](list(k_range), accuracies, 'o-')
[Link](best_k, color='red', linestyle='--', label=f'Best K={best_k}')
[Link]('K'); [Link]('Accuracy')
[Link]('KNN: Accuracy vs K'); [Link](); [Link]()
OUTPUT / GRAPH
Page 67 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
The KNN algorithm was implemented successfully. By testing K from 1 to 20, the optimal K was
identified from the accuracy vs K graph. The decision boundary plot shows the classification
regions. KNN is simple but computationally expensive at prediction time as it compares against all
training samples.
Page 68 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 4
Design and Evaluate a Data Model using K-Means Clustering
AIM
To apply K-Means Clustering on a dataset, determine the optimal number of clusters using the
Elbow Method, and visualize the clusters and centroids.
THEORY
K-Means is an unsupervised clustering algorithm that partitions data into K clusters. Algorithm: (1)
Initialize K centroids randomly. (2) Assign each point to the nearest centroid. (3) Recompute
centroids as mean of cluster points. (4) Repeat until convergence. The Elbow Method plots WCSS
(Within-Cluster Sum of Squares) vs K - the elbow point is the optimal K.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_blobs
from [Link] import KMeans
# Visualize clusters
for c in range(4):
[Link](X[labels==c,0], X[labels==c,1], label=f'Cluster {c+1}')
[Link](centroids[:,0], centroids[:,1], c='black', marker='X', s=200,
label='Centroids')
[Link]('K-Means Clustering'); [Link](); [Link]()
OUTPUT / GRAPH
Page 69 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
K-Means Clustering was applied successfully. The Elbow Method identified K=4 as the optimal
number of clusters. The algorithm converged and assigned all data points to 4 distinct clusters with
centroids marked by X. K-Means is effective for spherical, well-separated clusters but sensitive to
initialization and outliers.
Page 70 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 5
Design and Evaluate a Data Model using Support Vector Machine (SVM)
AIM
To implement a Support Vector Machine (SVM) classifier with RBF kernel, analyze the effect of
regularization parameter C on accuracy, and evaluate model performance.
THEORY
SVM finds the optimal hyperplane that maximizes the margin between classes. Support vectors are
the closest data points to the hyperplane. The RBF (Radial Basis Function) kernel maps data to a
higher-dimensional space for non-linear separation: K(x,z) = exp(-gamma * ||x-z||^2). The C
parameter controls the trade-off between margin width and misclassification. Always standardize
features before SVM.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import SVC
from [Link] import accuracy_score, classification_report
OUTPUT / GRAPH
Page 71 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
The SVM model with RBF kernel was trained on the standardized dataset. The accuracy vs C plot
shows that C=1 provides a good balance between margin and classification. SVM finds the optimal
hyperplane that maximizes the margin between classes. Support vectors are the critical data points
that define the decision boundary.
Page 72 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 6
Design and Evaluate a Data Model using Principal Component Analysis (PCA)
AIM
To apply Principal Component Analysis (PCA) for dimensionality reduction on the Iris dataset,
visualize explained variance, and project the 4-dimensional data to 2D for visualization.
THEORY
PCA is an unsupervised linear dimensionality reduction technique. Steps: (1) Standardize data. (2)
Compute covariance matrix C = (1/n) X^T X. (3) Compute eigenvalues and eigenvectors of C. (4)
Sort by eigenvalue (descending). (5) Select top k eigenvectors. (6) Project data: Z = X * W. The
explained variance ratio shows how much information each component captures. PCA is used for
visualization, noise reduction, and feature extraction.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import load_iris
from [Link] import StandardScaler
from [Link] import PCA
# Plot 2D projection
colors = ['steelblue', 'crimson', 'forestgreen']
for i, name in enumerate(iris.target_names):
[Link](X_2d[y==i,0], X_2d[y==i,1], c=colors[i], label=name)
[Link]('PC1'); [Link]('PC2')
[Link]('PCA: 2D Projection of Iris')
[Link](); [Link]()
OUTPUT / GRAPH
Page 73 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
PCA was applied on the 4-feature Iris dataset. The scree plot shows that the first 2 principal
components explain over 95% of the total variance. The 2D scatter plot shows clear separation of
the three iris species. PCA successfully reduced dimensionality from 4 to 2 while preserving most
information.
Page 74 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 7
Design and Evaluate a Data Model using Decision Tree
AIM
To build a Decision Tree Classifier, find the optimal tree depth to prevent overfitting, visualize the
decision boundary, and evaluate the model performance.
THEORY
A Decision Tree splits data recursively based on feature conditions forming a tree structure.
Splitting criteria: Gini Impurity = 1 - sum(pi^2) or Information Gain = Entropy(parent) - weighted
Entropy(children). Deeper trees overfit; use max_depth to control complexity. Features with lower
Gini or higher Information Gain are chosen first. No feature scaling required.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier, plot_tree
from [Link] import accuracy_score, classification_report
best_depth = list(depths)[[Link](test_acc)]
print(f'Best Depth: {best_depth}')
OUTPUT / GRAPH
Page 75 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
The Decision Tree Classifier was trained and the optimal depth was determined by comparing train
and test accuracy. The accuracy vs depth graph clearly shows overfitting for large depths. The best
depth provides a good balance. The decision boundary shows the piecewise rectangular regions
created by tree splits.
Page 76 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 8
Design and Evaluate a Data Model using Random Forest
AIM
To implement a Random Forest Classifier using ensemble learning, analyze how the number of
trees affects accuracy, compute feature importance scores, and evaluate overall model
performance.
THEORY
Random Forest is an ensemble of Decision Trees using Bagging (Bootstrap Aggregation). For each
tree: (1) A random bootstrap sample of training data is drawn. (2) At each node, only a random
subset of features (sqrt(p)) is considered for splitting. (3) Trees vote for the final class (majority
voting). This reduces variance and overfitting compared to a single decision tree. Feature
importance is computed from total Gini reduction across all trees.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score, classification_report
OUTPUT / GRAPH
Page 77 of 80
Python Programming Lab — Practical File | 2024–25
RESULT
The Random Forest Classifier was trained successfully. The accuracy vs number of trees plot
shows that accuracy stabilizes beyond 50-100 trees. Feature importance bar chart identifies which
features contribute most to predictions. Random Forest outperforms a single Decision Tree due to
variance reduction through ensemble averaging.
Page 78 of 80
Python Programming Lab — Practical File | 2024–25
PRACTICAL 9
Compare Performance of All ML Techniques using Matplotlib
AIM
To compare the performance of all implemented machine learning algorithms (Linear Regression,
Logistic Regression, KNN, SVM, Decision Tree, and Random Forest) on the same dataset and
visualize the results using Matplotlib bar and line charts.
THEORY
Model comparison is essential in machine learning to select the best algorithm for a given problem.
All models are trained and tested on the same train-test split to ensure fair comparison. Accuracy
score is computed for each classifier. Visualization through bar charts and line charts helps identify
the best performing algorithm at a glance. Different algorithms have different biases, variances, and
computational costs.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.linear_model import LinearRegression, LogisticRegression
from [Link] import KNeighborsClassifier
from [Link] import SVC
from [Link] import DecisionTreeClassifier
from [Link] import RandomForestClassifier
from [Link] import accuracy_score
lr = LinearRegression().fit(X_train, y_train)
results['Linear Reg'] = accuracy_score(y_test, ([Link](X_test) > 0.5).astype(int))
# Print results
print('\n===== ML Algorithms Comparison =====')
Page 79 of 80
Python Programming Lab — Practical File | 2024–25
for name, acc in sorted([Link](), key=lambda x: -x[1]):
print(f'{name:20s}: {acc:.4f}')
OUTPUT / GRAPH
RESULT
All six ML algorithms were compared on the same classification dataset. The bar chart and line
chart clearly show the accuracy of each algorithm. Ensemble methods (Random Forest) generally
achieve higher accuracy due to combining multiple weak learners. SVM with RBF kernel also
performs well on non-linearly separable data. Logistic Regression provides a strong baseline for
binary classification. The comparison helps in selecting the most appropriate algorithm based on
accuracy, interpretability, and computational requirements.
Page 80 of 80