SAVING YOUR CODE IN A MODULE
Earlier you saw how to launch the Python interpreter from the command line and then enter commands. However, everything you type in the Python interpreter is only valid for the current session: if you exit the interpreter and then launch the interpreter again, your previous definitions are no longer valid. Fortunately, Python enables you to store code in a text file, as discussed in the next section.
A module in Python is a text file that contains Python statements. In the previous section, you saw how the interpreter enables you to test code snippets whose definitions are valid for the current session. If you want to retain the code snippets and other definitions, place them in a text file so that you can execute that code outside of the interpreter.
The outermost statements in a Python program are executed from top to bottom when the module is imported for the first time, which will then set up its variables and functions.
A Python module can be run directly from the command line, as shown here:
python first.py
As an illustration, place the following two statements in a text file called first.py:
x = 3 print(x)
Now type the following command:
python first.py
The output from the preceding command is 3, which is the same as executing the preceding code from the interpreter.
When a module is run directly, the special variable __name__ is set to __main__. You will often see the following type of code in a module:
if __name__ == '__main__':
# do something here
print('Running directly')
The preceding code snippet enables Python to determine if a module was launched from the command line or imported into another module.