Showing posts with label Python tutorial. Show all posts
Showing posts with label Python tutorial. Show all posts

Monday, March 16, 2026

Lesson 16: Python Modules, Packages, and Pip | Coding Class Series

March 16, 2026 0



Lesson 16: Python Modules, Packages, and Pip | Coding Class Series

Introduction

Welcome to Lesson 16!
In this lesson, we will learn about Python modules and packages, how to import them, and how to install external libraries using pip.
Modules and packages help you organize code and reuse functionality efficiently.


1. What is a Module?

A module is a file containing Python code (functions, classes, variables).
You can reuse modules in multiple programs.

Example: math module

import math

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

2. Importing Modules

You can import a module in different ways:

# Import the whole module
import math
print(math.factorial(5))  # Output: 120

# Import specific functions
from math import factorial, ceil
print(factorial(6))  # Output: 720
print(ceil(4.2))     # Output: 5

# Import with alias
import math as m
print(m.sqrt(25))    # Output: 5.0

3. Creating Your Own Module

You can create a module by saving functions in a .py file.

my_module.py

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

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

main.py

import my_module

print(my_module.greet("Alice"))
print(my_module.add(10, 5))

4. What is a Package?

A package is a folder containing multiple modules and an __init__.py file.
It allows better organization of related modules.

Example structure:

my_package/
    __init__.py
    module1.py
    module2.py

Usage:

from my_package import module1
module1.function_name()

5. Installing External Libraries with pip

pip is the Python package manager. You can install external libraries easily.

# Install a library
pip install requests

# Check installed libraries
pip list

Example usage:

import requests

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

6. Upgrading and Uninstalling Packages

# Upgrade a package
pip install --upgrade requests

# Uninstall a package
pip uninstall requests

7. Practice Exercises

  1. Create a module calculator.py with functions for addition, subtraction, multiplication, and division. Import it in another program.
  2. Organize two modules (math_ops.py and string_ops.py) into a package my_utils. Import and use functions.
  3. Install the numpy library using pip and create an array.
  4. Upgrade numpy and then uninstall it using pip commands.


Lesson 15: Python Exception Handling and Debugging | Coding Class Series

March 16, 2026 0



Lesson 15: Python Exception Handling and Debugging | Coding Class Series

Introduction

Welcome to Lesson 15!
In this lesson, we will learn how to handle errors in Python programs using exceptions and debug our code.
Exception handling is important to prevent program crashes and manage unexpected situations gracefully.


1. What is an Exception?

An exception is an error that occurs during the execution of a program.
Common examples:

  • Division by zero
  • File not found
  • Index out of range
# Division by zero
a = 10
b = 0
print(a / b)  # Raises ZeroDivisionError

2. Try and Except

Use try and except to catch and handle exceptions.

try:
    a = 10
    b = 0
    print(a / b)
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")

3. Handling Multiple Exceptions

You can handle different types of exceptions separately.

try:
    numbers = [1, 2, 3]
    print(numbers[5])
    a = 10 / 0
except IndexError:
    print("Index not found in the list!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

4. Using else and finally

  • else: runs if no exception occurs
  • finally: always runs, even if an exception occurs
try:
    a = 10
    b = 2
    print(a / b)
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
else:
    print("Division successful!")
finally:
    print("This runs always!")

5. Raising Exceptions

You can manually raise exceptions using raise.

age = -5

if age < 0:
    raise ValueError("Age cannot be negative!")

6. Debugging Tips

  • Print statements: Check the values of variables at different points.
  • Python debugger (pdb): Step through code line by line.
  • IDE debugging tools: PyCharm, VS Code allow breakpoints and watches.
import pdb

x = 5
y = 0

pdb.set_trace()  # Start debugging here
z = x / y
print(z)

7. Practice Exercises

  1. Write a program that asks the user for two numbers and divides them. Handle division by zero errors.
  2. Open a file that may not exist and handle FileNotFoundError.
  3. Raise an exception if a user's input string length is less than 5.
  4. Use pdb to debug a program that calculates the factorial of a number.


Lesson 14: Python File Handling and CSV/JSON | Coding Class Series

March 16, 2026 0



Lesson 14: Python File Handling and CSV/JSON | Coding Class Series

Introduction

Welcome to Lesson 14!
In this lesson, we will learn how to work with files in Python, including reading, writing, and updating text files, as well as working with CSV and JSON formats.
File handling is essential for storing data permanently and exchanging it between programs.


1. Opening and Closing Files

Use the open() function to open a file. Always close it after use.

# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()

# Open the file in read mode
file = open("example.txt", "r")
print(file.read())  # Hello, Python!
file.close()

2. Using with Statement

with automatically closes the file after usage.

with open("example.txt", "w") as f:
    f.write("Using with statement!")

with open("example.txt", "r") as f:
    print(f.read())  # Using with statement!

3. Reading Files

  • read(): reads the entire file
  • readline(): reads one line at a time
  • readlines(): reads all lines into a list
with open("example.txt", "r") as f:
    print(f.readline())
    print(f.readlines())

4. Writing and Appending Files

  • "w" mode: write (overwrites existing content)
  • "a" mode: append (adds new content)
with open("example.txt", "a") as f:
    f.write("\nAppending a new line!")

with open("example.txt", "r") as f:
    print(f.read())

5. Working with CSV Files

CSV (Comma Separated Values) files store tabular data.

import csv

# Writing to a CSV file
with open("students.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["Name", "Age", "Grade"])
    writer.writerow(["Alice", 14, "A"])
    writer.writerow(["Bob", 15, "B"])

# Reading from a CSV file
with open("students.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

6. Working with JSON Files

JSON is widely used for data exchange between applications.

import json

# Writing JSON to a file
data = {
    "name": "Alice",
    "age": 14,
    "subjects": ["Math", "English", "Science"]
}

with open("data.json", "w") as jsonfile:
    json.dump(data, jsonfile)

# Reading JSON from a file
with open("data.json", "r") as jsonfile:
    loaded_data = json.load(jsonfile)
    print(loaded_data["name"])  # Alice

7. Practice Exercises

  1. Create a text file notes.txt and write 5 of your favorite quotes.
  2. Create a CSV file inventory.csv for a shop with columns: Item, Quantity, Price. Read it and calculate total value.
  3. Create a JSON file with your friends' details (name, age, city) and load it back in Python.
  4. Read a text file and count the number of words in it.


Lesson 13: Python Classes and Object-Oriented Programming | Coding Class Series

March 16, 2026 0



Lesson 13: Python Classes and Object-Oriented Programming (OOP) | Coding Class Series

Introduction

Welcome to Lesson 13!
In this lesson, we will learn about Object-Oriented Programming (OOP) in Python, including classes, objects, methods, and inheritance.
OOP helps you structure your code in a way that models real-world objects and makes programming more organized and reusable.


1. What is a Class?

A class is a blueprint for creating objects. It defines attributes (data) and methods (functions).

# Define a class
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def bark(self):
        print(f"{self.name} says Woof!")

2. Creating Objects

An object is an instance of a class.

# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

print(dog1.name)  # Buddy
dog2.bark()       # Max says Woof!

3. The __init__ Method

  • __init__ is a constructor used to initialize objects.
  • self refers to the instance of the class.
class Cat:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def meow(self):
        print(f"{self.name}, the {self.color} cat, says Meow!")

4. Methods

Methods are functions inside classes that operate on objects.

class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.1416 * self.radius ** 2
    
    def perimeter(self):
        return 2 * 3.1416 * self.radius

c = Circle(5)
print(c.area())       # 78.54
print(c.perimeter())  # 31.416

5. Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

class Animal:
    def speak(self):
        print("Some sound")

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

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

d = Dog()
c = Cat()
d.speak()  # Woof Woof
c.speak()  # Meow Meow

6. Encapsulation

Encapsulation hides data inside a class using private attributes.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private variable
    
    def deposit(self, amount):
        self.__balance += amount
    
    def get_balance(self):
        return self.__balance

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

7. Polymorphism

Polymorphism allows objects of different classes to be used interchangeably.

class Bird:
    def speak(self):
        print("Tweet")

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

def make_speak(animal):
    animal.speak()

b = Bird()
d = Dog()
make_speak(b)  # Tweet
make_speak(d)  # Woof

8. Practice Exercises

  1. Create a class Student with attributes name, roll_no, marks. Write a method to calculate percentage.
  2. Create a class Vehicle and inherit it with Car and Bike. Add different methods to each.
  3. Implement encapsulation for a Library class where books is private.
  4. Write a program demonstrating polymorphism with two different classes.


Lesson 12: Python Exception Handling and Debugging | Coding Class Series

March 16, 2026 0



Lesson 12: Python Exception Handling and Debugging | Coding Class Series

Introduction

Welcome to Lesson 12!
In this lesson, we will learn how to handle errors in Python using exceptions and use debugging techniques to make our programs more robust and error-free. Exception handling ensures that your program does not crash unexpectedly.


1. What is an Exception?

An exception is an error that occurs during program execution.
Examples: ZeroDivisionError, FileNotFoundError, ValueError.

# Example: Division by zero
a = 10
b = 0
print(a / b)  # This will cause ZeroDivisionError

2. Using try and except

The try block contains code that might raise an exception.
The except block handles the exception gracefully.

try:
    a = 10
    b = 0
    result = a / b
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")

3. Handling Multiple Exceptions

You can catch multiple types of exceptions:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input, not a number!")

4. Using else and finally

  • else → Executes if no exception occurs
  • finally → Executes always, even if an exception occurs
try:
    file = open("example.txt", "r")
except FileNotFoundError:
    print("File not found!")
else:
    print(file.read())
finally:
    print("Execution finished.")

5. Raising Exceptions

You can raise your own exceptions using raise:

age = int(input("Enter your age: "))
if age < 18:
    raise ValueError("You must be 18 or older to proceed.")

6. Debugging Techniques

  1. Print statements – Track variable values and flow.
  2. Using IDE debugger – Step through code line by line.
  3. Logging module – Log errors for later analysis.
import logging

logging.basicConfig(filename="app.log", level=logging.ERROR)

try:
    x = 10 / 0
except ZeroDivisionError as e:
    logging.error("An error occurred: %s", e)

7. Practice Exercises

  1. Write a program that asks for two numbers and divides them. Handle ZeroDivisionError and ValueError.
  2. Open a file safely using try-except-else-finally.
  3. Raise a custom exception if a user enters a negative number.
  4. Implement logging to record all exceptions in your program.


Lesson 11: Python File Handling and I/O | Coding Class Series

March 16, 2026 0

 


Lesson 11: Python File Handling and I/O | Coding Class Series

Introduction

Welcome to Lesson 11!
In this lesson, we will learn how to work with files in Python, including reading, writing, and appending data. File handling is crucial for data storage, logs, and application input/output.


1. Opening a File

Use the built-in open() function to open a file:

# Open a file in read mode
file = open("example.txt", "r")
print(file.read())
file.close()

Modes of File:

  • "r" → Read (default)
  • "w" → Write (creates or overwrites)
  • "a" → Append (adds data at end)
  • "rb" / "wb" → Read/Write in binary mode

2. Reading Files

  • Read all content at once:
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • Read line by line:
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())
  • Read specific characters:
with open("example.txt", "r") as file:
    print(file.read(10))  # Reads first 10 characters

3. Writing to Files

  • Write new content (overwrites existing file):
with open("example.txt", "w") as file:
    file.write("Hello, Python File Handling!")
  • Append content to existing file:
with open("example.txt", "a") as file:
    file.write("\nThis is appended text.")

4. Using with Statement

The with statement automatically closes the file, even if an error occurs:

with open("example.txt", "r") as file:
    data = file.read()
    print(data)
# File is automatically closed here

5. Handling CSV Files

Python provides csv module to handle CSV files:

import csv

# Writing to a CSV
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "New York"])
    writer.writerow(["Bob", 30, "London"])

# Reading from a CSV
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

6. Practice Exercises

  1. Create a text file and write your favorite poem into it.
  2. Read the text file line by line and print lines containing the word "Python".
  3. Create a CSV file for your friends' names, age, and city, and read it using Python.
  4. Append new data to the existing CSV file and verify it.


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.