Chapter 02
Scripts, imports and the Python runtime
A minimal program
Python executes statements in order. The __main__ guard makes code run only when the file is executed directly, not when imported.
def main():
print("Welcome to Python")
if __name__ == "__main__":
main()Hands-on lab: Save as main.py and run python main.py.
Arguments and encoding
sys.argv exposes command-line arguments. UTF-8 is the standard source encoding in modern Python 3; text file encoding should still be specified explicitly.
import sys
print("Arguments:", sys.argv[1:])
# run: python main.py Alice 42Hands-on lab: Print the first user-supplied argument safely.
Imports and packages
Use import to reuse standard-library or third-party code. Avoid naming your script after a standard library module.
import math
print(math.sqrt(81))Hands-on lab: Use math.pi to calculate a circle area.