←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Revision

Python Programming · Unit 3 Revision

Quick summary and key points for Unit 3

Modular Programming, Types of Modules & User-Defined Modules

Overview: Put a grading function in grades.py and import it from the marks-entry script.

What is Modular Programming & Why is it Important?

  • Modular Programming is a software design technique that divides a large, complex program into smaller, independent, and reusable files…
  • Importance / Advantages of Modular Programming: Code Reusability: Write a module once and import it into multiple projects without rewriting code.
  • Simplicity & Readability: Smaller files (100–200 lines) are much easier to understand than one giant 5,000-line file.
  • Easy Debugging & Maintenance: If an error occurs in billing, you only need to check billing.py.
  • Team Collaboration: Different developers can work on different modules simultaneously without conflict.
  • Avoids Naming Collisions (Separate Namespaces): Two modules (module1.py and module2.py) can both have a function named calculate() without clashing.

View diagram · Modular Programming Architecture in Python

What is a Module in Python?

  • A Module in Python is simply any file with a .py extension that contains executable Python code — such as **functions, classes, and…

Types of Modules in Python

  • Python modules are divided into two main categories:
  • Definition: Modules that come pre-installed with Python’s Standard Library
  • Creation: Written by Python core developers (in C or Python)
  • Installation: Ready to use immediately with import
  • Examples: math, os, sys, datetime, random, re, json

Creating and Importing a User-Defined Module

  • Let’s create our own module and use it inside another Python program!
  • Step 1: Create the Module File (mycalc.py): Save the following code in a file named mycalc.py:
  • Step 2: Import and Use mycalc in main.py: In the same folder, create main.py.
  • Way 1: Standard import module_name: Imports the whole module.
  • Way 2: Importing with an Alias (import module as alias): Gives a short nickname to the module name:
  • Way 3: Importing Specific Items (from module import item1, item2): Imports only selected functions/variables directly, so you don’t need the module prefix:
  • Way 4: Importing Everything (from module import *): Imports all functions and variables from the module (generally not recommended for large programs as it can cause name clashes):

Useful Built-in Module Inspection Tools

  • The dir() Function: Lists all functions, classes, and variables defined inside a module.
  • The __name__ == "__main__" Idiom:
  • When a Python file is run directly, its built-in __name__ variable is set to "__main__".
  • When the file is imported as a module into another file, __name__ is set to the module’s filename ("mycalc").
  • Putting test code inside if __name__ == "__main__": ensures the test code runs only when the file is executed directly, and not when…

Standard Modules in Python: math, datetime, and os

Overview: Use datetime to work out how many days remain until an exam, math for a square root, and os for operating-system services.

The math Module

  • The math module provides fast mathematical functions and constants.
  • Important Constants in math: math.pi → Value of Pi (3.141592653589793)
  • math.e → Euler’s number (2.718281828459045)
  • math.sqrt(x): Returns the square root of x as a float
  • math.pow(x, y): Returns x raised to power y as a float
  • math.ceil(x): Rounds a float UP to the nearest integer
  • math.floor(x): Rounds a float DOWN to the nearest integer
  • math.factorial(x): Returns the factorial of x (x!)

The datetime Module

  • The datetime module provides classes for manipulating dates and times in both simple and complex ways.
  • Main Classes Inside datetime Module: datetime.date Represents a calendar date (year, month, day).
  • datetime.time Represents time of day (hour, minute, second, microsecond).
  • datetime.datetime Combines both date and time into a single object.
  • datetime.timedelta Represents the difference (duration) between two dates or times (used for adding/subtracting days).
  • Formatting Dates with strftime() (String Format Time): The strftime() method converts a datetime object into a readable formatted string:
  • %d → Day of month (01 to 31)
  • %m → Month number (01 to 12)

The os Module (Operating System Interface)

  • The os module allows your Python program to interact directly with the underlying Operating System (Windows, Linux, macOS) to manage…
  • os.name: Returns the OS kernel name ('nt' for Windows, 'posix' for Linux/Mac)
  • os.getcwd(): Returns the Current Working Directory (folder path)
  • os.chdir(path): Changes the current working directory to path
  • os.listdir(path): Returns a list of all files and folders inside path
  • os.mkdir("folder"): Creates a single new folder (directory)
  • os.makedirs("a/b/c"): Creates nested folders recursively

Python Packages: Pre-defined, User-defined & Package vs Folder

Overview: A package groups related modules under a shared import name, such as college.results.

What is a Package in Python?

  • A Package is a directory (folder) that contains multiple related Python modules (.py files) along with a special initialization file…
    • Function: A single chapter or recipe.
    • Module (.py file): A book containing related chapters (functions & classes).
    • Package (Directory with __init__.py): A bookshelf/library section that organizes multiple related books (modules).
  • Role of __init__.py: The __init__.py file tells Python that the directory should be treated as an importable Package.
  • It can be completely empty, or it can contain package initialization code and specify which modules to expose when someone imports the…

View diagram · Organizing a Python Project into a Package (college_pkg)

Types of Packages in Python

  • Just like modules, Python packages are classified into two types:
  • A. Pre-Defined (Built-in & Third-Party) Packages: Packages created by the Python community or core developers that provide ready-made functionality:
  • Standard Library Packages (Pre-installed with Python):
  • tkinter (GUI development)
  • urllib (Working with URLs and HTTP requests)
  • xml and json (Data parsing)
  • unittest (Automated software testing)
  • Third-Party Packages (Installed via pip install <package> from PyPI):

Step-by-Step: Creating and Using a User-Defined Package

  • Let’s create the college_pkg package shown above and use it inside main.py.
  • Step 1: Create folder college_pkg and add __init__.py: Inside college_pkg/__init__.py:
  • Step 2: Create modules inside college_pkg/: Inside college_pkg/students.py:

Package vs Folder (Directory)

  • Students often ask: “Is every folder on my computer a Python package?” No! Here is the exact difference:
  • Definition: A namespace directory containing Python .py modules and an __init__.py file
  • Role of __init__.py: Contains __init__.py to initialize package-level state
  • Purpose: Organizes Python modules so they can be imported using dot notation (import pkg.mod)
  • Importability: Can be imported in Python scripts using import

Quick Comparison: Module vs Package

  • What is it?: A single Python file with a .py extension
  • Scope: Groups related functions, classes, and variables
  • Example: math.py, random.py, students.py

File and Directory Handling in Python

Overview: Opening a file with mode w truncates an existing file.

Opening a File & File Access Modes

  • In Python, we use the built-in open(filename, mode) function to open a file.
  • 'r': Read (Default)
  • 'w': Write
  • 'a': Append
  • 'x': Exclusive Create
  • 'r+': Read + Write
  • 'w+': Write + Read

Writing Data to a File (write() and writelines())

  • f.write(string): Writes a single string to the file.
  • f.writelines(list_of_strings): Writes multiple strings from a list to the file.

Reading Data from a File (read(), readline(), readlines())

  • f.read(): Reads the entire file and returns it as a single string (f.read(n) reads n characters)
  • f.readline(): Reads only one single line from the file at a time
  • f.readlines(): Reads all lines and returns them as a List of strings
  • Best Practice: The with open(...) Statement (Context Manager): When you open a file using the with keyword, Python automatically closes the file as soon as the block finishes (even…

Moving the File Cursor: tell() and seek()

  • When reading or writing a file, Python maintains an internal File Pointer (Cursor) that tracks your current byte position.
  • f.tell(): Returns the current position (in bytes) of the file pointer from the beginning of the file.
  • f.seek(offset): Moves the file pointer to a specific byte position (f.seek(0) resets the cursor back to the very beginning of the…

Directory (Folder) Handling in Python

  • Python uses the os and shutil modules to create, inspect, rename, and delete directories (folders):