Python Assignment– 8
Modules & Packages
Basic Questions
- Use ‘import math’ and print the values of ‘math.pi’ and ‘math.sqrt(81)’; then use ‘from math import ceil’ and print ‘ceil(3.14)’.
- Use ‘import random’ to generate and print five integers in ‘[1, 10]’ with ‘random.randint(1, 10)’ on one line separated by spaces.
- Use ‘from datetime import date, timedelta’ to print today’s date and the date 30 days from today.
- Print the current working directory using ‘import os’ and ‘os.getcwd()’; then list entries in it using ‘os.listdir()’.
- Print the module search path by importing ‘sys’ and iterating over ‘sys.path’ line by line.
- Create a file ‘mymath.py’ defining a function ‘add(a, b)’ that returns ‘a + b’; in another script, ‘import mymath’ and print ‘mymath.add(2, 3)’.
- In the same directory, create ‘greeter.py’ with ‘def greet(name): return f”Hello, {name}”‘; then do ‘from greeter import greet’ and print ‘greet(“World”)’.
- Use ‘math.factorial’ to compute ’10!’ and print it; then compute the product of numbers ‘1..10’ manually and print both to verify they match.
- Use ‘random.seed(42)’ to generate a deterministic sequence: print three ‘random.random()’ values and then reseed and print the same three again to show equality.
- Use ‘datetime.datetime.now()’ to print a timestamp in ISO format and as ‘DD-MM-YYYY HH:MM’ using ‘strftime’.
- Create a directory ‘pkgdemo’ with ‘init.py’ (empty) and a module ‘tools.py’ defining ‘square(n)’; import with ‘from pkgdemo.tools import square’ and print ‘square(7)’.
- Show aliasing: ‘import math as m’ and print ‘m.sin(m.pi/2)’; also alias a function with ‘from math import log as ln’ and print ‘ln(10)’.
- Use ‘os.path.join’ to build a path ‘logs/app.txt’ in a cross-platform way and print the result.
- Read a line from standard input using ‘sys.stdin.readline()’ and write it back using ‘sys.stdout.write()’.
- Use ‘random.choice’ to pick a random element from a list of five names and print it.
- Use ‘from datetime import timedelta’ to compute and print the number of seconds in 3 days and 12 hours.
- Add a directory ‘extras’ to the module search path at runtime by appending to ‘sys.path’; then explain by printing ‘sys.path[-1]’ where it was appended.
- Create a custom module ‘textops.py’ with ‘upper_first(s)’ (capitalizes the first character without using ‘str.title’); import and test it.
- Demonstrate ‘if name == “main”:’ in ‘runner.py’ by printing ‘running as script’ only when executed directly, not when imported.
- Use ‘math.isclose’ to compare floating results of two computations with a tolerance and print whether they are close.
Intermediate Questions
- Build a small package ‘calcpkg’ with ‘init.py’ exposing ‘add’ and ‘mul’ from submodules ‘ops/add.py’ and ‘ops/mul.py’ via imports in ‘init.py’; demonstrate ‘from calcpkg import add, mul’.
- Write ‘path_report.py’ that prints the first directory in ‘sys.path’ containing ‘greeter.py’ by searching each path and checking ‘os.path.exists’; print the directory or ‘not found’.
- Create ‘randutil.py’ with a function ‘roll_dice(n, sides=6)’ using ‘random.randint’; import it and simulate 100 rolls, printing counts for each face.
- Create ‘timeutil.py’ with ‘def now_ist()’ returning current time for ‘Asia/Kolkata’ using ‘datetime’ and manual offset (no external tz libs); import and print it.
- Write ‘fsinfo.py’ that prints total files and directories in a given path using ‘os.walk’; import and run it on the current directory.
- Demonstrate relative imports inside a package: create package ‘shop’ with modules ‘prices.py’ and ‘cart.py’ where ‘cart.py’ does ‘from .prices import price_of’; call ‘price_of’ from ‘cart.py’ and print a computed total.
- Create ‘version.py’ exporting ‘version’ and ‘get_version()’; in main script import both and print the same value through each.
- Build ‘mathplus.py’ that re-exports selected names from ‘math’ (‘sqrt’, ‘pow’) and adds ‘cube(n)’; in another script do ‘from mathplus import *’ and demonstrate the three functions.
- Write a script that prints a random ‘YYYY-MM’ between 2000 and 2030 using ‘random.randint’ and ‘datetime.date’; ensure months are ’01..12′.
- Write ‘rotator.py’ with ‘rotate(seq, k)’ and package ‘seqtools’ that exposes it; import from ‘seqtools’ and rotate a list by 2.
- Create a virtual environment via command comments (‘python -m venv .venv’) and then show, in code, how to print ‘sys.prefix’ and ‘sys.executable’ to verify running inside a venv.
- Generate a ‘requirements-like’ snapshot by running ‘pip freeze’ (documented via a comment) and, in code, read a file ‘requirements.txt’ and print non-comment lines; treat this as the saved snapshot.
- Build ‘datetools.py’ that provides ‘days_between(d1, d2)’ parsing ‘YYYY-MM-DD’ strings using ‘datetime.datetime.strptime’; import and test with two dates.
- Use ‘os.environ’ to read an environment variable ‘APP_MODE’ with a default of ‘dev’ and print which mode is active; keep all logic in a module ‘config.py’ and import it.
- Create a package ‘statskit’ with modules ‘mean.py’ and ‘median.py’, plus ‘init.py’ that imports and exposes ‘mean’ and ‘median’; demonstrate ‘from statskit import mean, median’.
- Demonstrate circular import avoidance by moving shared constants into ‘common.py’; have ‘a.py’ and ‘b.py’ import from ‘common.py’ and then import ‘a’ and ‘b’ from a main script without errors.
- Write ‘cli.py’ that uses ‘sys.argv’ to accept a name and optional ‘–shout’ flag; if ‘–shout’ is present, print the name uppercased; otherwise print it as-is.
- Use ‘random.sample’ to select 3 unique values from ‘range(1, 50)’ and print them sorted.
- Print the start-of-month datetime for the next 6 months using ‘datetime.date.today()’, ‘replace(day=1)’, and month arithmetic with a helper function.
- Implement ‘tempfile_demo.py’ that creates a temporary file in a subdirectory using ‘os’ only (no ‘tempfile’ module): build a unique name with current ‘datetime’ and ‘random.randint’; write and then read back content.
Advanced Questions
- Create a package ‘pipeline’ with subpackages ‘steps’ and ‘utils’; put ‘init.py’ files in each; implement ‘steps/clean.py’ (‘clean(text)’) and ‘steps/tokenize.py’ (‘tokenize(text)’); in ‘pipeline/init.py’, expose a function ‘run(text)’ that calls both and returns tokens; import ‘run’ and demonstrate.
- Implement a module loader utility ‘reload_if_changed(mod, path)’ that checks ‘os.path.getmtime(path)’ and calls ‘importlib.reload(mod)’ if the timestamp increases; demonstrate by editing a file between calls (simulate by updating mtime in code).
- Build a namespaced package structure ‘acme.tools’ (nested directories with ‘init.py’); create ‘acme/tools/slug.py’ with ‘slugify(s)’; import using ‘from acme.tools.slug import slugify’ and print a slug.
- Write a script that safely modifies ‘sys.path’ to insert a local ‘plugins’ directory at index 0, imports a plugin module ‘plugins/upper.py’ with ‘transform(s)’, runs it, then restores ‘sys.path’ to its original state.
- Create a custom module ‘safejson.py’ that wraps ‘json.loads’ and rejects inputs larger than a given size and disallows control characters; import and demonstrate on valid and invalid inputs.
- Build a small package ‘geom’ with classes ‘Point’ and ‘Polygon’; in ‘geom/init.py’ export both; implement ‘Polygon.perimeter()’ using ‘math.hypot’; write a script that imports from ‘geom’ and computes a sample perimeter.
- Write ‘venv_report.py’ that prints whether the current interpreter is inside a virtual environment by comparing ‘sys.prefix’ and ‘sys.base_prefix’; also print ‘sys.path[0]’ as the script directory.
- Create a package ‘scheduler’ with ‘tasks.py’ and ‘runner.py’; ‘tasks.py’ defines functions that print timestamps using ‘datetime.datetime.now()’; ‘runner.py’ imports from ‘tasks’ and schedules three calls using ‘random.uniform’ delays simulated with a loop and ‘time.sleep’ (allowed from core library), then prints ‘done’.
- Implement a best-practices linter script ‘modcheck.py’ that scans ‘.py’ files in the current directory and flags: missing module docstring, wildcard imports (‘from x import *’), and unused imports (naively, import lines not referenced later); print a summary report.
- Compose a short ‘MODULAR_CODE_GUIDE.md’ string in a Python script and write it to disk; include bullet points: ‘keep modules small’, ‘single responsibility’, ‘explicit exports in all’, ‘avoid circular imports’, ‘configure via env vars not code edits’, ‘document public APIs’, ‘pin dependencies via requirements’, ‘use venv per project’; print path to the generated file.