0% found this document useful (0 votes)
5 views41 pages

ML With Python Lab Manual CA119

The document is a lab manual for the Fundamentals of Machine Learning with Python course at Integral University, detailing the course objectives, outcomes, and guidelines for students. It includes a revision history, vision and mission statements, program educational objectives, and a structured outline of weekly experiments focusing on Python programming, data visualization, and machine learning concepts. The manual emphasizes hands-on practice with Python libraries such as NumPy and Pandas, and includes specific programming tasks for students to complete.

Uploaded by

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

ML With Python Lab Manual CA119

The document is a lab manual for the Fundamentals of Machine Learning with Python course at Integral University, detailing the course objectives, outcomes, and guidelines for students. It includes a revision history, vision and mission statements, program educational objectives, and a structured outline of weekly experiments focusing on Python programming, data visualization, and machine learning concepts. The manual emphasizes hands-on practice with Python libraries such as NumPy and Pandas, and includes specific programming tasks for students to complete.

Uploaded by

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

INTEGRAL UNIVERSITY LUCKNOW

Dasauli, Bas-ha Kursi Road, Lucknow – 226026

Department of Computer Application

LAB MANUAL

Session: 2025-2026

Subject Name : Fundamentals of Machine Learning with Python Lab

Lab Subject Code: CA119

Branch: BCA

Year: 1st

Semester: 2nd

1
REVISION HISTORY

REVISION AUTHOR(S) REVIEWER(S) DATE OF OWNER SUMMARY OF


RELEASE CHANGES
Revision -1 Syed Bassam Ali Internal 16/01/2026 HOD - Initial Release
Reviewers CA
Revision -2 Mohd Saquib Departmental 16/01/2026 HOD - Major revisions made.
Usmani QAC CA Incorporated review
comments from
departmental QAC
into Revision-2

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.

 To integrate the ebullience, intellect and dynamism of youth with


decency, decorum, discipline and dedication through value-based quality
education.

Mission
 To make every student a role model of intellectuals and torch bearer for
others all over the world through his / her inspiring existence.

 To inculcate a spirit of confidence, self-respect and firm commitment in


students along with farsighted wisdom and understanding.

 To make India a self-reliant and dominant G-1 country recognized for


quality education, higher economic growth and valuable moral practices.

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.

Programme Outcomes (PO)


 Computational knowledge: Acquire knowledge of Computing Fundamentals,
Basic Mathematics, Computing Specialization and Domain Knowledge of
proper computing models from defined problems.
 Problem analysis: Identify, formulate review research literate and analyze
complex engineering problems reading substantiated conclusions using first
principles mathematics, computing science and relevant domains.
 Design/development of solutions: Ability to design system s/w or process as
per needs and specifications.
 Conduct investigations of complex computing problems: Use research-based
knowledge and research methods including design of experiments, analysis &
interpretation of data & synthesis of information to provide valid conclusions.
 Modern Tool Usage: Ability to demonstrate skills to use modern s/w & h/w
tools to analyze problems.
 Professional Ethics: Apply ethical principles and commit to professional ethics
and cyber regulations.
 Life-Long Learning: Ability to develop confidence for self-education and life-
long learning in the broadest context of technological change.
 Project management and finance: Ability to demonstrate knowledge &
understanding of the engineering and management principles and apply them as
a member & as a leader in a team to manage multidisciplinary projects.
 Communication Efficacy: Ability to communicate effectively in both verbal
and written form.
 Societal and Environmental Concern: Ability to understand the impact of IT
solutions in a global and societal context.
 Innovations and entrepreneurship: Find out right opportunity for
entrepreneurship and create odd value for the betterment of an individual and
society at large.

4
Course Objectives: (CA119
567 Python Lab)

1. Primarily know the basic structure of python programming language.


2. Learn the concept of Conditional and Looping Statements, Data Structures, Functions, etc.
3. Understand the concept of Object oriented programming language.
4. Perform the operations on File handling and Exceptional handling.
5. Learn the basic concept of Machine learning and also, python libraries used for
implementation of Machine learning.

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

1. The students should implement the given Program individually.

2. While conducting the experiments students should see that their programs would

Meet the following criteria:

I. Programs should be interactive with appropriate prompt messages, error


messages if any, and descriptive messages for outputs.

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

IV. Statements within the program should be properly indented.

V. Use meaningful names for variables and functions.

VI. Make use of Constants and type definitions wherever needed.

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.

5. In case a student misses a class, it is his/her responsibility to complete that missed


experiment(s).

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

Basic Machine Write a program to demonstrate various Data Visualization Techniques.


Learning
2 10
Week-3

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 convert the given temperature from Fahrenheit to


Basic Python - Celsius and vice versa depending upon user’s choice. 13
4 II Write a program to print those numbers who are perfect square and
perfect cube between a given range.
Week-5

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 function to calculate the factorial of a given number.


7 Function 21
Write a function to generate a list of prime numbers up to a given number
using the Sieve of Eratosthenes algorithm.
Week-8

Write a program to build a user defined module named Calculator and


8 Module & File add all operations associated with the Calculator, and use the Calculator 24
Handling modules as library and perform the operations.
Write a program to implement the use of tell() and seek() method.
Write a program to count the alphabets, numbers and spaces of the string
in a given file.
7
Week-9

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

# Step 1: Create a matrix using NumPy


matrix = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

print("NumPy Matrix:")
9
print(matrix)

# Step 2: Convert NumPy array to Pandas DataFrame


df = [Link](matrix, columns=["Column1", "Column2", "Column3"])

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]
}

# Step 2: Convert to DataFrame


df = [Link](data)

print("Original DataFrame:")
print(df)

# Step 3: Export to CSV


df.to_csv("student_data.csv", index=False)

print("\nData exported to student_data.csv successfully.")

# Step 4: Import from CSV

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

Data exported to student_data.csv successfully.

Imported DataFrame:
Name Age Marks
0 Rahul 22 85
1 Aisha 23 90
2 John 21 88

11
Week-2

OBJECTIVE: To study and implement various data visualization techniques using


Python libraries.

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

In Machine Learning, visualization helps in data analysis and preprocessing.

Common Python Libraries for Data Visualization

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

1) Write a program to demonstrate various Data Visualization Techniques.

import [Link] as plt


import seaborn as sns
import numpy as np

# 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]()

# 5. Heatmap using Seaborn


data_matrix = [Link](5,5)
[Link](data_matrix, annot=True)
[Link]("Heatmap")
[Link]()

13
14
15
Week-3

Objective: -
 To understand user input in Python.
 To understand arithmetic operations.
 To understand and implement user-defined functions.

1) User Input in Python


In Python, input from the user is taken using the input() function.
The input() function reads data entered by the user as a string.

Syntax:
variable = input("Message to display")

If numerical input is required, type conversion is necessary using:

int() – for integer values


float() – for decimal values

Example:
age = int(input("Enter your age: "))

2) Arithmetic Operators in Python


Python provides arithmetic operators to perform mathematical calculations:

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

 def keyword is used to define a function.


 Parameters are inputs to the function.
 return statement sends result back.

3. Mathematical Formulae Used

 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

2) To calculate the area of a circle based on user input.


Source code:
radius = float(input("Enter radius of circle: "))
pi = 3.14
area = pi * radius * radius
print("Area of Circle is:", area)
Output:
Enter radius of circle: 5
Area of Circle is: 78.5

3) To calculate area of rectangle, square, circle and triangle using user-defined


functions.
Source code:
17
def rectangle_area(length, breadth):
return length * breadth
def square_area(side):
return side * side
def circle_area(radius):
pi = 3.14
return pi * radius * radius
def triangle_area(base, height):
return 0.5 * base * height
l = float(input("Enter length of rectangle: "))
b = float(input("Enter breadth of rectangle: "))
s = float(input("Enter side of square: "))
r = float(input("Enter radius of circle: "))
base = float(input("Enter base of triangle: "))
h = float(input("Enter height of triangle: "))
print("Area of Rectangle:", rectangle_area(l, b))
print("Area of Square:", square_area(s))
print("Area of Circle:", circle_area(r))
print("Area of Triangle:", triangle_area(base, h))
Output:
Enter length of rectangle: 10
Enter breadth of rectangle: 5
Enter side of square: 4
Enter radius of circle: 3
Enter base of triangle: 6
Enter height of triangle: 4
Area of Rectangle: 50.0
Area of Square: 16.0
Area of Circle: 28.259999999999998
Area of Triangle: 12.0

18
Week-4

Objective: -

 To understand and implement conditional statements.


 To convert temperature between Fahrenheit and Celsius.
 To print perfect square and perfect cube numbers within a given range.

1) Decision Making in Python (Conditional Statements)


Decision-making statements allow the program to execute certain blocks of code based on
conditions.

Python provides the following conditional statements:

- 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

2) Iterative Statements (Loops)


Loops are used to execute a block of code repeatedly.

Python supports:

1) for Loop
Used when the number of iterations is known.

for variable in range(start, stop):


statements

19
2) while Loop
Executes as long as a condition remains true.

while condition:
statements

Importance of Loops:

- Avoid repetition of code.


- Used for range-based operations.
- Essential for pattern generation and number checking.

In this experiment, a for loop is used to iterate through numbers in a given


range.

3) Mathematical Concept of Temperature Conversion


Temperature conversion is based on linear transformation formulas:

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.

In Python, we check perfect square using:

int(i ** 0.5) ** 2 == i

If true, the number is a perfect square.

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.

In Python, we check perfect cube using:

int(round(i ** (1/3))) ** 3 == i

If true, the number is a perfect cube.

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.

1) Voting Eligibility Logic


In India, a person is eligible to vote if:

Age≥18

The program checks whether the entered age satisfies this condition using an if-else
statement.

2) Leap Year Logic


A year is a leap year if:

 It is divisible by 4
 But not divisible by 100
 Except if it is divisible by 400

Mathematical condition:

3) Even and Odd Numbers


A number is:
Even → if divisible by 2
number%2==0

Odd → if not divisible by 2

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.

2) To check whether a given year is leap year.


Source code:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
Output:
Enter a year: 2024
Leap Year

3) To count even and odd numbers from N numbers.


Source code:
n = int(input("Enter how many numbers: "))
even = 0
odd = 0
for i in range(n):
num = int(input("Enter number: "))
if num % 2 == 0:
even += 1
else:
odd += 1
print("Even numbers:", even)
print("Odd numbers:", odd)
Output:
Enter how many numbers: 5
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
Even numbers: 2
23
Odd numbers: 3

4) To check whether a number is Armstrong or not.


Source code:
num = int(input("Enter a number: "))
temp = num
digits = len(str(num))
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** digits
temp //= 10
if sum == num :
print("Armstrong Number")
else:
print("Not an Armstrong Number")
Output:
Enter a number: 153
Armstrong Number

24
Week-6

Objective: -
- To understand string manipulation in Python.
- To perform operations on lists.
- To perform operations on dictionaries.

1. Data Structures in Python


Data structures are used to store and organize data efficiently so that it can be
accessed and modified easily.

Python provides built-in data structures such as:


 String
 List
 Tuple
 Set
 Dictionary
In this experiment, we use String, List, and Dictionary.

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.

In this experiment, we find the maximum element in a list.


25
4. Dictionary
A dictionary stores data in key-value pairs.

Example:

student = {"name": "Ali", "marks": 90}

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:

1) Write a program to accept a string and convert uppercase letters into


lowercase and lowercase letters into uppercase.
Source code:
text = input("Enter a string: ")
converted_text = [Link]()
print("Converted string:", converted_text)
Output:
Enter a string: Hello World
Converted string: hELLO wORLD

2) Write a program to print the maximum element in a list.


Source code:
n = int(input("Enter number of elements: "))
numbers = []
for i in range(n):
num = int(input("Enter element: "))
[Link](num)
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
print("Maximum element in the list is:", maximum)
Output:
Enter number of elements: 5
Enter element: 12
Enter element: 45
Enter element: 7
Enter element: 89
Enter element: 23
Maximum element in the list is: 89

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:

𝟎! = 𝟏

Factorial is widely used in:


Mathematics
Probability
Permutations & Combinations
2) Prime Numbers
A prime number is a number greater than 1 that has only two factors:
 1
 Itself

Example:
2, 3, 5, 7, 11, 13 …

3) Sieve of Eratosthenes Algorithm


It is an efficient algorithm to find all prime numbers up to a given number n.
Steps:
1. Create a list of numbers from 2 to n.
2. Start with first prime number (2).
3. Mark all multiples of 2 as non-prime.
4. Move to next unmarked number.
5. Repeat until √n.
6. Remaining unmarked numbers are prime.

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

2) Write a program to generate prime numbers up to a given number using


Sieve of Eratosthenes.
Source code:
def sieve(n):
prime = [True] * (n + 1)
prime[0] = prime[1] = False
p=2
while p * p <= n:
if prime[p] == True:
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
print("Prime numbers up to", n, "are:")
29
for i in range(2, n + 1):
if prime[i]:
print(i, end=" ")
num = int(input("Enter limit: "))
sieve(num)
Output:
Enter limit: 20
Prime numbers up to 20 are:
2 3 5 7 11 13 17 19

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

Steps to Create and Use User-Defined Module

1. Create a Python file (example: [Link])


2. Define functions inside it
3. Save the file
4. Import it in another file using:

import calculator

2) File Handling in Python


File handling is used to store data permanently in files and retrieve data when needed.
By default, Python stores data in memory (RAM).
When the program stops, memory data is lost.
To store data permanently, we use files.

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

File Handling Process


File handling in Python follows three steps:
1. Open the file
2. Perform operation (Read/Write)
3. Close the file

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)

This moves pointer to the beginning of the file.

5) String Handling in Files


When reading data from a file, it is stored as a string.
To count:
 Alphabets → isalpha()
 Digits → isdigit()
 Spaces → isspace()
These are built-in string methods used for character classification.

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

2) Write a program to implement tell() and seek() methods.


file = open("[Link]", "r")
content = [Link](10)
print("First 10 characters:", content)
position = [Link]()
print("Current file pointer position:", position)
[Link](0)
content = [Link](10)
print("After seek, first 10 characters:", content)
[Link]()
Output:
First 10 characters: Hello12345
Current file pointer position: 10
After seek, first 10 characters: Hello12345

3) Write a program to count alphabets, digits, and spaces in a file.


Source Code:
file = open("[Link]", "r")
33
content = [Link]()
alphabets = 0
digits = 0
spaces = 0
for ch in content:
if [Link]():
alphabets += 1
elif [Link]():
digits += 1
elif [Link]():
spaces += 1
print("Number of Alphabets:", alphabets)
print("Number of Digits:", digits)
print("Number of Spaces:", spaces)
[Link]()
Output:
Number of Alphabets: 11
Number of Digits: 3
Number of Spaces: 2

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.

1) OOP (Object Oriented Programming)


OOP (Object Oriented Programming) is a programming style where we organize
code using:
 Classes
 Objects

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

Syntax of Class: class ClassName:


variables
methods

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:

 __init__ is always called automatically.


 self represents the current object.
 Used to initialize variables.

5) Inheritance
Inheritance means one class can use properties and methods of another class.
It reduces code repetition.

Example:

Parent Class → Person


Child Class → Student

Student can use Person’s properties.

Syntax:

class Child(Parent):

6) Operator Overloading

Normally operators like +, -, * work with numbers.


Operator overloading means:

Giving new meaning to operators for user-defined objects.

Example:

 Using + to add two objects.

Python uses special methods called Magic Methods:

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

2) Write a program to Implement inheritance in Python

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

3) Write a program to perform operator overloading

Source code:
class Number:
def init(self, value):
[Link] = value

def __add__(self, other):

return [Link] + [Link]


37
n1 = Number(10)
n2 = Number(20)
result = n1 + n2
print("Addition is:", result)

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

When Python encounters an error:

- It stops execution
- Displays error message
- Terminates the program

Example:
10 / 0

This produces:
ZeroDivisionError

Because division by zero is not allowed.

Types of Errors in Python

There are mainly three types of errors:

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:

area = length + breadth # Wrong formula

3. Runtime Errors (Exceptions)


 Occur during execution.
 Example: dividing by zero.

39
2) Exception Handling
Exception handling is a technique used to handle runtime errors so that:

 Program does not crash


 Error message is shown properly
 Execution continues normally

Python provides special keywords for exception handling.

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

1) Write a program to perform ZeroDivisionError using try-except statement.


Source code:
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result is:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("Program executed successfully.")
Output:
Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed.
Program executed successfully.

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

You might also like