Practice: Creating Custom Modules

« Read the chapter

Q1. Create and use a square module

BeginnerCoding

Write a module file named mathx.py containing a function square(n). Import it and print square(7).

Goal: Create a module

Q2. Import with an alias

BeginnerCoding

Create a module named shapes.py with a function area(w, h) that returns w * h. Import it as sh and print the area of a 3 by 4 rectangle.

Goal: Use import as

Q3. From-import two names

BeginnerCoding

Create a module consts.py with the variables WIDTH = 80 and HEIGHT = 24. Use from-import to bring in both names and print their sum.

Goal: Use from-import

Q4. Print the module name

BeginnerCoding

Create a module named info.py and print its __name__ attribute after importing it.

Goal: Understand __name__

Q5. Guarded demo code

IntermediateCoding

Create a module demo.py with a function hi() returning 'hi' and a guarded block that prints 'script'. Import it, call hi() and print the result. The guarded text must NOT appear.

Goal: Use the __name__ guard

Q6. Module-level counter

IntermediateCoding

Create a module state.py with a variable total = 0 and a function add(n) that adds n to total using global. Call add(5) and add(7) through the module and print state.total.

Goal: Share module state

Q7. Name of a running script

BeginnerOutput

What does this print?

Code
print(__name__)

Goal: Understand __name__

Q8. Import runs once

IntermediateOutput

What does this print?

Code
import sys
sys.path.insert(0, ".")
from pathlib import Path
Path("once.py").write_text("print('loaded')\nvalue = 1\n")
import once
import once as again
print(again.value)
print(once is again)

Goal: Understand import caching

Q9. Is the name exported?

IntermediateOutput

What does this print?

Code
import sys
sys.path.insert(0, ".")
from pathlib import Path
Path("vis.py").write_text("__all__ = ['shown']\nshown = 1\nhidden = 2\n")
from vis import *
print('shown' in globals())
print('hidden' in globals())

Goal: Use __all__

Q10. Module in sys.modules

BeginnerOutput

What does this print?

Code
import sys
sys.path.insert(0, ".")
from pathlib import Path
import sys
Path("fresh.py").write_text("a = 1\n")
print('fresh' in sys.modules)
import fresh
print('fresh' in sys.modules)

Goal: Use sys.modules

Q11. Alias name only

IntermediateOutput

What does this print?

Code
import sys
sys.path.insert(0, ".")
from pathlib import Path
Path("m.py").write_text("v = 5\n")
import m as k
print(k.v)
try:
    print(m.v)
except NameError as e:
    print(type(e).__name__)

Goal: Understand aliases

Q12. Fix the import

BeginnerDebugging

This code fails with an error. Fix it so it prints 8.

Code
import lib
print(add(3, 5))

Goal: Use module attributes

Q13. Fix the guard

IntermediateDebugging

The script below was meant to run its demo only when executed directly, but the demo runs on every import. Fix the condition.

Code
def f():
    return 1

if __name__ == "guard_demo":
    print("demo")

Goal: Use the __name__ guard

Q14. Why not name a file random.py?

IntermediateConceptual

You create a file called random.py in your project and then write import random. Explain what goes wrong.

Goal: Understand sys.path

Q15. Reusable validation helpers

IntermediateApplication

You are building a small app that checks user input in many scripts. Describe how you would organise the checking code using a module, and name one thing to keep out of the top level of that module.

Goal: Design a module