devnotes.

Running Python Code: REPL, Scripts, and Notebooks

Python code can be run three main ways, each suited to a different kind of work.

python3                  # starts the interactive REPL
>>> 2 + 2
4
>>> exit()

python3 script.py        # runs a .py file from top to bottom

The REPL (Read-Eval-Print Loop) — started by typing python3 with no arguments — is Python's interactive shell: type an expression, press Enter, and see the result immediately, without saving a file first. It's ideal for quick experiments and checking how a function behaves, but not for anything you want to save or run again later.

A .py script is a plain text file of Python code, run top-to-bottom with python3 script.py — this is the standard way to write and run real programs, since the code is saved, version-controllable, and repeatable.

if __name__ == "__main__":
    print("This runs only when the file is executed directly")

The if __name__ == "__main__": guard is a near-universal Python idiom: __name__ equals "__main__" only when the file is run directly, not when it's imported by another file — this lets a script define reusable functions and runnable top-level code in the same file, without the runnable part accidentally executing whenever someone else imports it.

Jupyter notebooks (.ipynb files) offer a third style: code split into cells that can be run individually and re-run in any order, with output (including plots and tables) displayed directly beneath each cell — the standard tool for data exploration and analysis, though less suited to production code than plain .py scripts.

Running Python: REPL, Scripts, and Jupyter Notebooks | DevNotes