Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 07 / Stage 1

Modules and environment

Goal: Split code into modules and packages, use the standard library, and manage project packages with a virtual environment and pip. Time: ~1 hour

What you will learn

  • What a module is
  • Import styles: import x, from x import y, as alias (and why to avoid import *)
  • Writing your own module and importing it
  • Packages and __init__.py
  • if __name__ == "__main__":
  • How Python finds modules (sys.path)
  • Virtual environments (venv)
  • pip and requirements.txt (and a quick look at uv)
  • Standard library tour: math, random, secrets, os, sys, datetime, time

Topics in this part

Practice

Python workbench — write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Use only the standard library. Put your logic in functions and call them under if __name__ == "__main__":.


Exercise 1: Party planner

Scenario: You are organising a birthday party and need to plan tables and cake.

What to do:

  • Use the math module.
  • Write tables_needed(guests, seats_per_table). It must round up.
  • Write cake_area(diameter_cm) for a round cake (area = π × r²).
  • Print the tables, the cake area and the cake area per guest for 45 guests, 6 seats per table and a 30 cm cake.

Sample output:

Guests: 45
Tables (6 seats each): 8
Cake area (30 cm wide): 706.9 sq cm
Slice per guest: 15.7 sq cm

💡 Hint: math.ceil() rounds up and math.pi gives π.


Show the solution to Exercise 1
"""Exercise 1: Party planner (math module).

Run: python ex01.py   (macOS/Linux: python3 ex01.py)
"""

import math


def tables_needed(guests: int, seats_per_table: int) -> int:
    # ceil rounds UP: 2.25 tables -> 3 tables
    return math.ceil(guests / seats_per_table)


def cake_area(diameter_cm: float) -> float:
    radius = diameter_cm / 2
    return math.pi * radius ** 2


if __name__ == "__main__":
    guests = 45
    print(f"Guests: {guests}")
    print(f"Tables (6 seats each): {tables_needed(guests, 6)}")
    print(f"Cake area (30 cm wide): {cake_area(30):.1f} sq cm")
    print(f"Slice per guest: {cake_area(30) / guests:.1f} sq cm")

Exercise 2: Ludo dice roller

Scenario: Your family plays Ludo, but the dice is lost.

What to do:

  • Use from random import ... or import random.
  • Write roll_dice(times) that returns a list of rolls (1 to 6).
  • Roll 10 times. Print the rolls, how many sixes, and the highest roll.
  • Pick a random first player from ["Asha", "Ravi", "Meena", "Kiran"].
  • Your numbers will differ each run. To get exactly the sample output below, call random.seed(7) once at the start.

Sample output:

Rolls: [3, 2, 4, 6, 1, 1, 5, 1, 3, 5]
Number of sixes: 1
Highest roll: 6
First player: Asha

💡 Hint: random.randint(1, 6), list.count(6), random.choice(names). Call random.seed(7) first if you want the same numbers every run.


Show the solution to Exercise 2
"""Exercise 2: Ludo dice roller (random module).

Run: python ex02.py   (macOS/Linux: python3 ex02.py)
"""

import random


def roll_dice(times: int) -> list[int]:
    return [random.randint(1, 6) for _ in range(times)]


if __name__ == "__main__":
    random.seed(7)  # same "random" numbers every run, handy for testing
    rolls = roll_dice(10)
    print("Rolls:", rolls)
    print("Number of sixes:", rolls.count(6))
    print("Highest roll:", max(rolls))
    print("First player:", random.choice(["Asha", "Ravi", "Meena", "Kiran"]))

Exercise 3: Your own temperature module

Scenario: A weather app needs reusable temperature helpers.

What to do:

  • Create a module with c_to_f(c), f_to_c(f) and describe(c) ("Very hot" ≥ 40, "Warm" ≥ 25, "Pleasant" ≥ 10, else "Cold").
  • Add a self-test under if __name__ == "__main__":.
  • Bonus: save it as temperature.py, then create weather.py in the same folder that does import temperature. Check that the self-test does not run on import.

Sample output:

Delhi: 44°C = 111.2°F (Very hot)
Bengaluru: 26°C = 78.8°F (Warm)
Shimla: 4°C = 39.2°F (Cold)
98.6°F = 37.0°C
__name__ is '__main__'

💡 Hint: °F = °C × 9 / 5 + 32.


Show the solution to Exercise 3
"""
Exercise 3: Your own module (temperature converter).

In a real project you would save this as `temperature.py` and write
`import temperature` in another file. The block at the bottom runs only
when this file is run directly, not when it is imported.

Run: python ex03.py   (macOS/Linux: python3 ex03.py)
"""


def c_to_f(celsius: float) -> float:
    return celsius * 9 / 5 + 32


def f_to_c(fahrenheit: float) -> float:
    return (fahrenheit - 32) * 5 / 9


def describe(celsius: float) -> str:
    if celsius >= 40:
        return "Very hot"
    if celsius >= 25:
        return "Warm"
    if celsius >= 10:
        return "Pleasant"
    return "Cold"


if __name__ == "__main__":
    # Self-test
    for city, temp in {"Delhi": 44, "Bengaluru": 26, "Shimla": 4}.items():
        print(f"{city}: {temp}°C = {c_to_f(temp):.1f}°F ({describe(temp)})")
    print(f"98.6°F = {f_to_c(98.6):.1f}°C")
    print("__name__ is", repr(__name__))

Exercise 4: Bank OTP with 3 attempts

Scenario: A payment app sends a 6-digit OTP. The user gets 3 tries.

What to do:

  • Use secrets (not random) to make the OTP. It can start with 0, so keep it as a string.
  • Write check_attempts(otp, attempts, max_tries=3). attempts is a list of what the user typed (use a fixed list instead of input()).
  • Print a message for each wrong try. Return the final message: "Attempt N: correct. Payment approved ✅" or "Too many wrong attempts. Card blocked 🔒".
  • Make one OTP, print it, then call check_attempts twice, with a blank line between the two runs:
    • Run 1: attempts = ["111111", otp] (one wrong try, then the right OTP)
    • Run 2: attempts = ["111111", "222222", "333333"] (three wrong tries)
  • Your OTP will differ each run.

Sample output:

OTP sent to your phone: 360773
Attempt 1: wrong OTP. 2 left.
Attempt 2: correct. Payment approved ✅

Attempt 1: wrong OTP. 2 left.
Attempt 2: wrong OTP. 1 left.
Attempt 3: wrong OTP. 0 left.
Too many wrong attempts. Card blocked 🔒

💡 Hint: secrets.choice(string.digits) in a loop, and secrets.compare_digest(a, b) to compare.


Show the solution to Exercise 4
"""Exercise 4: Bank OTP with 3 attempts (secrets module).

Run: python ex04.py   (macOS/Linux: python3 ex04.py)
"""

import secrets
import string


def generate_otp(length: int = 6) -> str:
    return "".join([secrets.choice(string.digits) for _ in range(length)])


def check_attempts(otp: str, attempts: list[str], max_tries: int = 3) -> str:
    for number, typed in enumerate(attempts[:max_tries], start=1):
        if secrets.compare_digest(otp, typed):
            return f"Attempt {number}: correct. Payment approved ✅"
        print(f"Attempt {number}: wrong OTP. {max_tries - number} left.")
    return "Too many wrong attempts. Card blocked 🔒"


if __name__ == "__main__":
    otp = generate_otp()
    print(f"OTP sent to your phone: {otp}")

    # Demo with fixed "typed" values instead of input().
    # (If the random OTP happens to be "111111", run 1 is correct on attempt 1.)
    # Run 1: one wrong try, then the right OTP
    print(check_attempts(otp, ["111111", otp]))
    print()
    # Run 2: three wrong tries
    print(check_attempts(otp, ["111111", "222222", "333333"]))

Exercise 5: Birthday countdown

Scenario: Show a user their age and how many days until their next birthday.

What to do:

  • Use datetime.date.
  • Write next_birthday(birth, today) and age_on(birth, today).
  • If this year's birthday has passed, the next one is next year.
  • Someone born on 29 February has no birthday in a non-leap year. In those years, use 1 March.
  • Use a fixed today = date(2025, 6, 1) so your output is repeatable. Show two people: born date(2000, 8, 15) and born date(2004, 2, 29).

Sample output:

Today: 01 Jun 2025

Born: 15 Aug 2000
Age: 24
Next birthday: 15 August 2025 (Friday)
Days to go: 75

Born: 29 Feb 2004
Age: 21
Next birthday: 01 March 2026 (Sunday)
Days to go: 273

💡 Hint: birth.replace(year=today.year) gives this year's birthday; wrap it in try / except ValueError and use date(year, 3, 1) when it fails (29 Feb in a non-leap year). Subtracting two dates gives a timedelta; use .days. Age = today.year - birth.year, minus 1 if this year's birthday has not happened yet. Check that with a tuple comparison: (today.month, today.day) >= (birth.month, birth.day) (tuples compare the month first, then the day).


Show the solution to Exercise 5
"""Exercise 5: Birthday countdown (datetime module).

Run: python ex05.py   (macOS/Linux: python3 ex05.py)
"""

from datetime import date


def birthday_in(birth: date, year: int) -> date:
    """The birthday in a given year. 29 Feb falls back to 1 March in non-leap years."""
    try:
        return birth.replace(year=year)
    except ValueError:              # 29 Feb does not exist in this year
        return date(year, 3, 1)


def next_birthday(birth: date, today: date) -> date:
    this_year = birthday_in(birth, today.year)
    if this_year < today:           # already passed this year -> next year
        return birthday_in(birth, today.year + 1)
    return this_year


def age_on(birth: date, today: date) -> int:
    # Tuples compare item by item: first the month, then the day (Part 4).
    had_birthday = (today.month, today.day) >= (birth.month, birth.day)
    # Year difference, minus 1 if this year's birthday has not happened yet
    return today.year - birth.year - (0 if had_birthday else 1)


def show(birth: date, today: date) -> None:
    nb = next_birthday(birth, today)
    print(f"Born: {birth:%d %b %Y}")
    print(f"Age: {age_on(birth, today)}")
    print(f"Next birthday: {nb:%d %B %Y} ({nb:%A})")
    print(f"Days to go: {(nb - today).days}")


if __name__ == "__main__":
    today = date(2025, 6, 1)  # fixed so output stays the same
    print(f"Today: {today:%d %b %Y}")
    print()
    show(date(2000, 8, 15), today)
    print()
    show(date(2004, 2, 29), today)  # leap-day birthday

Exercise 6: Medicine reminder

Scenario: A doctor says "one tablet every 8 hours for 2 days". Make a schedule.

What to do:

  • Parse the first dose time from text "10-03-2025 08:00" with strptime.
  • Write dose_times(first, every_hours, days) that returns a list of datetimes.
  • Print each dose with strftime in 12-hour format, for "every 8 hours for 2 days".

Sample output:

Paracetamol every 8 hours, 6 doses:
  Dose 1: Mon 10 Mar, 08:00 AM
  Dose 2: Mon 10 Mar, 04:00 PM
  Dose 3: Tue 11 Mar, 12:00 AM
  Dose 4: Tue 11 Mar, 08:00 AM
  Dose 5: Tue 11 Mar, 04:00 PM
  Dose 6: Wed 12 Mar, 12:00 AM

💡 Hint: timedelta(hours=8). Format codes: %a weekday, %I 12-hour, %p AM/PM.


Show the solution to Exercise 6
"""Exercise 6: Medicine reminder (datetime + timedelta).

Run: python ex06.py   (macOS/Linux: python3 ex06.py)
"""

from datetime import datetime, timedelta


def dose_times(first: datetime, every_hours: int, days: int) -> list[datetime]:
    times = []
    current = first
    end = first + timedelta(days=days)
    while current < end:
        times.append(current)
        current += timedelta(hours=every_hours)
    return times


if __name__ == "__main__":
    first = datetime.strptime("10-03-2025 08:00", "%d-%m-%Y %H:%M")
    doses = dose_times(first, every_hours=8, days=2)
    print(f"Paracetamol every 8 hours, {len(doses)} doses:")
    for number, when in enumerate(doses, start=1):
        print(f"  Dose {number}: {when:%a %d %b, %I:%M %p}")

Exercise 7: Password generator and strength checker

Scenario: A college portal needs strong passwords for new students.

What to do:

  • Write generate_password(length=12) using secrets and string. It must contain at least one lowercase letter, one uppercase letter, one digit and one symbol from !@#$%&*?. If length < 8, raise ValueError("Password must be at least 8 characters").
  • Write strength(password) that returns "Weak", "Medium" or "Strong". Give 1 point each for: length ≥ 8, length ≥ 12, has lower, has upper, has digit, has symbol. 6 = Strong, 4–5 = Medium, else Weak.
  • Test with the fixed passwords "rahul123", "Rahul@2025" and "xK9!mP2#qL7&", then one password made with generate_password(14) (14 characters), then call generate_password(5) and print the error. Your generated password will differ each run.

Sample output:

rahul123       -> Weak
Rahul@2025     -> Medium
xK9!mP2#qL7&   -> Strong

Generated: eQ9&vmnbI13Bbg -> Strong
Error: Password must be at least 8 characters

💡 Hint: pick one character from each group first, fill the rest, then shuffle with secrets.SystemRandom().shuffle(chars). For the checks, string methods help: c.islower(), c.isupper() and c.isdigit() return True or False for one character c. any([...]) is True if at least one item in the list is True, so any([c.isdigit() for c in password]) means "has at least one digit". True counts as 1 when you add it to a number: score += len(password) >= 8. Catch the error with except ValueError as err: and print "Error:", err.

Show the solution to Exercise 7
"""Exercise 7: Password generator and strength checker (secrets + string).

Run: python ex07.py   (macOS/Linux: python3 ex07.py)
"""

import secrets
import string

SYMBOLS = "!@#$%&*?"


def generate_password(length: int = 12) -> str:
    if length < 8:
        raise ValueError("Password must be at least 8 characters")
    pools = [string.ascii_lowercase, string.ascii_uppercase, string.digits, SYMBOLS]
    chars = [secrets.choice(pool) for pool in pools]          # one from each
    everything = "".join(pools)
    chars += [secrets.choice(everything) for _ in range(length - len(chars))]
    secrets.SystemRandom().shuffle(chars)
    return "".join(chars)


def strength(password: str) -> str:
    """1 point per rule passed. any(list) is True if at least one item is True."""
    score = 0
    score += len(password) >= 8
    score += len(password) >= 12
    score += any([c.islower() for c in password])
    score += any([c.isupper() for c in password])
    score += any([c.isdigit() for c in password])
    score += any([c in SYMBOLS for c in password])
    if score >= 6:
        return "Strong"
    if score >= 4:
        return "Medium"
    return "Weak"


if __name__ == "__main__":
    for pwd in ["rahul123", "Rahul@2025", "xK9!mP2#qL7&"]:
        print(f"{pwd:<14} -> {strength(pwd)}")

    new = generate_password(14)
    print(f"\nGenerated: {new} -> {strength(new)}")

    try:
        generate_password(5)
    except ValueError as err:
        print("Error:", err)

Common mistakes

Mistake Why it is wrong Fix
Naming your file random.py or math.py Your file hides the real module, so random.randint is "not found" Use a unique name like dice_game.py; delete any __pycache__
from module import * You cannot tell where names came from; names get overwritten import module or import the names you need
Writing import shop_utils.py Import uses the module name, not the file name import shop_utils
Demo code at the top level of a module It runs every time someone imports the module Put it under if __name__ == "__main__":
Using random for OTPs or passwords random is predictable Use secrets
pip install without an active venv Packages go into the global Python and clash between projects Create and activate .venv first
Committing the .venv folder It is big and machine-specific Add .venv/ to .gitignore, share requirements.txt
Mixing up strftime and strptime One formats, one parses f = format (date → text), p = parse (text → date)

Quick recap

  • A module is a .py file. A package is a folder of modules with __init__.py.
  • Prefer import x or from x import y. Avoid import *.
  • if __name__ == "__main__": runs code only when the file is run directly.
  • Python looks for modules in sys.path, starting with the script's folder.
  • One project = one virtual environment (python -m venv .venv).
  • pip freeze > requirements.txt saves versions; pip install -r requirements.txt restores them.
  • random for games, secrets for security.
  • datetime + timedelta handle dates; strftime formats, strptime parses.

Checklist

  • I can import a module in three ways and explain when to use each.
  • I can write my own module and import it from another file.
  • I can make a small package with __init__.py.
  • I can explain what if __name__ == "__main__": does.
  • I can create, activate and deactivate a virtual environment on my system.
  • I can install packages with pip and use requirements.txt.
  • I can generate a secure OTP with secrets.
  • I can find the number of days between two dates.

Search the guide