This lesson makes your Python programs more practical. You’ll learn how to import and create modules, explore the Standard Library, build friendly command-line interfaces with argparse, and read configuration from environment variables. (Optional) We’ll also touch on structural pattern matching (Py 3.10+) and a quick Date & Time primer.
1) Imports & Your Own Modules
Use import to bring code from other files or libraries into your script.
You can import from three places:
- Built-in (Standard Library) — ships with Python (no install needed).
- Third-party packages — installed via
pipinto your environment. - Your own modules/packages — your project’s
.pyfiles or package folders.
a) Import styles (quick reference)
import math # import whole module
import math as m # Module alias (shorten long names)
from math import sqrt # Import a single name into your local namespace
from math import sqrt as rt # Import a single name with an alias
Here, “name” means the identifier that gets created in your current file’s namespace.
from math import sqrt imports the object math.sqrt and binds it to the name sqrt in your file.
After that, you call sqrt(16) directly (no math. prefix).
If you alias it, the name changes locally: from math import sqrt as rt → now the name is rt.
Caution: rebinding the name (don’t do this)
from math import sqrt
sqrt = 42 # now "sqrt" no longer refers to the function!
# sqrt(9) would fail here because it's an int now
from module import *) to keep namespaces clean and autocomplete helpful.
b) Built-in (Standard Library) imports
import math
from pathlib import Path
print(math.pi) # 3.14159...
# Rounding helpers
print(math.floor(3.7), math.ceil(3.1), math.trunc(-3.9)) # 3 4 -3
# Roots & powers
print(math.sqrt(49)) # 7.0
print(math.pow(2, 3)) # 8.0 (same as 2**3)
# Home and current working directory
print(Path.home(), Path.cwd())
# Path object
p = Path("data") / "file.txt"
# Check if path exists
print(p.exists()) # True if 'data/file.txt' exists, False if it doesn't
# Check if it's a file
if p.is_file():
print("It's a file.")
elif p.is_dir():
print("It's a directory.")
else:
print("Path doesn't exist or is neither a file nor directory.")
c) Third-party packages (via pip or any other package manager)
Install once, then import like any other module. Use a virtual environment (python -m venv .venv) to isolate dependencies. Later, in Packaging & Distribution , we’ll learn how to set up and manage virtual environments to keep your projects organized.
# In terminal run pip install {package name} command to install third party packages
pip install numpy
pip install pandas
pip list # view installed packages and versions
Once installed, you can import these packages into your code like any other module. For example:
import numpy as np
import pandas as pd
# NumPy: quick numeric operations
arr = np.array([1, 2, 3, 4, 5])
print(arr.mean()) # 3.0
# pandas: data analysis on tabular data
df = pd.DataFrame({
"city": ["Lahore", "Karachi", "Lahore", "Quetta"],
"sales": [120, 200, 180, 90]
})
print(df.groupby("city")["sales"].mean())
b) Creating your own module
Create a file my_utils.py:
# my_utils.py
def title_case(s: str) -> str:
return " ".join(w.capitalize() for w in s.split())
Use it from another file:
# main.py
import my_utils
print(my_utils.title_case("hello from python")) # Hello From Python
c) Module search path & script entry point
When you import a module in Python, Python needs to know where to look for the module file. The sys.path list contains the directories Python will search for modules when you use import. You can view this list using print(sys.path).
import sys
# This prints a list of directories where Python looks for modules
print(sys.path)
Python looks in the directories listed in sys.path in the order they appear. This includes locations such as:
- The directory of the current script
- Standard library paths (e.g.,
/usr/lib/python3.x) - Third-party package directories installed via
pip
If a module is not found in these locations, you’ll get an ImportError.
if __name__ == “__main__”:
The if __name__ == "__main__": block is used to ensure that certain code runs only when the script is executed directly (not when it’s imported as a module). This is useful for testing or for scripts that can be run standalone.
if __name__ == "__main__":
# code here runs only when the file is executed directly
print("Running as a script")
When Python runs a script, it sets the special variable __name__ to "__main__" for that script. If the script is imported as a module in another file, __name__ will be set to the module name instead, and the code under if __name__ == "__main__": will not run.
2) Standard Library Highlights (Built-ins You’ll Use a Lot)
Python ships with batteries included. Here are a few modules you’ll reach for often. For the full list of built-in packages, you can check the Python Standard Library reference
a) os / pathlib for files & paths
from pathlib import Path
p = Path("data") / "users.csv"
print(p.exists(), p.suffix) # True/False, ".csv"
b) json for structured data
import json
payload = {"name": "Ammar", "active": True}
text = json.dumps(payload) # to JSON string
back = json.loads(text) # to Python dict
c) csv for comma-separated files
import csv
with open("users.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
d) random & statistics
import random, statistics as stats
nums = [random.randint(1, 10) for _ in range(5)]
print(nums, stats.mean(nums))
e) itertools & collections (power tools)
from itertools import combinations
from collections import Counter
print(list(combinations([1,2,3], 2))) # [(1,2), (1,3), (2,3)]
print(Counter("bananas")) # counts per letter
3) Command-Line Arguments with argparse
Make your scripts configurable and user-friendly from the terminal.
# greet.py
import argparse
parser = argparse.ArgumentParser(
description="Greet someone with an optional style."
)
parser.add_argument("name", help="Person to greet") # positional
parser.add_argument("-t", "--times", type=int, default=1, help="Repeat count")
parser.add_argument("-u", "--uppercase", action="store_true", help="Uppercase output")
args = parser.parse_args()
msg = f"Hello, {args.name}!"
if args.uppercase:
msg = msg.upper()
for _ in range(args.times):
print(msg)
Example use: python greet.py Ali -t 3 --uppercase
Tips:
- Use clear
help=text; it shows up in-h/--help. - Use
choices=["low","med","high"]to restrict valid values. - Prefer explicit types (e.g.,
type=int) for safer parsing.
4) Environment Variables
Store configuration outside your code (API keys, modes, toggles). Read them via os.getenv.
import os
API_URL = os.getenv("API_URL", "https://api.example.com") # default fallback
DEBUG = os.getenv("DEBUG", "0") == "1" # simple boolean flag
TIMEOUT = int(os.getenv("TIMEOUT", "30")) # cast to int
print(API_URL, DEBUG, TIMEOUT)
Env vars + argparse (nice combo)
import os, argparse
parser = argparse.ArgumentParser()
parser.add_argument("--timeout", type=int, default=int(os.getenv("TIMEOUT", "30")))
args = parser.parse_args()
print("Timeout:", args.timeout)
5) (Optional) Structural Pattern Matching — match / case (Python 3.10+)
Cleaner branching than long if/elif chains by matching shapes and values.
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Other")
event = {"type": "click", "x": 120, "y": 40}
match event:
case {"type": "click", "x": x, "y": y} if x >= 0 and y >= 0:
print(f"Click at {x},{y}")
case {"type": "keydown", "key": key}:
print(f"Key: {key}")
case _:
print("Unknown")
Notes: Requires Python 3.10+. Use _ as a wildcard. Great for events, API payloads, and parsers.
6) (Optional) Date & Time Quick Start
You planned to place Date & Time here. Here’s a compact starter you can expand later.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo # Python 3.9+
now_utc = datetime.now(timezone.utc)
now_pk = now_utc.astimezone(ZoneInfo("Asia/Karachi"))
print(now_utc.isoformat())
print(now_pk.strftime("%Y-%m-%d %H:%M"))
from datetime import datetime
# Parse string to datetime
dt = datetime.strptime("2025-09-22 14:30", "%Y-%m-%d %H:%M")
# Format datetime to string
print(dt.strftime("%b %d, %Y at %I:%M %p")) # Sep 22, 2025 at 02:30 PM
Key Takeaways
- Import modules with clear, explicit imports; organize reusable code in your own modules.
- Python’s Standard Library covers common tasks—files (
pathlib), data (json,csv), math/probability (random,statistics), iteration & counting (itertools,collections). argparsemakes robust command-line tools with helpful--helptext.- Use environment variables for configuration; combine them with
argparsefor flexible defaults. - (Optional) Structural Pattern Matching (
match/case) simplifies complex branching (Py 3.10+). - (Optional) Date & Time: use
datetimeandzoneinfo, store UTC, format for users.
Continue learning with Debugging, Testing & Best Practices to write clean, reliable, and maintainable Python.
Leave a comment
Your email address will not be published. Required fields are marked *
