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 definesdouble(x)that returnsx * 2and, with the guard, showsRun as a programif__name__is"__main__"andImported as a moduleotherwise. - Read
nand thennnames, 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 functiondoubleof the namespace with 21.
2
__main__
util
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