The Python REPL and More

Creating a Python file is pretty easy. Open a new file in your favorite text editor, put some Python code in it, and save it with a .py extension. Done!

“Done” means “but wait, there’s more!”

RIP

Let’s try creating a simple Python file. Save the following code as two.py:

1 + 1

Since we’re working with a file now, let’s use the python command to run the file instead of opening the REPL:

$ python two.py
$

Pikachu used Python! It’s not very effective…Why don’t we see a “2” anywhere?

Unlike the REPL, running code in files with Python requires you to explicitly print anything you want to see in the output. The code was executed, but the result vanished into thin air. Let’s try again, this time printing out the result of the addition explicitly:

print(1 + 1)

When we run the file this time, we see:

$ python two.py
2
$

Heck yes.

Let’s recap. Python can execute code stored in plain-text files. The Python interpreter behaves slightly differently when used to execute code in files as compared to being used as a REPL. As you think up more and more software, storing it in files will prove immensely useful.