Running Python Code

Getting Started

Running Python Code

In this tutorial, we'll use the Python shell and run saved Python files.

There are two common ways to run Python code:

  • The interactive shell, which is useful for quick experiments
  • Python files, which are better for programs you want to save

Both are useful. Beginners often start in the shell, then move into files as their code gets longer.

The Interactive Shell

Open your terminal and type:

python3

You should see a prompt that looks like this:

>>>

That prompt means Python is waiting for you to type code. Try:

>>> 2 + 3
5
>>> print("Hello")
Hello

The shell is great for testing small ideas. For example, if you are unsure what 10 / 4 gives you, try it there.

To leave the shell, type:

exit()

Running a Python File

Most programs are written in files. A Python file usually ends in .py.

Create a file called greeting.py:

name = "Sam"
print("Hello", name)

Then run it:

python3 greeting.py

Python reads the file from top to bottom. First it stores "Sam" in name, then it prints the greeting.

Why Files Matter

Files let you build programs one step at a time. You can save your work, run it again, change one line, and run it again. This loop is how programming normally feels:

1. Write a small amount of code 2. Run it 3. Read the result 4. Fix or improve it

Do not wait until you have written a lot of code before running it. Small checks are much easier to debug.

Common Mistakes

If the terminal says it cannot find your file, make sure you are in the same folder as the file. You can use ls on macOS/Linux or dir on Windows to list files in the current folder.

If the file opens as text but does not run, check that the filename ends in .py, not .txt.

Practice

Create a file called about_me.py. Store your name, favourite food, and current goal in variables, then print them.