Friday, November 27, 2026

Desision Tree

Inside Classification: How Machines Learn to Sort the World

Inside Classification: How Machines Learn to Sort the World

Every day, machines sort things for us. Your email filter decides what counts as spam, a bank decides whether a loan is risky, and a hospital system flags scans that need a doctor's attention. Behind many of these decisions is a family of techniques called classification. This post walks through the core ideas, from intuition to arithmetic.

What Classification Really Means

Classification is a form of supervised learning. We give a model examples where the correct answer is already known, and the model learns a pattern it can apply to examples it has never seen.

The process has two phases:

  • Training: the model sees labelled records, each described by attributes (such as colour, size, or income) and tagged with a class (such as "fraud" or "not fraud"). It learns how the attributes relate to the class.
  • Prediction: the model receives a new record with no label and assigns it to one of the known classes.

Classification is not the same as regression. Regression predicts a continuous number, such as a house price. Classification predicts a category. Every technique below is a different way of building the mapping from attributes to classes.

Decision Trees: Learning by Asking Questions

Imagine a bank officer deciding whether a refund claim is fraudulent. She might ask: Was the refund requested within 30 days? Does the customer have a high income? Has this account filed claims before? Each answer narrows the decision until she reaches a verdict. That is how a decision tree works.

Anatomy of a tree

  • The root node holds the first question.
  • Internal nodes each test one attribute.
  • Branches represent the possible answers to a test.
  • Leaf nodes hold the final class label.

To classify a record, start at the root, follow the branch matching the record's value, and continue until you reach a leaf.

Building a tree: Hunt's idea

  1. Start with all training records at the root.
  2. If every record in a node has the same class, make that node a leaf.
  3. Otherwise, pick the attribute test that separates the classes best.
  4. Split the records according to the test's outcomes.
  5. Repeat on each child node.

The procedure is greedy: at each step it picks the best split for that node alone, without looking ahead. Greedy choices are fast and usually work well, though they do not guarantee a globally optimal tree.

Expressing the Question: Attribute Test Conditions

The form of a test depends on the type of attribute.

Nominal attributes, such as colour, have no natural order. Use one branch per value (multiway), or group the values into two sets (binary), such as {red} versus {blue, green}.

Ordinal attributes, such as clothing size (S, M, L), have an order. Groups must respect that order. Grouping {S, L} against {M} throws away information the ordering provides.

Continuous attributes, such as age, are usually split with a threshold: "Age ≤ 35" versus "Age > 35".

Binary splits are simpler to search and are used by CART. Multiway splits are common for nominal data in ID3.

Choosing the Best Split

When a node holds a mix of classes, we measure impurity: how mixed the classes are. A pure node contains one class, and a good split produces children that are purer than their parent.

Three impurity measures

For a node where p(i) is the fraction of records in class i:

  • Entropy = −Σ p(i) · log₂ p(i). Zero for a pure node, largest when classes are evenly mixed.
  • Gini index = 1 − Σ p(i)². Also zero when pure and largest when mixed. Used by CART.
  • Classification error = 1 − max p(i). The fraction misclassified if the node predicts its majority class. Simple, but less sensitive to changes in class mix, so rarely used to grow trees.

Measuring a split's quality

Gain = I(parent) − Σ (Nj / N) · I(childj)

Each child's impurity is weighted by the fraction of records it receives, so a split that sends most records into one pure child is rewarded.

  • Information gain uses entropy (ID3).
  • Gini gain uses the Gini index (CART).
  • Gain ratio divides information gain by a split-information term that penalises attributes with many distinct values. An ID column would split data perfectly but generalise terribly. C4.5 uses this measure to avoid that trap.

A worked example

A parent node has 10 records: 5 of class A and 5 of class B. One candidate split sends 4 A and 1 B left, and 1 A and 4 B right.

  • Parent Gini = 1 − (0.5² + 0.5²) = 0.50
  • Each child Gini = 1 − (0.8² + 0.2²) = 0.32
  • Weighted child Gini = 0.5 × 0.32 + 0.5 × 0.32 = 0.32
  • Gini gain = 0.50 − 0.32 = 0.18

With entropy, the parent is 1.0 and each child is about 0.722, so the information gain is about 0.278. With classification error, the error gain is 0.30.

All three measures agree this split is informative. A split that sends 5 A to one side and 5 B to the other would produce pure children and maximum gain.

The Algorithm in Full

TreeGrow(records, attributes):
    if all records share one class      → return leaf(that class)
    if attributes is empty              → return leaf(majority class)
    best = attribute test with highest gain
    partition records by best's outcomes
    for each partition:
        child = TreeGrow(partition, attributes minus best)
    return node(best, children)

Growing a tree until every leaf is pure can memorise the training data, noise included. This is overfitting. The usual remedy is pruning: trimming branches that add little predictive value, or stopping growth early.

Rule-Based Classifiers: Knowledge as IF–THEN Statements

A decision tree can be rewritten as rules, one per path from root to leaf:

  • IF Blood = Warm AND Gives birth = Yes THEN Mammal
  • IF Blood = Cold THEN Non-mammal
  • IF Gives birth = No AND Can fly = Yes THEN Bird

Two measures describe a rule:

  • Coverage: the fraction of records whose attributes match the rule's condition.
  • Accuracy: among covered records, the fraction that actually have the rule's class.

Rules extracted from a tree never overlap. Rules learned directly, for example by RIPPER, may overlap or leave gaps, so they are ordered or resolved by voting.

Nearest Neighbour: Judging by Similarity

The k-nearest neighbour classifier stores all training records. To classify a new record, it finds the k closest training records and takes a majority vote among their labels.

This makes it a lazy learner: training just stores the data, and all the work happens at prediction time.

  • Distance: Euclidean distance, d = √Σ(xᵢ − yᵢ)², is the usual default.
  • Choice of k: a small k follows the data closely and is sensitive to noise. A large k smooths the boundary but can blur classes together. An odd k avoids ties in two-class problems.
  • Normalisation: income in lakhs will swamp age in years unless both are rescaled.
  • Weighted voting: closer neighbours can count for more.

Bayesian Classifiers: Reasoning with Probability

The Bayesian approach asks how probable each class is, given the attributes observed. It uses Bayes' theorem:

P(C | X) = P(X | C) · P(C) / P(X)

P(C) is the prior, how common the class is. P(X | C) is the likelihood, how likely these attribute values are under class C. P(X) is the same for every class, so we compare classes using the numerator alone.

Naive Bayes

Estimating P(X | C) directly is hard with many attributes. Naive Bayes assumes attributes are conditionally independent given the class, so the likelihood factorises:

P(X | C) = Π P(xᵢ | C)

The prediction chooses the class that maximises P(C) · Π P(xᵢ | C). The assumption is often unrealistic, yet naive Bayes performs well in practice, especially for text such as spam filtering.

A worked example

A play-tennis dataset has 14 records: 9 Yes and 5 No. Classify a new day: Outlook = Sunny, Temperature = Cool, Humidity = High, Windy = True.

Attribute valueP(value | Yes)P(value | No)
Sunny2/93/5
Cool3/91/5
High humidity3/94/5
Windy3/93/5
  • Yes: 9/14 × (2/9 × 3/9 × 3/9 × 3/9) ≈ 0.0053
  • No: 5/14 × (3/5 × 1/5 × 4/5 × 3/5) ≈ 0.0206

The score for No is about four times larger, so the prediction is No. P(X) never had to be computed, since it cancels out.

The zero-probability problem

If a combination never appears in the training data, its probability is zero, and that zero makes the whole product zero. Laplace smoothing adds a small count to every possibility, so no probability is exactly zero.

Comparing the Approaches

MethodStrengthsWeaknesses
Decision treesInterpretable; handle mixed attribute typesCan overfit; sensitive to small data changes
Rule-basedTransparent; easy to editConflicting rules need careful handling
Nearest neighbourNo training; adapts to complex boundariesSlow on large data; depends on scaling and k
Naive BayesFast; needs little data; good for textIndependence assumption often violated

No single method wins everywhere. The right choice depends on data size, whether explanations are needed, and how the attributes behave.

Closing Thoughts

Classification rests on one goal: learn from labelled examples so that unseen examples can be sorted correctly. The methods differ in how they represent that knowledge, as questions, rules, neighbours, or probabilities. Understanding the mechanics of each makes it far easier to choose the right tool and explain its decisions to others.

Sunday, November 22, 2026

Data Science Unit I

Data Science - Unit I Notes

DATA SCIENCE – UNIT I

Introduction to Data Mining and Data Pre-processing

Course: II M.Sc. Computer Science

1. Introduction to Data Mining

Definition: Data Mining is the process of discovering useful information, hidden patterns and relationships from large amounts of data.

In simple words, Data Mining means analysing data to discover something useful.

Real-Life Example:
A supermarket analyses thousands of customer bills. It discovers that customers who buy bread also frequently buy milk. This relationship is a pattern discovered through Data Mining.
Applications:
  • Banking
  • Education
  • Healthcare
  • Online Shopping
  • Social Media

2. Kinds of Data and Patterns to Be Mined

Types of Data

TypeMeaningExample
Relational DataData stored in tablesStudent records
Transactional DataBuying and selling recordsShopping bills
Text DataWritten informationEmails and messages
Multimedia DataImages, audio and videosYouTube videos
Web DataInformation from websitesWebsite visits

Patterns to Be Mined

  • Association: Finding relationships between items.
    Example: Customers buying bread also buy butter.
  • Classification: Assigning data to predefined categories.
    Example: Classifying students as Pass or Fail.
  • Clustering: Grouping similar data together.
    Example: Grouping customers based on shopping habits.
  • Prediction: Estimating future results.
    Example: Predicting next month's sales.

3. Technologies Used in Data Mining

Data Mining combines different technologies to analyse data and discover useful knowledge.

TechnologyPurpose
DatabaseStores data
StatisticsAnalyses numerical data
Machine LearningLearns patterns from data
Artificial IntelligenceHelps machines make intelligent decisions
Data VisualizationDisplays data using charts
Big DataHandles huge amounts of data
Example: An online shopping website uses Machine Learning to recommend products based on customers' previous purchases.

4. Kinds of Applications Targeted

FieldApplication
EducationPredicting student performance
HealthcareIdentifying diseases
BankingDetecting fraudulent transactions
MarketingUnderstanding customer behaviour
RetailRecommending products
AgriculturePredicting crop production
Social MediaAnalysing user interests

5. Major Issues in Data Mining

Data Mining faces several challenges while analysing data.

  1. Data Quality: Data may contain incorrect or missing values.
  2. Data Privacy: Personal information must be protected.
  3. Data Security: Data must be protected from unauthorized access.
  4. Large Data Volume: Analysing huge amounts of data is difficult.
  5. Data Integration: Combining data from different sources is challenging.
  6. Data Complexity: Different types of data require different analysis methods.
Example: A college database contains missing attendance details and incorrect marks. These errors may produce incorrect analysis results.

6. Data Objects and Attribute Types

Data Object: A data object represents an individual item or record in a dataset.

For example, each student in a college database is considered a data object.

Roll NoNameAgeMarkResult
101Ravi2085Pass
102Priya2192Pass
103Kumar2035Fail
  • Each row represents a Data Object.
  • Each column represents an Attribute.

Types of Attributes

AttributeMeaningExample
NominalCategories without orderDepartment, Blood Group
OrdinalCategories with orderLow, Medium, High
IntervalEqual intervals without a true zeroTemperature in Celsius
RatioNumerical values with a true zeroAge, Height, Weight

7. Basic Statistical Descriptions of Data

Statistics helps us understand and summarize numerical data.

1. Mean (Average)

Mean is the sum of all values divided by the number of values.

Example:
Marks = 60, 70, 80, 90, 100

Mean = (60 + 70 + 80 + 90 + 100) / 5
Answer = 80

2. Median

Median is the middle value when data is arranged in ascending order.

Example: 10, 20, 30, 40, 50
Median = 30

3. Mode

Mode is the value that occurs most frequently.

Example: 10, 20, 20, 30, 40
Mode = 20

4. Minimum and Maximum

  • Minimum: Smallest value.
  • Maximum: Largest value.

5. Range

Range = Maximum - Minimum

Marks = 35, 45, 60, 80, 95
Range = 95 - 35
Answer = 60

8. Data Visualization

Definition: Data Visualization is the process of representing data using charts, graphs and diagrams.

It helps us understand information quickly and easily.

VisualizationPurpose
Bar ChartComparing values
Pie ChartShowing percentages
Line ChartShowing changes over time
HistogramShowing data distribution
Scatter PlotShowing relationships between two variables
Popular Visualization Tools:
  • Python Matplotlib
  • Tableau
  • Power BI
  • Microsoft Excel
Example: A teacher uses a bar chart to compare the marks of five students instead of reading each mark separately.

DATA PRE-PROCESSING

9. Introduction to Data Pre-processing

Definition: Data Pre-processing is the process of preparing raw data before analysing it.

Raw data may contain:

  • Missing values
  • Duplicate records
  • Incorrect information
  • Unnecessary data
  • Different formats
Example:
A college database contains missing marks, duplicate student records and incorrect ages. Data Pre-processing helps prepare this data for accurate analysis.

10. Data Cleaning

Definition: Data Cleaning is the process of identifying and correcting missing, incorrect, duplicate and inconsistent data.

Example – Before Cleaning:

NameMark
Ravi85
PriyaMissing
Kumar75

After Cleaning:

NameMark
Ravi85
Priya80
Kumar75

Note: 80 is an illustrative replacement value.

Main Activities:
  • Handling missing values
  • Removing duplicate records
  • Correcting incorrect values
  • Removing inconsistent data

11. Data Integration

Definition: Data Integration is the process of combining data from two or more different sources into a single dataset.

Database 1 – Student Details

Roll NoName
101Ravi
102Priya

Database 2 – Student Marks

Roll NoMark
10185
10290

After Data Integration:

Roll NoNameMark
101Ravi85
102Priya90

12. Data Reduction

Definition: Data Reduction is the process of reducing the size of data while maintaining its important information.

It helps save storage space and reduce processing time.

Example: A college has records of 10,000 students. For an initial study, it selects a representative sample of 1,000 students instead of analysing all records.
Techniques:
  • Data Sampling
  • Data Compression
  • Feature Selection
  • Dimensionality Reduction

13. Data Transformation

Definition: Data Transformation is the process of converting data from one format or structure into another suitable format for analysis.

Example 1 – Normalization

Original Marks:

20, 40, 60, 80, 100

Normalized Values using Min-Max Normalization:

0, 0.25, 0.50, 0.75, 1.00

Example 2 – Data Formatting

Original Date: 23/11/2026

Transformed Date: 2026-11-23

Common Techniques:
  • Normalization
  • Aggregation
  • Smoothing
  • Generalization

QUICK REVISION – UNIT I

TopicEasy Meaning
Data MiningFinding useful patterns from data
Kinds of DataDifferent forms of data
PatternsRelationships and trends in data
TechnologiesTools used to analyse data
ApplicationsReal-world uses of Data Mining
Major IssuesProblems faced during data analysis
Data ObjectsIndividual records
AttributesProperties of records
StatisticsSummarizing numerical data
Data VisualizationPresenting data using charts
Data CleaningCorrecting data errors
Data IntegrationCombining data sources
Data ReductionReducing data size
Data TransformationConverting data into a suitable format

IMPORTANT QUESTIONS

Part A – Short Answer Questions

  1. Define Data Mining.
  2. What is Classification?
  3. Define Clustering.
  4. What is a Data Object?
  5. List the types of Attributes.
  6. Define Mean, Median and Mode.
  7. What is Data Visualization?
  8. Define Data Cleaning.
  9. What is Data Integration?
  10. Define Data Reduction.
  11. What is Data Transformation?

Part B – Essay Questions

  1. Explain Data Mining and its applications.
  2. Discuss the different kinds of data and patterns to be mined.
  3. Explain Data Objects and Attribute Types with examples.
  4. Describe the basic statistical descriptions of data.
  5. Explain different Data Visualization techniques.
  6. Explain Data Pre-processing techniques with suitable examples.

CLASSROOM ACTIVITY

Activity: Analyse a College Student Database

Imagine that you are managing a college database. Perform the following activities:

  1. Collect student names and marks.
  2. Identify missing marks.
  3. Remove duplicate records.
  4. Calculate the average marks.
  5. Identify students who passed and failed.
  6. Represent the marks using a bar chart.
Learning Outcome:
Students will understand how raw data is collected, cleaned, analysed and represented using Data Science concepts.

REMEMBER

Data Mining discovers useful knowledge from data.

Data Pre-processing prepares the data for accurate analysis.

Unit II -Code Structures

Python Programming – Unit II: Code Structures

Python Programming

Unit II – Code Structures

II M.Sc. Computer Science

Simple Notes for Easy Understanding

Introduction

Code structures are the basic building blocks of Python programming. They help programmers control the execution of programs, repeat tasks, organize code and handle errors.

In this unit, we will learn conditional statements, loops, comprehensions, functions, generators, decorators, namespaces, scope and exception handling.

1. Conditional Statements (if, elif, else)

Conditional statements are used to make decisions based on given conditions.

  • if: Checks whether a condition is True.
  • elif: Checks another condition if the previous condition is False.
  • else: Executes when all conditions are False.

Example: Checking whether a student has passed or failed.

2. Repeat with While

A while loop executes a block of code repeatedly as long as the given condition is True.

Example: Printing numbers from 1 to 10 using a while loop.

Key Point: The condition must eventually become False to stop the loop.

3. Iterate with For

A for loop is used to repeat statements for each item in a sequence, such as a list, tuple or string.

Example: Displaying all student names stored in a list.

Key Point: A for loop is commonly used when working with collections of data.

4. Comprehensions

Comprehensions provide a shorter and simpler way to create collections in Python.

  • List Comprehension: Creates a new list.
  • Dictionary Comprehension: Creates a dictionary.
  • Set Comprehension: Creates a set.

Example: Creating a list of even numbers in a single line of code.

5. Functions

A function is a reusable block of code designed to perform a specific task.

  • Functions help avoid code repetition.
  • They make programs easier to understand.
  • Functions are defined using the def keyword.
  • The return statement sends a result back.

Example: Creating a function to add two numbers.

6. Generators

Generators are special functions that produce values one at a time instead of returning all values at once.

  • Generators use the yield keyword.
  • They are useful for handling large amounts of data.
  • They generate values when needed.

Example: Generating numbers from 1 to 5 one by one.

7. Decorators

Decorators are used to modify or extend the behaviour of an existing function without changing its original code.

  • Decorators accept a function as an argument.
  • They add additional functionality.
  • They are commonly used in advanced Python programming.

Example: Adding a welcome message before executing a function.

8. Namespaces and Scope

A namespace is a collection of names and their corresponding objects. Scope defines where a variable can be accessed in a program.

  • Local Scope: Variables created inside a function.
  • Global Scope: Variables created outside functions.
  • Enclosing Scope: Variables available in an outer function.
  • Built-in Scope: Names provided by Python itself.

Example: Understanding the difference between local and global variables.

9. Handle Errors with try and except

Exception handling is used to manage runtime errors and prevent programs from terminating unexpectedly.

  • try: Contains code that may cause an error.
  • except: Handles the error.
  • else: Executes when no exception occurs.
  • finally: Executes whether an exception occurs or not.

Example: Handling division by zero errors.

10. User Exceptions

User-defined exceptions are custom errors created by programmers to handle specific situations in a program.

  • Custom exceptions are created using classes.
  • The raise keyword is used to generate an exception.
  • They help programmers manage application-specific errors.

Example: Displaying a custom error when a student's mark is below zero.

Quick Revision Table

S.No Topic Main Purpose
1 if, elif, else Decision Making
2 while Repetition based on a condition
3 for Iteration
4 Comprehensions Shorter collection creation
5 Functions Code Reusability
6 Generators Produce values one at a time
7 Decorators Extend function behaviour
8 Namespaces and Scope Variable accessibility
9 try and except Error Handling
10 User Exceptions Create Custom Errors

Learning Outcome

After completing this unit, students will be able to:

  • Use conditional statements for decision-making.
  • Write programs using for and while loops.
  • Create collections using comprehensions.
  • Define and use Python functions.
  • Understand generators and decorators.
  • Identify namespaces and variable scopes.
  • Handle runtime errors using exception handling.
  • Create and use user-defined exceptions.

Learn Python – Practise Coding – Build Your Skills!

Python programming Lab-Msc CS

Python Programming Practical Programs

Python Programming – Practical Programs

Elementary Data Items | Lists | Tuples | Dictionaries | Conditional Branches | Loops

II M.Sc. Computer Science

Introduction

Python is a simple, powerful and beginner-friendly programming language. It is widely used in software development, Data Science, Artificial Intelligence, Machine Learning and Web Development.

In this lesson, we will learn Python programs using elementary data items, lists, tuples, dictionaries, conditional statements and loops.

1. Programs Using Elementary Data Items

Elementary data items are the basic types of data used in Python programs. They help us store different kinds of information.

Data TypeDescriptionExample
Integer (int)Whole numbers10, 20
Float (float)Decimal numbers10.5, 25.6
String (str)Text or characters"Python"
Boolean (bool)True or False valuesTrue, False

Program 1: Basic Arithmetic Operations

Aim: To perform addition, subtraction, multiplication and division.
Python Program
a = 20
b = 10

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
Output:
Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2.0

Program 2: Display Student Details

Aim: To display student information using different data types.
Python Program
name = "Arun"
age = 21
mark = 85.5

print("Student Name:", name)
print("Age:", age)
print("Mark:", mark)
Output:
Student Name: Arun
Age: 21
Mark: 85.5

2. Programs Using Lists

A list is a collection of elements stored in a single variable. Lists are ordered, changeable and allow duplicate values.

Lists are created using square brackets [ ].

Program 1: Create and Display a List

Aim: To create a list of fruits and display its elements.
Python Program
fruits = ["Apple", "Banana", "Mango"]

print("Fruits:", fruits)
print("First Fruit:", fruits[0])
Output:
Fruits: ['Apple', 'Banana', 'Mango']
First Fruit: Apple
Explanation: List indexing starts from zero. Therefore, fruits[0] displays the first element.

Program 2: Add and Remove Elements

Aim: To add and remove elements from a list.
Python Program
numbers = [10, 20, 30]

numbers.append(40)
print("After Adding:", numbers)

numbers.remove(20)
print("After Removing:", numbers)
Output:
After Adding: [10, 20, 30, 40]
After Removing: [10, 30, 40]

Program 3: Find the Sum of List Elements

Aim: To calculate the sum of all elements in a list.
Python Program
numbers = [10, 20, 30, 40, 50]

total = sum(numbers)

print("Sum:", total)
Output:
Sum: 150

3. Programs Using Tuples

A tuple is a collection of elements stored in a single variable. Tuples are ordered and immutable, which means their elements cannot be changed after creation.

Tuples are created using parentheses ( ).

Program 1: Create and Display a Tuple

Aim: To create a tuple and access its elements.
Python Program
student = ("Arun", 21, 85)

print("Student Details:", student)
print("Name:", student[0])
print("Age:", student[1])
print("Mark:", student[2])
Output:
Student Details: ('Arun', 21, 85)
Name: Arun
Age: 21
Mark: 85

Program 2: Tuple Operations

Aim: To perform basic tuple operations.
Python Program
numbers = (10, 20, 30, 20, 40)

print("Tuple:", numbers)
print("Length:", len(numbers))
print("Count of 20:", numbers.count(20))
print("Index of 30:", numbers.index(30))
Output:
Tuple: (10, 20, 30, 20, 40)
Length: 5
Count of 20: 2
Index of 30: 2

4. Programs Using Dictionaries

A dictionary is a collection of data stored in key-value pairs. Each key is used to access its corresponding value.

Dictionaries are created using curly brackets { }.

Program 1: Display Student Details

Aim: To create and display student details using a dictionary.
Python Program
student = {
    "Name": "Arun",
    "Age": 21,
    "Mark": 90
}

print("Student Name:", student["Name"])
print("Age:", student["Age"])
print("Mark:", student["Mark"])
Output:
Student Name: Arun
Age: 21
Mark: 90

Program 2: Add and Update Dictionary Elements

Aim: To add a new element and update an existing value.
Python Program
student = {"Name": "Arun", "Mark": 80}

student["Age"] = 21
student["Mark"] = 95

print(student)
Output:
{'Name': 'Arun', 'Mark': 95, 'Age': 21}

5. Programs Using Conditional Branches

Conditional statements are used to make decisions in Python programs. They execute different blocks of code depending on whether a condition is True or False.

Types of conditional statements:

  • if statement
  • if-else statement
  • if-elif-else statement
  • Nested if statement

Program 1: Check Positive or Negative Number

Aim: To check whether a given number is positive, negative or zero.
Python Program
num = int(input("Enter a number: "))

if num > 0:
    print("Positive Number")
elif num < 0:
    print("Negative Number")
else:
    print("Zero")
Sample Output:
Enter a number: 10
Positive Number

Program 2: Find the Largest of Two Numbers

Aim: To find the largest number using an if-else statement.
Python Program
a = 10
b = 20

if a > b:
    print("A is Largest")
else:
    print("B is Largest")
Output:
B is Largest

Program 3: Check Student Pass or Fail

Aim: To check whether a student has passed or failed.
Python Program
mark = int(input("Enter your mark: "))

if mark >= 40:
    print("Pass")
else:
    print("Fail")
Sample Output:
Enter your mark: 75
Pass

Program 4: Find Student Grade

Aim: To calculate a student's grade using if-elif-else.
Python Program
mark = int(input("Enter your mark: "))

if mark >= 90:
    print("Grade A")
elif mark >= 75:
    print("Grade B")
elif mark >= 60:
    print("Grade C")
elif mark >= 40:
    print("Grade D")
else:
    print("Fail")
Sample Output:
Enter your mark: 85
Grade B

6. Programs Using Loops

A loop is used to execute a block of statements repeatedly until a particular condition is satisfied.

Types of loops in Python:

  • For Loop
  • While Loop

Program 1: Print Numbers from 1 to 10 Using For Loop

Aim: To display numbers from 1 to 10 using a for loop.
Python Program
for i in range(1, 11):
    print(i)
Output:
1
2
3
4
5
6
7
8
9
10

Program 2: Print Numbers Using While Loop

Aim: To display numbers from 1 to 10 using a while loop.
Python Program
i = 1

while i <= 10:
    print(i)
    i = i + 1
Output:
1
2
3
4
5
6
7
8
9
10

Program 3: Sum of First 10 Natural Numbers

Aim: To calculate the sum of the first 10 natural numbers.
Python Program
total = 0

for i in range(1, 11):
    total = total + i

print("Sum:", total)
Output:
Sum: 55

Program 4: Generate Multiplication Table

Aim: To generate the multiplication table for a given number.
Python Program
num = int(input("Enter a number: "))

for i in range(1, 11):
    print(num, "x", i, "=", num * i)
Sample Output:
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Program 5: Find Factorial of a Number

Aim: To calculate the factorial of a given number using a for loop.
Python Program
num = int(input("Enter a number: "))
fact = 1

for i in range(1, num + 1):
    fact = fact * i

print("Factorial:", fact)
Sample Output:
Enter a number: 5
Factorial: 120

Program 6: Print Even Numbers from 1 to 20

Aim: To display even numbers between 1 and 20.
Python Program
for i in range(1, 21):
    if i % 2 == 0:
        print(i)
Output:
2
4
6
8
10
12
14
16
18
20

7. Practical Exercise – Student Practice

Students can practise the following programs to improve their Python programming and logical thinking skills.

S.NoPractical Exercise
1Perform arithmetic operations using elementary data items.
2Create and manipulate lists.
3Perform tuple operations.
4Create and update dictionary elements.
5Find the largest of two numbers using conditional statements.
6Find the grade of a student using if-elif-else.
7Check whether a number is odd or even.
8Print natural numbers using a for loop.
9Find the sum of natural numbers using a loop.
10Generate a multiplication table.
11Find the factorial of a number.
12Display even and odd numbers using loops.

Conclusion

In this lesson, we learned the basic Python programming concepts, including elementary data items, lists, tuples, dictionaries, conditional branches and loops.

These concepts form the foundation of Python programming. By practising these programs regularly, students can improve their coding skills, develop logical thinking and prepare themselves for advanced Python topics.

Keep Practising Python – Learn, Code and Grow!

Monday, October 19, 2026

Online Quiz-C & C++

📝 Online Quiz - Assistant Professor Test

Click below to download and attend the quiz

Download & Start Test

After download, open file from your phone's Files/Downloads to start test.
பதிவிறக்கம் செய்த பிறகு Files-ல் இருந்து Open செய்யவும்.

Saturday, July 25, 2026

Faculty AI assistant professor

Faculty AI Assistant
FA

Faculty AI Assistant

Mrs. S. Srividhya · Timetable · Syllabus · Teaching content

online

Pin your first question to the board

Fill in your Timetable and Syllabus tabs first — then ask for a lecture plan, quiz, or teaching content and I'll build it around your actual classes and topics.

Weekly Timetable

Saved ✓

Filled in from your timetable photo, as best as I could read it — some handwritten / crossed-out cells were unclear, so please tap any cell and correct it. "VAC" = your Generative AI & Prompt Engineering value-added course.

Day Hour 1Hour 2Hour 3Hour 4Hour 5Hour 6

Subjects on record

Syllabus by Subject

Paste or type each subject's units / topics (in teaching order). The chat assistant reads this to generate on-topic lecture notes, quizzes, and teaching content — so the more complete this is, the better its output.

Responses are AI-generated — review before use in class.

Wednesday, January 7, 2026

Function, Class and Object

  I. Functions in C++

A function is a block of code that performs a specific task.

It helps in code reusability, modularity, and readability.

General Syntax

Copy code

Cpp

return_type function_name(parameters)

{

    // statements

}

1. Inline Functions

An inline function is a function whose function call is replaced by the function code itself during compilation.

Purpose

Avoids function call overhead

Increases execution speed

Used for small functions

Syntax

Copy code

Cpp

inline return_type function_name(parameters)

Example

Copy code

Cpp

#include <iostream>

using namespace std;


inline int square(int x)

{

    return x * x;

}


int main()

{

    cout << square(5);

    return 0;

}

Advantage

✔ Faster execution

Limitation

❌ Not suitable for large functions

2. Function Overloading

Function overloading allows multiple functions with the same name but different parameters.

Purpose

Improves code clarity

Implements compile-time polymorphism

Rules

Functions must differ in:

Number of arguments

Type of arguments

(Return type alone is NOT enough)

Example

Copy code

Cpp

#include <iostream>

using namespace std;


int add(int a, int b)

{

    return a + b;

}


float add(float a, float b)

{

    return a + b;

}


int main()

{

    cout << add(10, 20) << endl;

    cout << add(2.5f, 3.5f);

    return 0;

}

II. Classes and Objects

Class

A class is a blueprint that contains data members and member functions.

Object

An object is an instance of a class.

1. Declaring Objects

Syntax

Copy code

Cpp

class_name object_name;

Example

Copy code

Cpp

class Student

{

public:

    int roll;

};


Student s1;

2. Defining Member Functions

Member functions can be defined:

Inside the class

Outside the class using scope resolution operator (::)

Example (Outside class)

Copy code

Cpp

#include <iostream>

using namespace std;


class Sample

{

public:

    void show();

};


void Sample::show()

{

    cout << "Hello C++";

}


int main()

{

    Sample s;

    s.show();

    return 0;

}

3. Static Member Variables and Functions

Static Member Variable

Shared by all objects

Only one copy exists

Static Member Function

Can access only static members

Called using class name

Example

Copy code

Cpp

#include <iostream>

using namespace std;


class Count

{

public:

    static int c;


    static void show()

    {

        cout << "Count = " << c;

    }

};


int Count::c = 10;


int main()

{

    Count::show();

    return 0;

}

4. Array of Objects

Used when multiple objects of the same class are needed.

Example

Copy code

Cpp

#include <iostream>

using namespace std;


class Student

{

public:

    int roll;

};


int main()

{

    Student s[3];

    s[0].roll = 101;

    s[1].roll = 102;

    s[2].roll = 103;


    for(int i=0;i<3;i++)

        cout << s[i].roll << endl;


    return 0;

}

5. Friend Functions

A friend function can access private and protected members of a class.

Purpose

Allows external function to access class data

Example

Copy code

Cpp

#include <iostream>

using namespace std;


class Sample

{

private:

    int x;

public:

    Sample()

    {

        x = 10;

    }

    friend void show(Sample s);

};


void show(Sample s)

{

    cout << s.x;

}


int main()

{

    Sample s;

    show(s);

    return 0;

}

6. Overloading Member Functions

Member functions of a class can be overloaded.

Example

Copy code

Cpp

#include <iostream>

using namespace std;


class Demo

{

public:

    void display(int a)

    {

        cout << a << endl;

    }


    void display(float b)

    {

        cout << b << endl;

    }

};


int main()

{

    Demo d;

    d.display(10);

    d.display(5.5f);

    return 0;

}

7. Bit Fields and Classes

Bit fields allow storing data in bits, saving memory.

Syntax

Copy code

Cpp

data_type variable : size;

Example

Copy code

Cpp

#include <iostream>

using namespace std;


class Flags

{

public:

    unsigned int a : 1;

    unsigned int b : 1;

};


int main()

{

    Flags f;

    f.a = 1;

    f.b = 0;


    cout << f.a << " " << f.b;

    return 0;

}

8. Constructor and Destructor with Static Members

Constructor

Called automatically when object is created

Destructor

Called when object is destroyed

Example

Copy code

Cpp

#include <iostream>

using namespace std;


class Test

{

public:

    static int count;


    Test()

    {

        count++;

        cout << "Object Created: " << count << endl;

    }


    ~Test()

    {

        cout << "Object Destroyed" << endl;

    }

};


int Test::count = 0;


int main()

{

    Test t1, t2;

    return 0;

}

⭐ Importance (Why We Use These Concepts)

Concept

Purpose

Inline function

Faster execution

Function overloading

Code clarity & polymorphism

Class & object

Real-world modeling

Static members

Shared data

Friend function

Controlled data access

Array of objects

Handle multiple objects

Bit fields

Memory optimization

Constructor & destructor

Resource management

Desision Tree

Inside Classification: How Machines Learn to Sort the World Inside Classification: How Machines Learn to Sort the World Every d...