Monday, March 16, 2026

Lesson 10: Python Modules and Libraries | Coding Class Series

March 16, 2026 0



Lesson 10: Python Modules and Libraries | Coding Class Series

Introduction

Welcome to Lesson 10!
In this lesson, we will learn about Python Modules and Libraries. These are essential for reusing code, extending Python functionality, and making development faster and easier.


1. What is a Module?

A module is a Python file (.py) that contains functions, classes, and variables which you can use in other Python programs.

Example:

# math_module.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

You can use this module in another file using import:

import math_module

print(math_module.add(10, 5))       # Output: 15
print(math_module.subtract(10, 5))  # Output: 5

2. Built-in Python Modules

Python has many built-in modules ready to use:

  • math → Mathematical functions
  • random → Random number generation
  • datetime → Date and time functions
  • os → Operating system functionalities

Example:

import math
import random
from datetime import datetime

print(math.sqrt(25))          # Output: 5.0
print(random.randint(1, 10))  # Output: Random number between 1 and 10
print(datetime.now())         # Output: Current date and time

3. Installing Third-Party Libraries

Python libraries like requests, numpy, pandas, etc., can be installed using pip:

pip install requests
pip install numpy

Example using requests:

import requests

response = requests.get("https://api.github.com")
print(response.status_code)  # Output: 200

4. Creating Your Own Library

You can combine multiple modules into a package (your own library):

my_library/
│
├── __init__.py
├── math_utils.py
└── string_utils.py

Usage:

from my_library.math_utils import add
print(add(5, 10))  # Output: 15

5. Practice Exercises

  1. Create a module calc.py with functions multiply and divide. Import it in another file and test it.
  2. Use the random module to generate a random list of numbers and find the max and min.
  3. Install requests and fetch data from any public API.
  4. Create a simple package with 2 modules and use it in a program.


Lesson 9: Object-Oriented Programming (OOP) in Python | Coding Class Series

March 16, 2026 0



Lesson 9: Object-Oriented Programming (OOP) in Python | Coding Class Series

Introduction

Welcome to Lesson 9!
In this lesson, we will learn Object-Oriented Programming (OOP) in Python, which is a powerful way to structure code using classes and objects. OOP helps you write reusable, organized, and maintainable programs.


1. What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities.
Key concepts:

  • Class → Blueprint of an object
  • Object → Instance of a class
  • Attributes → Properties of an object
  • Methods → Functions of an object

2. Creating a Class and Object

Example:

class Person:
    def __init__(self, name, age):
        self.name = name  # Attribute
        self.age = age    # Attribute

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object
person1 = Person("Alice", 20)
person1.greet()  # Output: Hello, my name is Alice and I am 20 years old.

Explanation:

  • __init__ → Constructor method, runs automatically when object is created
  • self → Refers to the current object

3. Inheritance

Inheritance allows a class to reuse code from another class.

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def show_id(self):
        print(f"My student ID is {self.student_id}")

student1 = Student("Bob", 18, "S123")
student1.greet()      # Inherited method
student1.show_id()    # Own method

Benefits:

  • Reuse existing code
  • Create hierarchical relationships
  • Simplify complex programs

4. Encapsulation

Encapsulation is the concept of hiding private details of an object.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # Output: 1500

Note: Prefix __ to make an attribute private.


5. Polymorphism

Polymorphism allows methods with the same name to behave differently depending on the object.

class Dog:
    def speak(self):
        print("Woof!")

class Cat:
    def speak(self):
        print("Meow!")

animals = [Dog(), Cat()]
for animal in animals:
    animal.speak()
# Output: Woof! Meow!

6. Practice Exercises

  1. Create a class Car with attributes brand and year, and method display_info().
  2. Create a subclass ElectricCar that inherits from Car and adds battery_capacity.
  3. Create objects of both classes and call their methods.
  4. Make a class Account with private balance and methods deposit and withdraw.


Lesson 8: File Handling and Exception Handling | Coding Class Series

March 16, 2026 0



Lesson 8: File Handling and Exception Handling | Coding Class Series

Introduction

Welcome to Lesson 8!
In this lesson, we will learn about file handling in Python and how to manage errors using exception handling. These skills are essential to make your programs robust and data-driven.


1. File Handling

File handling allows your program to read from and write to files on your computer.

Opening a file:

file = open("example.txt", "w")  # 'w' mode to write
file.write("Hello, Python!")
file.close()

Reading a file:

file = open("example.txt", "r")  # 'r' mode to read
content = file.read()
print(content)  # Output: Hello, Python!
file.close()

Using with statement (recommended):

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

File Modes:

  • r → read
  • w → write (overwrite)
  • a → append
  • rb / wb → read/write binary

2. Exception Handling

Exceptions occur when your program runs into an error.
Python allows you to handle exceptions gracefully using try, except, finally blocks.

Example:

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Enter a number.")
finally:
    print("Execution completed.")

Key Points:

  • try: Block where error might occur
  • except: Handles specific errors
  • finally: Executes always, even if an error occurs

3. Combining File Handling and Exceptions

You can handle file errors with exception handling:

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found. Please check the file name!")

Benefits:

  • Prevents program crashes
  • Provides useful error messages
  • Improves program reliability

4. Practice Exercises

  1. Create a file notes.txt and write 5 lines of text in it.
  2. Read the file and count the number of words.
  3. Write a program that asks the user for a filename and prints its content. Handle errors if the file does not exist.
  4. Create a program that divides two numbers and handles division by zero and invalid input using exception handling.


Lesson 7: Functions and Modules | Coding Class Series

March 16, 2026 0



Lesson 7: Functions and Modules | Coding Class Series

Introduction

Welcome to Lesson 7!
In this lesson, we will learn about functions and modules in Python. Functions allow you to reuse code, while modules help you organize your programs efficiently.


1. Functions

A function is a block of code that performs a specific task and can be reused multiple times.

Syntax:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!

Key Points:

  • Functions start with the def keyword.
  • Arguments can be passed inside parentheses.
  • return keyword is used to give back a result.

Example with Return:

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

2. Modules

A module is a file containing Python definitions and functions.
You can import modules to use their functions in your program.

Importing a module:

import math

print(math.sqrt(16))  # Output: 4.0

From module import specific function:

from math import pow

print(pow(2, 3))  # Output: 8.0

Creating your own module:

  1. Create a file my_module.py:
def welcome():
    print("Welcome to my module!")
  1. Import in another file:
import my_module

my_module.welcome()  # Output: Welcome to my module!

3. Advantages of Functions and Modules

  • Reusability: Write once, use multiple times.
  • Organization: Keeps code clean and structured.
  • Efficiency: Saves time and reduces errors.
  • Scalability: Easier to maintain and expand large programs.

Practice Exercises

  1. Create a function multiply(a, b) that returns the product of two numbers.
  2. Write a function that takes a list of numbers and returns the largest number.
  3. Create a module math_utils.py with a function square(n) that returns the square of a number. Import it and test.
  4. Use the random module to generate 5 random numbers between 1 and 50.


Lesson 6: Lists, Tuples, and Dictionaries | Coding Class Series

March 16, 2026 0



Lesson 6: Lists, Tuples, and Dictionaries | Coding Class Series

Introduction

Welcome to Lesson 6!
In this lesson, we will learn about Python data structures: lists, tuples, and dictionaries. These structures help you store and organize multiple values efficiently.


1. Lists

A list is an ordered and mutable collection of items.
You can add, remove, or change elements in a list.

Syntax:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Access first item

Common List Methods:

fruits.append("orange")     # Add item
fruits.remove("banana")     # Remove item
fruits.sort()               # Sort items
print(fruits)

2. Tuples

A tuple is ordered but immutable.
Once created, you cannot change its elements.

Syntax:

coordinates = (10, 20)
print(coordinates[0])

Why use tuples?

  • They are faster than lists
  • Useful for data that should not change, like coordinates or constants.

3. Dictionaries

A dictionary stores key-value pairs.
You can access values using keys, not indexes.

Syntax:

student = {"name": "Alice", "age": 16, "grade": "A"}
print(student["name"])  # Output: Alice

Common Dictionary Methods:

student["age"] = 17        # Update value
student["city"] = "Delhi"  # Add new key-value pair
print(student.keys())      # Show all keys
print(student.values())    # Show all values

Practice Exercises

  1. Create a list of your 5 favorite movies. Print them in alphabetical order.
  2. Create a tuple of your 3 favorite colors and try to change one color (observe what happens).
  3. Create a dictionary for a book: title, author, year. Update the year and print all keys and values.
  4. Use a list of dictionaries to store 3 students’ information and print each student’s name and grade.


Lesson 5: Conditional Statements and Loops | Coding Class Series

March 16, 2026 0



Lesson 5: Conditional Statements and Loops | Coding Class Series

Introduction

Welcome to Lesson 5!
In this lesson, we will learn how to make decisions in your code using conditional statements (if, elif, else) and how to repeat tasks efficiently using loops (for and while).


Conditional Statements

Conditional statements let your program execute code based on certain conditions.

Syntax in Python:

age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

Explanation:

  • if age >= 18: → checks if the condition is True
  • else: → executes if the condition is False

Example with multiple conditions:

marks = 75

if marks >= 90:
    print("Grade: A")
elif marks >= 75:
    print("Grade: B")
else:
    print("Grade: C")

Loops

Loops allow repeating code multiple times without rewriting it.

For Loop

Used to iterate over sequences like lists, strings, or ranges.

for i in range(1, 6):
    print(f"Number: {i}")

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

While Loop

Executes code as long as a condition is True.

count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Practice Exercises

  1. Write a program to check if a number is positive, negative, or zero using if-elif-else.
  2. Print all even numbers from 1 to 50 using a for loop.
  3. Use a while loop to print the first 10 Fibonacci numbers.
  4. Write a program to count the number of vowels in a string using a loop.


क्या मैं Lesson 6 भी बना दूँ?

Lesson 4: Functions and Modular Programming | Coding Class Series

March 16, 2026 0



Lesson 4: Functions and Modular Programming | Coding Class Series

Introduction

Welcome to Lesson 4!
In this lesson, we will learn about functions – reusable blocks of code – and how to organize your program into modules. Functions make your code cleaner, easier to read, and maintainable.


What is a Function?

A function is a block of code that performs a specific task. You can call it whenever you need to perform that task.

Example in Python:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!
greet("Bob")    # Output: Hello, Bob!

Explanation:

  • def greet(name): → defines a function named greet with a parameter name.
  • print(f"Hello, {name}!") → code inside the function.
  • greet("Alice") → calls the function with argument "Alice".

Benefits of Functions

  1. Reusability: Write once, use many times.
  2. Readability: Makes code organized and easier to understand.
  3. Debugging: Easy to test and fix small blocks of code.

Modular Programming

Modular programming is the practice of splitting your code into multiple files or modules. Each module has a specific purpose, making your program scalable and easier to maintain.

Example:

  • math_utils.py → contains functions for math operations
  • main.py → calls functions from math_utils.py
# math_utils.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

# main.py
from math_utils import add, subtract

print(add(5, 3))      # Output: 8
print(subtract(5, 3)) # Output: 2

Practice Exercises

  1. Write a function to calculate the factorial of a number.
  2. Create a function to check if a string is a palindrome.
  3. Write a module string_utils.py containing functions: reverse_string(), count_vowels().
  4. Import the module in another file and test all the functions.