Scripts and the Terminal

A script is a file that contains Python code. The terminal is a plain way to ask your computer to run that file.

The terminal can look unfamiliar because it is mostly text. For this chapter, you only need it for one simple job: run a Python file and show the output.

The command name may differ by operating system, but the Python file is the same.

This is the first local workflow:

  1. create a file
  2. write Python code
  3. run the file from the terminal
  4. read the output

Create the File

Use any plain-text editor available on your computer. Create a new folder named python-practice, save a file inside it as hello.py, and make sure the name does not end in .txt.

Open a terminal in that folder. Many file managers provide an Open in Terminal action. If yours does not, open a terminal, type cd including the space, drag the python-practice folder into the terminal when your system supports it, and press Enter. Then use pwd and the file-list command below to check where you are before running Python.

A Small Script

Create a file named hello.py:

If the file is in the folder where your terminal is currently looking, run:

On macOS or Linux:

python3 hello.py

On Windows PowerShell:

py -3 hello.py

Expected output:

Hello from a file
2 + 3 = 5

The terminal command has two parts:

  • python3 or py -3 starts Python
  • hello.py tells Python which file to run

Current Folder

The terminal always has a current folder. Think of it as the folder the terminal is looking at right now. If hello.py is not in that folder, Python will not find it.

On macOS, Linux, or Windows PowerShell, you can print the current folder with:

pwd

On macOS or Linux, list files with:

ls

On Windows PowerShell, list files with:

dir

File Names Matter

If your file is named hello.py, this command is wrong:

On macOS or Linux:

python3 helo.py

On Windows PowerShell:

py -3 helo.py

The spelling differs. Python will report that it cannot open the file. That is a file-path problem, not a Python-language problem.

Why Scripts Matter

Interactive prompts are useful for quick checks, but scripts can be rerun. That is why experiments should eventually become scripts. If you can rerun the same file, you can check whether a change improved the result or merely changed the conditions.

Exercise: Edit a tiny script

Change the value so the output contains score: 8.

Edit a tiny script

Runs locally with Python in your browser.

Ready to run.

HintChange the stored value

The print line already supplies the text score:. Change the number assigned to score.

SolutionAssign eight

Use score = 8 and leave the print line unchanged. The name then refers to 8, so print("score:", score) produces score: 8.

Why This Workflow Matters

A script is code you can rerun. That single property makes it important for learning, debugging, and experiments.