ML With Python Lab Manual CA119
ML With Python Lab Manual CA119
LAB MANUAL
Session: 2025-2026
Branch: BCA
Year: 1st
Semester: 2nd
1
REVISION HISTORY
2
Vision
To lead the teeming millions of the world through the wilderness of
ignorance and illiteracy, as "Kindly Light" (Exodus 13:21) with the
resounding divine proclamation. "Read: Thy Lord is the most bounteous
(Quran 30:96:3)." and to educate them in the most constructive and
innovative ways.
Mission
To make every student a role model of intellectuals and torch bearer for
others all over the world through his / her inspiring existence.
3
Programme Educational Objectives (PEO)
To enhance foundation of mathematics, computer application and problem
solving methodology for effective implementation in the area of s/w
development.
To effectively design, implement, improve, and manage the integrated socio-
technical systems.
To inculcate effective communication skills combined with professional &
ethical attitude.
To gain multidisciplinary knowledge through real time projects and industry
internship training and providing a sustainable competitive edge in R&D and
meeting industry needs.
4
Course Objectives: (CA119
567 Python Lab)
Course outcome
After undergoing this laboratory module, the participant should be able to:
1. Understand the basic concept of Machine learning and can write programs on the
python libraries.
2. Student will able to write basic programming structure of Python using elements of
Python.
3. Ability to write and implement programs on Control, Looping Statements and can use
data structure of Python.
4. Ability to write programs with the help of functions and also used modules and file
handling.
5. Ability to implement the OOPs concept and also configure the Exceptional handling
implementation.
5
Guidelines for the Students
2. While conducting the experiments students should see that their programs would
II. Programs should perform input validation (Data type, range error, etc.) and
give appropriate error messages and suggest corrective actions.
III. Comments should be used to give the statement of the problem and every
function should indicate the purpose of the function, inputs and outputs
3. Once the experiment(s) get executed, they should show the program and results to
the instructors and copy the same in their Lab Report.
4. Students should be regular and come prepared for the lab practice.
6. Students should bring the lab Report, class notes can be kept ready for reference
if required.
6
Week Title of Name of the Experiments Page No.
No Experiments
Week-1
Write a program to create the matrix with the help of numpy and then
Basic Machine convert into dataframe using pandas. 8
1 Learning Write a python program to import and export data using Pandas library
functions.
Week-2
Write a program to display the welcome message on the screen with the
Basic Python - help of user input. 11
3 I Write a program to calculate the area of circle based on the radius entered
by the user.
Write a program, using user-defined function to find the area of rectangle,
square, circle and triangle by accepting suitable input parameters from user.
Week-4
Write a program to input the age by user, check and print, if the user is
5 Control And eligible for voting or not. 15
Looping Write a program to enter the year by user and check whether the given year
Statements is leap year or not using nested if statement.
Write a program to count the number of even and odd numbers from N
numbers.
Write a program to determine if a given number is Armstrong or not.
Week-6
Write a program that accepts a string and convert the upper case letters into
6 Data Structure lower case and lower case letters into upper case. 18
Write a program to print the maximum element in a list
Write a program to find the sum of all items in a dictionary.
Week-7
Write a program to create the class, object and accessing class variables
9 OOPs 26
and class methods using constructor.
Write a program to implement inheritance in Python.
Write a program to perform the operator overloading in Python.
Week-10
Write a program to perform the ZeroDivisionError using try….except
10 Exception
statement.
Handling
Write a program to calculate the sum of numbers in the list using try except
statement such that if the list is empty, it will be handled by except
statement.
8
Week-1
Objective:
To study the features and working of NumPy and Pandas libraries used in Machine Learning.
NumPy
NumPy (Numerical Python) is a fundamental library in Python used for numerical and scientific
computing. It provides support for large, multi-dimensional arrays and matrices, along with a
collection of mathematical functions to operate on these arrays.
The main object in NumPy is the ndarray (N-dimensional array).\
Basic NumPy Operations:
- Creating arrays
- Array indexing and slicing
- Mathematical operations
- Statistical functions (mean, median, sum, etc.)
- Matrix operations
Pandas
Pandas is a powerful Python library used for data manipulation and data analysis. It
provides easy-to-use data structures and data analysis tools.
The two main data structures in Pandas are:
1) Series – One-dimensional labeled array.
2) DataFrame – Two-dimensional labeled data structure (like a table).
Features of Pandas:
1) Handling missing data.
2) Data filtering and selection.
3) Grouping and aggregation.
4) Importing and exporting data (CSV, Excel, etc.).
5) Data alignment and merging.
Experiment No.-1
1. To create a matrix using NumPy and convert it into a DataFrame using
Pandas.
import numpy as np
import pandas as pd
print("NumPy Matrix:")
9
print(matrix)
print("\nPandas DataFrame:")
print(df)
Output:
NumPy Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Pandas DataFrame:
Column1 Column2 Column3
0 1 2 3
1 4 5 6
2 7 8 9
2 To write a Python program to import and export data using Pandas library functions.
import pandas as pd
# Step 1: Create sample data
data = {
"Name": ["Rahul", "Aisha", "John"],
"Age": [22, 23, 21],
"Marks": [85, 90, 88]
}
print("Original DataFrame:")
print(df)
10
new_df = pd.read_csv("student_data.csv")
print("\nImported DataFrame:")
print(new_df)
Output:
Original DataFrame:
Name Age Marks
0 Rahul 22 85
1 Aisha 23 90
2 John 21 88
Imported DataFrame:
Name Age Marks
0 Rahul 22 85
1 Aisha 23 90
2 John 21 88
11
Week-2
Data Visualization
Data visualization is the graphical representation of data using charts, plots, and graphs. It helps in:
- Understanding patterns and trends
- Identifying relationships
- Comparing data
- Detecting outliers
- Supporting decision making
1 ) Matplotlib
Matplotlib is a basic and widely used plotting library in Python. It is used to create:
Line plots
Bar charts
Histograms
Pie charts
Scatter plots
2. Seaborn
Seaborn is built on top of Matplotlib. It provides:
- Attractive and advanced statistical graphics
- Better themes and styles
- Heatmaps
- Box plots
# Sample Data
x = [Link]([1, 2, 3, 4, 5])
y = [Link]([10, 20, 15, 25, 30])
# 1. Line Plot
[Link]()
[Link](x, y)
[Link]("Line Plot")
[Link]("X Values")
[Link]("Y Values")
12
[Link]()
# 2. Bar Chart
[Link]()
[Link](x, y)
[Link]("Bar Chart")
[Link]("X Values")
[Link]("Y Values")
[Link]()
# 3. Scatter Plot
[Link]()
[Link](x, y)
[Link]("Scatter Plot")
[Link]("X Values")
[Link]("Y Values")
[Link]()
# 4. Histogram
data = [Link](100)
[Link]()
[Link](data)
[Link]("Histogram")
[Link]()
13
14
15
Week-3
Objective: -
To understand user input in Python.
To understand arithmetic operations.
To understand and implement user-defined functions.
Syntax:
variable = input("Message to display")
Example:
age = int(input("Enter your age: "))
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
Example:
area = 3.14 * r * r
3) Functions in Python
A function is a block of reusable code that performs a specific task.
Functions improve modularity and code reusability.
Types of Functions:
1. Built-in Functions (print(), input(), len())
2. User-defined Functions
16
Syntax of User-defined Function:
def function_name(parameters):
statements
return value
Area of Circle = π × r²
Area of Rectangle = length × breadth
Area of Square = side × side
Area of Triangle = ½ × base × height
Experiment
1) To display a welcome message using user input.
Source code:
name = input("Enter your name: ")
print("Welcome to Python Programming,", name)
Output:
Enter your name: Ravi
Welcome to Python Programming, Ravi
18
Week-4
Objective: -
- if Statement
Executes a block of code only if the condition is true.
if condition:
statements
- if-else Statement
Executes one block if the condition is true and another block if it is false.
if condition:
statements
else:
statements
- if-elif-else Statement
Used when multiple conditions need to be checked.
if condition1:
statements
elif condition2:
statements
else:
statements
Python supports:
1) for Loop
Used when the number of iterations is known.
19
2) while Loop
Executes as long as a condition remains true.
while condition:
statements
Importance of Loops:
Celsius to Fahrenheit:
F=(C×9/5)+32
Fahrenheit to Celsius:
C=(F−32)×5/9
These formulas convert temperature values between two different measurement scales.
4) Perfect Square
A number is said to be a perfect square if it can be expressed as:
n=k2
Where k is an integer.
int(i ** 0.5) ** 2 == i
5. Perfect Cube
A number is said to be a perfect cube if it can be expressed as:
n=k3
Where k is an integer.
int(round(i ** (1/3))) ** 3 == i
20
Experiments
1) To convert temperature from Fahrenheit to Celsius and vice versa based on user’s choice.
Source Code:
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
choice = int(input("Enter your choice (1/2): "))
if choice == 1:
c = float(input("Enter temperature in Celsius: "))
f = (c * 9/5) + 32
print("Temperature in Fahrenheit:", f)
elif choice == 2:
f = float(input("Enter temperature in Fahrenheit: "))
c = (f - 32) * 5/9
print("Temperature in Celsius:", c)
else:
print("Invalid Choice")
Output:
Celsius to Fahrenheit
Fahrenheit to Celsius
Enter your choice (1/2): 1
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77.0
2) To print perfect square and perfect cube numbers within a given range.
Source Code:
start = int(input("Enter starting number: "))
end = int(input("Enter ending number: "))
print("Perfect Squares in range:")
for i in range(start, end + 1):
if int(i ** 0.5) ** 2 == i:
print(i)
print("Perfect Cubes in range:")
for i in range(start, end + 1):
if int(round(i ** (1/3))) ** 3 == i:
print(i)
Output:
Enter starting number: 1
Enter ending number: 30
Perfect Squares in range:
1
4
9
16
25
Perfect Cubes in range:
1
8
27
21
Week-5
Objective: -
1. To understand control statements in Python.
2. To check voting eligibility using conditional statements.
3. To determine whether a year is leap year.
4. To count even and odd numbers from N numbers.
5. To determine whether a number is Armstrong or not.
Age≥18
The program checks whether the entered age satisfies this condition using an if-else
statement.
It is divisible by 4
But not divisible by 100
Except if it is divisible by 400
Mathematical condition:
Loops are used to count even and odd numbers from N numbers.
4) Armstrong Number
An Armstrong number is a number that is equal to the sum of its digits raised to the
power of number of digits.
Example:
153=13+53+33=153
22
Experiments
1) To check whether the user is eligible for voting.
Source code:
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Output:
Enter your age: 20
You are eligible to vote.
24
Week-6
Objective: -
- To understand string manipulation in Python.
- To perform operations on lists.
- To perform operations on dictionaries.
2. String
A string is a sequence of characters enclosed in single (' ') or double (" ") quotes.
Example:
name = "Python"
Properties of String:
Strings are immutable (cannot be changed after creation).
Strings support indexing and slicing.
Many built-in functions are available like:
o upper()
o lower()
o swapcase()
o len()
In this experiment, we convert uppercase letters into lowercase and lowercase
into uppercase using swapcase().
3. List
A list is an ordered collection of elements enclosed in square brackets [ ].
Example:
numbers = [10, 20, 30, 40]
Properties of List:
Lists are mutable.
Elements can be of different data types.
Supports indexing and slicing.
Built-in functions: max(), min(), append(), etc.
Example:
Properties of Dictionary:
Enclosed in curly braces { }.
Keys must be unique.
Values can be of any type.
Accessed using keys.
In this experiment, we calculate the sum of all values in a dictionary.
Experiments:
3) Write a program to to find the sum of all items in a dictionary using loop
logic.
Source code:
26
n = int(input("Enter number of items in dictionary: "))
data = {}
for i in range(n):
key = input("Enter key: ")
value = int(input("Enter value: "))
data[key] = value
total = 0
for value in [Link]():
total += value
print("Dictionary:", data)
print("Sum of all values:", total)
Output:
Enter number of items in dictionary: 3
Enter key: a
Enter value: 10
Enter key: b
Enter value: 20
Enter key: c
Enter value: 30
Dictionary: {'a': 10, 'b': 20, 'c': 30}
Sum of all values: 60
27
Week-7
Objective: -
- To understand user-defined functions in Python.
- To calculate factorial of a number using a function.
- To generate prime numbers using the Sieve of Eratosthenes algorithm.
1) Factorial of a Number
The factorial of a non-negative integer n is the product of all positive integers less than or equal
to n.
𝒏! = 𝒏 × (𝒏 − 𝟏) × (𝒏 − 𝟐) ×. . .× 𝟏
Example:
𝟓! = 𝟓 × 𝟒 × 𝟑 × 𝟐 × 𝟏 = 𝟏𝟐𝟎
Special Case:
𝟎! = 𝟏
Example:
2, 3, 5, 7, 11, 13 …
28
Advantage:
Faster than checking each number individually.
Time complexity ≈ O(n log log n)
Experiment :
1) Write a program to calculate factorial of a given number using function.
Source code:
def factorial(n):
if n == 0 or n == 1:
return 1
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
num = int(input("Enter a number: "))
result = factorial(num)
print("Factorial of", num, "is:", result)
Output:
Enter a number: 5
Factorial of 5 is: 120
30
Week-8
Objective: -
- To create and use a user-defined module.
- To understand and implement file handling using tell() and seek() Methods.
- To count alphabets, digits, and spaces in a file.
1) Module in Python
A module is a file containing Python definitions, functions, classes, and variables
that can be reused in another Python program.:
A module is a separate Python file (.py) used to organize and reuse code.
Types of Modules
1. Built-in Modules
o Already available in Python
o Example: math, random, os
2. User-defined Modules
o Created by the user
o Saved as .py file
o Imported into another program
import calculator
Types of Files
1. Text Files (.txt)
o Store data in readable format
o Example: [Link]
2. Binary Files (.bin)
o Store data in binary format
o Not human-readable
31
Opening a File
Syntax:
file = open("filename", "mode")
File Modes
Mode Description
'r' Read mode
Write mode
'w'
(overwrites file)
'a' Append mode
'r+' Read and Write mode
3) tell() Method
The tell() method returns the current position of the file pointer.
The file pointer indicates where reading or writing is currently happening in the file.
Example:
[Link]()
If the file pointer is at position 10, it means 10 characters have been read.
4) seek() Method
The seek() method is used to move the file pointer to a specific position.
Syntax:
[Link](offset)
Where:
offset → number of bytes from beginning
Example:
[Link](0)
32
Experiment
1) Write a program to create a user-defined module named Calculator and perform arithmetic
operations.
Source Code
Step 1: Create a file named [Link]
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Division by zero not allowed"
Step 2: Main Program File
import calculator
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
print("Addition:", [Link](x, y))
print("Subtraction:", [Link](x, y))
print("Multiplication:", [Link](x, y))
print("Division:", [Link](x, y))
Output:
Enter first number: 10
Enter second number: 5
Addition: 15.0
Subtraction: 5.0
Multiplication: 50.0
Division: 2.0
34
Week-9
Objective: -
- To understand class and object creation in Python.
- To access class variables and methods using constructor.
- To implement inheritance in Python.
- To perform operator overloading in Python.
Instead of writing everything in one place, we divide the program into small units
called objects.
2) Class
A class is a blueprint or template used to create objects.
Example in real life:
Class → Car
Objects → BMW, Audi, Tesla
A class contains:
Variables (Data)
Methods (Functions)
Syntax of Class:
class ClassName:
variables
methods
3) Object
An object is an instance of a class.
It represents real-world entities.
Example:
obj = ClassName()
Here:
obj → object
ClassName() → calling class
35
4) Constructor
A constructor is a special function that runs automatically when an object is created.
In Python, constructor is written as:
def __init__(self):
Important Points:
5) Inheritance
Inheritance means one class can use properties and methods of another class.
It reduces code repetition.
Example:
Syntax:
class Child(Parent):
6) Operator Overloading
Example:
Operator Method
+ add()
- sub()
* mul()
== eq()
36
Experiment
1) Create a class, object and access variables and methods using constructor.
Source code:
class Student:
def init(self, name, marks):
[Link] = name
[Link] = marks
def display(self):
print("Name:", [Link])
print("Marks:", [Link])
s1 = Student("Rahul", 85)
[Link]()
Output:
Name: Rahul
Marks: 85
Source code:
class Animal:
def speak(self):
print("Animal makes sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
[Link]()
[Link]()
Output:
Animal makes sound
Dog barks
Source code:
class Number:
def init(self, value):
[Link] = value
Output:
Addition is: 30
38
Week-10
Objective: -
- To understand exception handling in Python.
- To handle ZeroDivisionError using try-except.
- To handle empty list error using try-except.
1) Exception
An exception is an error that occurs during the execution of a program (runtime error).
- It stops execution
- Displays error message
- Terminates the program
Example:
10 / 0
This produces:
ZeroDivisionError
1. Syntax Errors
Occur due to wrong grammar in code.
Detected before execution.
Example:
print("Hello"
2. Logical Errors
Program runs but gives wrong output.
Hard to detect.
Example:
39
2) Exception Handling
Exception handling is a technique used to handle runtime errors so that:
Basic Structure
try:
# Code that may cause error
except:
# Code to handle error
Python provides:
try
except
else
finally
3) try Block
The code which may cause error is written inside try.
Syntax:
try:
risky code
4) except Block
If error occurs, control goes to except block.
Syntax:
except ErrorName:
handling code
40
Experiment
2) Write a program to calculate sum of list elements and handle empty list using try-except.
Source code:
try:
n = int(input("Enter number of elements: "))
numbers = []
for i in range(n):
num = int(input("Enter number: "))
[Link](num)
if len(numbers) == 0:
raise ValueError("List is empty. Cannot calculate sum.")
total = 0
for num in numbers:
total += num
print("Sum of list elements is:", total)
except ValueError as e:
print("Error:", e)
finally:
print("Program ended.")
Output:
Enter number of elements: 0
Error: List is empty. Cannot calculate sum.
Program ended.
41