Skip to content

Module 1 · Introduction to Python — topic 13 of 14

Source code and execution

How a .py file becomes a running program: source code, execution order, the entry point with if __name__ == "__main__", exit codes and command-line arguments.

Intermediate 15 min read·Lesson 13 of 306 in Python Programming

Learning objectives

  • Explain the difference between source code and a running program
  • Use the if __name__ == "__main__" entry point
  • Read command-line arguments and exit with a status code

Definition

How a .py file becomes a running program: source code, execution order, the entry point with if __name__ == "__main__", exit codes and command-line arguments.

Introduction

Source code is the text you write. Execution is what happens when the interpreter carries it out. Between the two sit a few rules about where a program starts, in what order statements run, and how a program reports success or failure to the operating system.

Why it matters

These rules let you build programs that can be imported by other files without running unexpectedly, that accept options from the command line, and that tell scripts and schedulers whether they succeeded.

Detailed explanation

Source files are plain text saved with a .py extension and UTF-8 encoding. Python executes top-level statements in order. A def statement only creates a function; its body runs later when the function is called.

Every running file has a name stored in __name__. When you run a file directly, __name__ is "__main__". When another file imports it, __name__ is the module’s name. Checking if __name__ == "__main__": lets a file run its main code only when executed directly.

sys.argv is a list of the command-line words: sys.argv[0] is the script name and the rest are arguments typed after it.

When a program ends normally, it returns exit status 0 to the operating system. sys.exit(1) (or any non-zero number) signals failure, which tools such as schedulers and CI systems check.

Syntax

Python
def main():
...
if __name__ == "__main__":
main()
  • main() holds the program’s top-level work.
  • The if line is true only when this file is run directly.
  • Importing the file elsewhere defines main without running it.

Code examples

def creates, calling runs

Python
def greet():
print("inside greet")
print("before call")
greet()
print("after call")
Output
before call
inside greet
after call

The value of __name__

Python
print(__name__)
Output
__main__

Run directly, a file’s __name__ is "__main__".

More examples

A script with an entry point and arguments

Python
import sys
def total(prices):
return sum(prices)
def main(argv):
if len(argv) < 2:
print("usage: bill.py PRICE [PRICE ...]")
return 1
prices = [float(p) for p in argv[1:]]
print(f"Items: {len(prices)}, total: {total(prices):.2f}")
return 0
if __name__ == "__main__":
status = main(["bill.py", "120", "45.5", "80"])
print("exit status:", status)
Output
Items: 3, total: 245.50
exit status: 0

Step-by-step explanation

  • total() and main() are defined first; nothing inside them runs yet.
  • main(argv) checks there is at least one price and returns 1 (failure) if not.
  • argv[1:] skips the script name; each argument is converted to a float.
  • The example passes a sample argument list so it runs anywhere; in a real script you would call sys.exit(main(sys.argv)) to use the real command line.

Expected output

Running “A script with an entry point and arguments” prints exactly:

TextOutput
Items: 3, total: 245.50
exit status: 0

Practical applications

  • Command-line tools such as pip read options from sys.argv (often through argparse).
  • Shell scripts and CI pipelines stop when a step exits with a non-zero status.
  • Library files use the __main__ check to include a small demo that doesn’t run on import.

Best practices

  • Put a file’s main work in a main() function.
  • Return or exit with 0 for success and non-zero for errors.
  • Validate arguments and print a usage line when they are missing.

Common mistakes

Code runs when the file is imported

Avoid

main() called at the bottom of a module without a check.

Prefer

if __name__ == "__main__":
main()

Any top-level call runs on import; the check limits it to direct execution.

Forgetting argument strings are text

Avoid

total = sys.argv[1] + sys.argv[2]

Prefer

total = float(sys.argv[1]) + float(sys.argv[2])

Command-line arguments always arrive as strings and must be converted.

Key takeaways

  • Source code is text; execution runs top-level statements in order.
  • __name__ is "__main__" only when a file is run directly.
  • sys.argv holds command-line arguments as strings; exit status 0 means success.

Try it yourself

  1. 1
    Write a script that prints how many command-line arguments it received.
    Show hint

    len(sys.argv) - 1

  2. 2
    Change the bill example to apply 18% tax to the total before printing it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat happens first when CPython runs a .py file?
Practise this topic