Monday, November 30, 2026

Unit-II

Python: Iteration to Exceptions - Lecture 7 | Control, Abstraction, and Robustness
Lecture 7 • Python Course • Assistant Professor

Python: Iteration to Exceptions

Control, Abstraction, and Robustness. Iterate with intention, package behaviour in functions, generate lazily, wrap carefully, know where your names live, and let errors speak in the language of your problem.

1. Iterate with for

A for loop in Python is not a counter. It is an iterator protocol. It asks an object: "Give me your next item," until there is none left.

fruits = ["apple", "mango", "banana"]
for fruit in fruits:
    print(fruit)

Internally: iter(fruits) → repeatedly next(iterator) → StopIteration ends the loop.

marks = {"Anitha": 92, "Kumar": 78, "Priya": 85}
for name, mark in marks.items():
    print(f"{name} scored {mark}")

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
Professor's Note: If you write for i in range(len(list)), stop. Use for item in list or for i, item in enumerate(list).

2. Comprehensions

A comprehension is a for loop compressed into an expression that builds a new collection.

numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
even_squares = [n * n for n in numbers if n % 2 == 0]
name_lengths = {fruit: len(fruit) for fruit in fruits}
first_letters = {fruit[0] for fruit in fruits}

Structure: [expression for variable in iterable if condition]

Do NOT use comprehensions only for side effects: [print(x) for x in numbers] is bad style. Use a normal loop for actions, comprehension for building values.

3. Functions

def greet(name, greeting="Vanakkam"):
    """Return a greeting message."""
    return f"{greeting}, {name}!"

print(greet("Anitha"))
print(greet("Kumar", greeting="Hello"))

def total(*numbers):
    return sum(numbers)

def show_profile(**details):
    for key, value in details.items():
        print(key, ":", value)

def min_max(data):
    return min(data), max(data)

low, high = min_max([10, 20, 5, 30])

Parameters are in the definition. Arguments are in the call. Never use a mutable default like def f(x=[]).

4. Generators

A normal function computes everything at once. A generator computes one item at a time with yield. It is lazy.

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

squares_gen = (x*x for x in range(10000000))
print(next(squares_gen))  # 0
Classic Exam Question: Fibonacci Generator
def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

for num in fibonacci(20):
    print(num, end=" ")

Note: (x*x for x in ...) is a generator expression. [x*x for x in ...] is a list comprehension.

5. Decorators

A decorator takes a function and returns a new, enhanced function. @timer is shorthand for func = timer(func).

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f} seconds")
        return result
    return wrapper

@timer
def slow_work():
    time.sleep(1)
    return "Done"

print(slow_work())

6. Namespaces and Scope

Python follows LEGB: Local → Enclosing → Global → Built-in.

x = 100  # Global
def outer():
    x = 50  # Enclosing
    def inner():
        x = 10  # Local
        print(x)  # 10
    inner()
    print(x)  # 50
outer()
print(x)  # 100
count = 0
def increment():
    global count
    count += 1

def counter():
    count = 0
    def inc():
        nonlocal count
        count += 1
        return count
    return inc

c = counter()
print(c())  # 1
print(c())  # 2

7. Handle Errors with try and except

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("No error occurred.")
finally:
    print("This always runs, for cleanup.")

Catch specific exceptions, not bare except:. A bare except hides bugs.

8. User Exceptions

Define your own by inheriting from Exception when your domain has a specific error.

class InvalidMarksError(Exception):
    """Raised when marks are outside 0 to 100."""
    pass

def set_marks(marks):
    if not 0 <= marks <= 100:
        raise InvalidMarksError(f"Marks {marks} are invalid. Must be 0 to 100.")
    return f"Marks accepted: {marks}"

try:
    print(set_marks(120))
except InvalidMarksError as e:
    print("Error:", e)
class InsufficientBalanceError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Need {amount}, but balance is only {balance}")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError(balance, amount)
    return balance - amount

9. Putting It All Together

class InvalidAgeError(Exception):
    pass

def get_eligible_students(students):
    def check_age(student):
        name, age = student
        if age < 0:
            raise InvalidAgeError(f"Age cannot be negative for {name}")
        return age >= 18

    for student in students:
        try:
            if check_age(student):
                yield student[0]
        except InvalidAgeError as e:
            print("Skipping:", e)

students = [("Anitha", 20), ("Kumar", 17), ("Priya", -5), ("Ravi", 19)]
print(list(get_eligible_students(students)))

Assignment for Next Class

Write a decorator @validate_marks that checks if a function's argument is between 0 and 100, and raises InvalidMarksError if not.

@validate_marks
def record_score(name, mark):
    return f"{name}: {mark}"

print(record_score("Anitha", 92))  # Anitha: 92
# record_score("Kumar", 140)  # should raise InvalidMarksError
Python: Iteration to Exceptions • Lecture 7 • Control, Abstraction, and Robustness

Decision Tree

Decision Tree - Working and Building
MACHINE LEARNING | STUDY NOTES

Decision Tree

Working of Decision Tree & Building a Decision Tree

Simple Concepts • Real-World Examples • Easy Learning

1. Introduction to Decision Tree

A Decision Tree is a supervised machine learning algorithm used for classification and prediction. It represents decisions in the form of a tree-like structure.

Simple Definition:
A Decision Tree is a flowchart-like model that makes decisions by checking conditions step by step until it reaches a final result.

Real-World Example

A college wants to predict whether a student will pass or fail based on attendance and internal marks.

  • Check student attendance.
  • Check internal examination marks.
  • Predict the final result.

2. Working of a Decision Tree

A Decision Tree starts with the complete dataset and divides it into smaller groups based on selected conditions. It continues this process until a final prediction is obtained.

Steps Involved in Working

1
Start with Dataset

Collect training data containing input attributes and output labels.

2
Select the Best Attribute

Identify the most useful attribute for dividing the dataset.

3
Split the Dataset

Divide the records into smaller groups based on a condition.

4
Repeat the Process

Continue splitting the groups until a suitable final decision is reached.

5
Generate Prediction

Reach a leaf node to obtain the final output.

3. Components of Decision Tree

🌳

Root Node

The starting point containing the complete dataset.

🔷

Decision Node

Represents a condition or attribute test.

➡️

Branch

Represents the outcome of a condition.

🍃

Leaf Node

Represents the final prediction or result.

4. Building a Decision Tree

Building a Decision Tree means creating a tree structure using training data to make predictions for new data.

1
Collect Training Dataset

Gather the required data with input attributes and target values.

2
Identify Attributes

Separate input features and the target variable.

3
Select Root Node

Choose the best attribute using Information Gain, Entropy or Gini Index.

4
Divide the Dataset

Split records into groups according to the selected condition.

5
Create Child Nodes

Create additional decision nodes for groups that need further splitting.

6
Repeat Splitting

Continue until a stopping condition is satisfied.

7
Create Leaf Nodes

Assign the final class or predicted value.

8
Pruning

Remove unnecessary branches to reduce complexity and overfitting.

5. Methods for Selecting Attributes

1. Entropy

Entropy measures the impurity or uncertainty in a dataset. Lower entropy indicates more homogeneous data.

Entropy(S) = - Σ p(i) log₂ p(i)

2. Information Gain

Information Gain measures how much uncertainty is reduced after splitting a dataset using an attribute.

Information Gain = Parent Entropy − Weighted Child Entropy
Remember: The attribute with the highest Information Gain is generally selected for splitting.

3. Gini Index

Gini Index measures the impurity of a dataset. A lower Gini value indicates a purer group.

Gini(S) = 1 − Σ p(i)²

4. Gain Ratio

Gain Ratio adjusts Information Gain using Split Information. It helps reduce the bias towards attributes having many values.

Gain Ratio = Information Gain / Split Information

6. Example: Student Pass or Fail Prediction

Consider a college predicting student results using attendance and internal marks.

Student Attendance Internal Mark Result
A90%80Pass
B60%30Fail
C85%70Pass
D50%25Fail
E80%45Pass

Decision Tree Diagram

Attendance ≥ 75%?
YES
↓
PASS
NO
↓
Internal Mark ≥ 40?
YES
↓
PASS
NO
↓
FAIL
Note: This is a simplified teaching example. Actual examination eligibility and pass rules depend on institutional regulations.

7. Advantages of Decision Tree

  • Easy to understand and interpret.
  • Simple to construct and visualize.
  • Handles numerical and categorical data.
  • Useful for classification and prediction.
  • Requires less data preparation.

8. Disadvantages of Decision Tree

  • Large trees can become difficult to understand.
  • Small changes in data may create a different tree.
  • Overfitting may occur.
  • Pruning may be required.

9. Applications

🎓

Education

Student performance prediction

🏦

Banking

Loan approval prediction

🏥

Healthcare

Disease classification

🛒

Marketing

Customer behaviour analysis

10. Quick Revision

TermMeaning
Decision TreeTree-based prediction algorithm
Root NodeStarting point
Decision NodePerforms a condition test
BranchOutcome of a condition
Leaf NodeFinal prediction
EntropyMeasures impurity
Information GainReduction in uncertainty
PruningRemoval of unnecessary branches

11. Test Your Knowledge

Choose the correct answer for each question.

Q1. What is the starting point of a Decision Tree?

Q2. Which method measures impurity?

Q3. What is the purpose of pruning?

12. Conclusion

A Decision Tree is a simple and powerful machine learning algorithm. It works by selecting the best attributes, splitting the dataset into smaller groups and generating final predictions through leaf nodes.

Classroom Activity:
Construct a Decision Tree for the question: "Should a person carry an umbrella?" Use weather conditions such as Sunny, Rainy and Cloudy.

Learning Machine Learning

Understand Concepts • Practice Examples • Build Knowledge

Educational Notes | Decision Tree

Sunday, November 29, 2026

Python programming (1-5 program)

React Artifact

Unit-II

Python: Iteration to Exceptions - Lecture 7 | Control, Abstraction, and Robustness Lecture 7 • Python Course • Assistant Profess...