Modules and imports · 15 / 16 Exercise Medium

Program or module

Objective

A file can be run as a program or imported as a module. The special name __name__ is "__main__" in the first case and the module name in the second. It is used to write the guard if __name__ == "__main__":.

Instructions

  • Store this code in a string SOURCE: it defines double(x) that returns x * 2 and, with the guard, shows Run as a program if __name__ is "__main__" and Imported as a module otherwise.
  • Read n and then n names, one per line.
  • For each name run the code with exec(SOURCE, {"__name__": name}), so that __name__ has that name.
  • Then show name: result, calling the function double of the namespace with 21.
Input
2
__main__
util
Output
Run as a program
__main__: 42
Imported as a module
util: 42

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise