Python by Example

Hello World

The smallest runnable Python program - printing a message and understanding the script guard pattern.

The smallest runnable Python program prints a message to the console. Run it with python file.py, or add a shebang line (#!/usr/bin/env python3) to make the file executable directly. The if __name__ == "__main__": guard lets the same file act as both a runnable script and an importable module.

print() writes its argument to stdout, followed by a newline. This is how Python says hello to the world.

print("Hello, World!")

Running the script produces:

OUTPUT
Hello, World!

Wrapping your script logic inside if __name__ == "__main__": lets the file be imported by another module without running the script body. __name__ is the module's name when imported, or "__main__" when run directly.

def greet(name):
    print(f"Hello, {name}!")
 
if __name__ == "__main__":
    greet("World")

In production

print() is fine for scripts and CLIs. Production services need the stdlib logging module (or structlog) so log levels, structured fields, and request-correlation IDs survive into Datadog or Loki. Plain print() writes to stdout with no level metadata and cannot be silenced without code changes.

Enjoyed this? Get more essays on software craft delivered to your inbox.

Subscribe free