Sub topic 2
Trying Code in the Interactive Interpreter
Assume Python 3 is installed and your terminal can run python3 or py. You should also know how to open a terminal and change directories. This chapter uses the REPL, Python’s interactive interpreter, to test small pieces of code before saving a program.
Trying code in the REPL
Open a terminal and enter the command for your system:
python3
# Windows:
pyThe prompt >>> means Python is waiting for a statement. Python evaluates each statement as soon as you press Enter.
>>> 2 + 3
5
>>> name = "Ada"
>>> print("Hello, " + name)
Hello, Ada
>>> exit()The REPL is useful for quick calculations, checking how a function behaves, and exploring unfamiliar features. It is not the best place for a complete program because your work disappears when you exit unless you save it elsewhere.
Choosing an editor
Use a code editor that supports plain text and Python syntax highlighting. A general editor such as VS Code is a common choice. Avoid word processors because they can add formatting characters that Python cannot read.
The editor saves your code in a file ending in .py. The terminal runs that file with the Python interpreter.
Writing and running a script
Create a file named hello.py in a new folder. Enter this code and save it:
print("Hello, world!")In the terminal, change to the folder containing the file. Then run:
python3 hello.py
# Windows:
py hello.pyPython reads the file from top to bottom and prints:
Hello, world!The workflow is:
Exercise
When should you prefer the REPL over a script file?
Show answer
Prefer the REPL for quick experiments and a script file for code you want to save, rerun, or share.