Menu
CoddyTech

Imports and the Main Guard

Lesson 29 of 48 in Coddy's Python for C# Developers course.

Keep modules reusable by guarding interactive execution.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

// A using directive makes a namespace convenient; it is not Python import.
Console.WriteLine(System.Math.Abs(-4));

Python

import math

def root(n):
    return math.isqrt(n)

if __name__ == "__main__":
    print(root(16))

What changes

Python import loads a module and executes its top-level statements on first normal import in a process, then normally reuses the cached module. C# using affects name lookup; it is not equivalent to executing a Python module. A .py filename provides its module name. The main guard runs the interactive entry point only when the file is executed as the main module, leaving definitions reusable on import.

Transfer mistake

Putting input at module scope consumes data during import. Keep reusable definitions outside the guard and input inside main. The locked driver selects its own script/import mode; your editable module must not read that selector.

Your task

Edit program.py to import math, define common_pack(a, b) returning math.gcd(a, b), and define main() that reads two nonnegative integers and prints their gcd. Keep definitions outside if __name__ == "__main__": and call main only inside it. gcd(0, b) is b and gcd(0, 0) is 0. The locked driver consumes a script/import mode line: do not read that line yourself. Script mode executes your entry point. Import mode forbids input/output during module loading, then reads a helper-call count and pairs and prints each helper result. Your module must support both uses.

challenge icon

Challenge

Beginner

Edit program.py to import math, define common_pack(a, b) returning math.gcd(a, b), and define main() that reads two nonnegative integers and prints their gcd. Keep definitions outside if __name__ == "__main__": and call main only inside it. gcd(0, b) is b and gcd(0, 0) is 0. The locked driver consumes a script/import mode line: do not read that line yourself. Script mode executes your entry point. Import mode forbids input/output during module loading, then reads a helper-call count and pairs and prints each helper result. Your module must support both uses.

Editable implementation files: program.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

Try it yourself

import importlib as _coddy_importlib
import runpy as _coddy_runpy
import builtins as _coddy_builtins
_coddy_input = _coddy_builtins.input
_coddy_print = _coddy_builtins.print
_coddy_mode = _coddy_input()
_coddy_import_io = []
def _coddy_forbidden_input(*args, **kwargs):
    _coddy_import_io.append("input")
    raise AssertionError("input during module loading")
def _coddy_forbidden_print(*args, **kwargs):
    _coddy_import_io.append("print")
    raise AssertionError("print during module loading")
if _coddy_mode == "script":
    __name__ = "__main__"
elif _coddy_mode == "import":
    __name__ = "course_module"
    _coddy_builtins.input = _coddy_forbidden_input
    _coddy_builtins.print = _coddy_forbidden_print
else:
    raise AssertionError("invalid harness mode")

if _coddy_mode == "script":
    _coddy_namespace = _coddy_runpy.run_module("program", run_name="__main__")
else:
    _coddy_namespace = vars(_coddy_importlib.import_module("program"))
common_pack = _coddy_namespace['common_pack']
main = _coddy_namespace['main']
_coddy_builtins.input = _coddy_input
_coddy_builtins.print = _coddy_print
if _coddy_import_io:
    raise AssertionError("module loading attempted input or output")
if _coddy_mode == "import":
    if not callable(main):
        raise AssertionError("main must be a callable function")
    _coddy_count = int(_coddy_input())
    for _coddy_index in range(_coddy_count):
        _coddy_left, _coddy_right = _coddy_input().split()
        _coddy_result = common_pack(int(_coddy_left), int(_coddy_right))
        if type(_coddy_result) is not int:
            raise AssertionError("common_pack must return an integer")
        _coddy_print(_coddy_result)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C# Developers

Practice on your own: Online Python compiler