Python • Getting Started and Tooling

Running Python Scripts — Run a Python script from the command line (python file.py)

Learn how to write, save, and execute Python programs directly from your terminal or command prompt.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Before graphical user interfaces became widespread, programmers interacted with computers almost exclusively through a command line — a text-based interface where you type instructions and the computer responds. When Guido van Rossum created Python in the late 1980s, he designed it to be run from this command line environment. Even today, with all the fancy code editors and integrated development environments (IDEs) available, running a Python script from the command line remains the most fundamental and universal way to execute your code.

Understanding how to run scripts from the command line gives you direct control over your programs. It is also the foundation for automation, server-side programming, and professional software development workflows. Whether you are building a simple calculator or training a machine learning model, the journey starts with a single command: python file.py.

1991 • Python 0.9 Released

Guido van Rossum releases the first public version of Python. Scripts are run from Unix shell terminals using the command line.

2000 • Python 2.0 Arrives

Python 2.0 introduces list comprehensions and garbage collection. The python command becomes standard on Linux and macOS systems.

2008 • Python 3.0 Released

Python 3 modernizes the language. On some systems, users must type python3 to distinguish it from older Python 2 installations.

2020s • Python Dominates Education

Python becomes the most popular introductory programming language worldwide. Running scripts from the command line remains a core skill taught in classrooms and bootcamps everywhere.

So how does a plain text file on your computer become a running program? That is exactly the question this lesson answers. You will learn to create a Python file, open a terminal, navigate to the right folder, and execute your script — all with a single, powerful command.

SECTION 2

Core Principles & Definitions

Before you can run a Python script, you need to understand a few foundational concepts. These building blocks will help you troubleshoot problems and feel confident every time you open a terminal.

1

Python Script

A plain text file with a .py extension containing Python code. Your computer does not execute this file directly — it passes it to the Python interpreter.
2

Python Interpreter

The program installed on your computer that reads your .py file, translates each line into instructions the computer understands, and executes them one by one.
3

Terminal / Command Prompt

A text-based interface where you type commands. On Windows it is called Command Prompt or PowerShell; on macOS and Linux it is called Terminal.
4

Working Directory

The folder your terminal is currently "inside." When you type python file.py, the terminal looks for that file in the working directory.
5

PATH Environment Variable

A system setting that tells your terminal where to find executable programs like python. If Python is not on your PATH, the terminal will not recognize the command.
✦

KEY TAKEAWAY

Think of running a Python script like ordering food at a restaurant. Your script is the recipe written on paper, the interpreter is the chef who reads the recipe and cooks the dish, and the terminal is the counter where you hand the recipe to the chef. The command python file.py is you saying, "Hey chef, please follow this recipe!"

SECTION 3

Visual Explanation — From File to Output

The diagram below shows the complete journey of running a Python script. It starts with you typing a command in the terminal, moves through the Python interpreter, and ends with output displayed on your screen. Follow the arrows to trace each step.

How python file.py WorksSTEP 1You type command$ python hello.pySTEP 2Terminal finds Pythonvia PATH variableSTEP 3Interpreter readshello.py fileSTEP 4Translates & executesline by lineSTEP 5Output appearsHello, World!$ python hello.pyHello, World!
The five-step flow from typing a command to seeing output. Steps 1–3 happen almost instantly: the terminal locates the Python interpreter, which then reads your .py file. Step 4 is where your code actually runs, and Step 5 displays the result.

Notice that the interpreter processes your code line by line from top to bottom. This is why the order of statements in your script matters. If you reference a variable before defining it, Python will raise an error because it has not encountered that line yet.

SECTION 4

How It Works — Step by Step

Step 1: Create Your Python File

Open any text editor — Notepad on Windows, TextEdit on macOS (in plain text mode), or a code editor like VS Code. Type your Python code and save the file with a .py extension. For example, create a file called hello.py with this content:

ℹ

hello.py

print("Hello, World!")

Step 2: Open Your Terminal

On Windows, press the Windows key, type "cmd" or "PowerShell", and press Enter. On macOS, open Spotlight (Cmd + Space), type "Terminal", and press Enter. On Linux, look for Terminal in your applications menu or press Ctrl + Alt + T.

Step 3: Navigate to Your File's Location

Use the cd (change directory) command to navigate to the folder where you saved your file. For example, if you saved hello.py on your Desktop, you would type cd Desktop and press Enter. You can verify you are in the right place by typing dir (Windows) or ls (macOS/Linux) to list the files in your current directory.

Step 4: Run the Script

Type python hello.py and press Enter. If you are on macOS or Linux and your system has both Python 2 and Python 3 installed, you may need to type python3 hello.py instead. The interpreter will read your file and execute the print() function, displaying Hello, World! in the terminal.

⚠

Common Gotcha: "python is not recognized"

If you see an error like "python is not recognized as an internal or external command," Python is not on your system's PATH. On Windows, reinstall Python and check the box labeled "Add Python to PATH" during installation. On macOS/Linux, try typing python3 instead.

SECTION 5

Essential Terminal Commands for Python

To run Python scripts effectively, you need to be comfortable with a handful of terminal commands. The diagram below maps out the most important ones and shows how they relate to each other in a typical workflow.

Essential Terminal Commands Cheat SheetNAVIGATIONcd folder_nameEnter a foldercd ..Go up one levelpwd / cdShow current pathls / dirList filesmkdir folder_nameCreate new folderRUNNING PYTHONpython file.pyRun a scriptpython3 file.pyRun with Python 3python --versionCheck versionpythonOpen REPLexit()Exit REPLTYPICAL WORKFLOW EXAMPLE1.cd Desktop/my_projectNavigate to your project folder2.lsVerify your .py file is there3.python hello.pyRun your script4.Hello, World!Output appears — success!
A reference chart of essential terminal commands grouped by purpose. The bottom section shows a typical workflow: navigate, verify, run, and see output.
CommandWindowsmacOS / Linux
List filesdirls
Change directorycd folder_namecd folder_name
Show current pathcd (alone)pwd
Run Python scriptpython file.pypython3 file.py
Check Python versionpython --versionpython3 --version

Cross-platform command comparison

SECTION 6

Worked Example — Building and Running a Temperature Converter

Let's walk through a complete example from scratch. We will create a Python script that converts a temperature from Fahrenheit to Celsius, then run it from the command line.

Create and Run temp_converter.py

  1. 1

    Step 1 — Write the Script

    Open your text editor and type the following code. Save the file as temp_converter.py on your Desktop. fahrenheit = 98.6 celsius = (fahrenheit - 32) * 5 / 9 print(f"{fahrenheit}°F is {celsius:.2f}°C")
    File saved as temp_converter.py
  2. 2

    Step 2 — Open the Terminal

    Open your terminal application. On Windows, press the Windows key and type "cmd". On macOS, press Cmd + Space and type "Terminal".
    Terminal window is now open
  3. 3

    Step 3 — Navigate to the Desktop

    Type cd Desktop and press Enter. Verify the file is there by listing the directory contents with ls (macOS/Linux) or dir (Windows). You should see temp_converter.py in the output.
    Working directory is now Desktop
  4. 4

    Step 4 — Run the Script

    Type python temp_converter.py (or python3 temp_converter.py on macOS/Linux) and press Enter.
    98.6°F is 37.00°C
  5. 5

    Step 5 — Modify and Re-run

    Go back to your text editor and change the value of fahrenheit to 212. Save the file, then return to your terminal and press the Up arrow key to recall the previous command. Press Enter to run the updated script.
    212°F is 100.00°C
💡

Pro Tip: The Up Arrow Key

You do not need to retype your command every time you want to run your script again. Pressing the Up arrow key in the terminal recalls your previous commands, saving you time during the edit-run-debug cycle.

SECTION 7

Command Line vs. Other Ways to Run Python

Running scripts from the command line is not the only option for executing Python code. You might have used an online editor, a Jupyter notebook, or an IDE's built-in run button. Each method has its place, but understanding their trade-offs helps you choose the right tool for the job.

MethodStrengthsLimitations
Command Line (python file.py)Works everywhere, fast, no extra software needed, great for automation and scriptingNo built-in code highlighting, no auto-complete, must navigate with cd commands
IDE Run Button (VS Code, PyCharm)Syntax highlighting, auto-complete, integrated debugging, click-to-run convenienceHeavier software, hides what is actually happening behind the scenes
Interactive REPL (typing python alone)Instant feedback, great for testing small snippets and exploringCode is not saved, impractical for multi-line programs
Online Editors (Replit, Google Colab)No installation required, shareable, accessible from any deviceRequires internet, limited access to local files and system features

Comparison of Python execution methods

✦

KEY TAKEAWAY

IDEs and online editors are like riding a bike with training wheels — helpful while you learn, but eventually you will want the freedom of riding without them. The command line is like riding a regular bike: it requires a bit more skill, but once you learn it, you can go anywhere. Mastering python file.py gives you a skill that transfers to every operating system and every professional environment.

SECTION 8

Connection to Advanced Workflows

Running a single script from the command line is your starting point, but professional developers build on this foundation every day. As you grow as a programmer, you will encounter more powerful ways to use the command line with Python. Here is a preview of what lies ahead.

What You Know NowWhat Comes Next
python file.pypython file.py arg1 arg2 — passing command-line arguments to your script
Running one script at a timeUsing virtual environments to manage different projects and their dependencies
Seeing output in the terminalRedirecting output to files: python file.py > output.txt
Manually running scriptsAutomating scripts with cron jobs (Linux/macOS) or Task Scheduler (Windows)
Single-file programsMulti-file projects with modules and packages using import

From beginner to advanced command-line usage

Each of these advanced skills builds directly on the same python file.py command you are learning today. By mastering the fundamentals now, you are setting yourself up for a smooth transition into more complex development workflows. Think of today's lesson as learning to drive in a parking lot before heading out onto the highway.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

When you type python hello.py in the terminal, what role does the Python interpreter play? Explain in your own words what happens between pressing Enter and seeing output.
Show answer
The Python interpreter is a program that acts as a translator between your human-readable Python code and the machine instructions your computer understands. When you press Enter, the terminal locates the Python interpreter using the PATH environment variable, then passes the filename hello.py to it. The interpreter opens the file, reads the code line by line from top to bottom, translates each line, and executes it. If the code includes a print() statement, the output is sent back to the terminal for you to see.

Question 2: BASIC CALCULATION

You create a file called area.py with this content: length = 12 width = 5 area = length * width print("Area:", area) You save it in your Documents folder. Write the exact terminal commands (for Windows) to navigate to Documents and run this script. What output will you see?
Show answer
First, you would type cd Documents and press Enter to navigate to the Documents folder. Then you would type python area.py and press Enter. The output will be Area: 60 because the script multiplies 12 × 5 to get 60, then prints it with the label "Area:". If you wanted to verify the file was in the right place first, you could also type dir to list the files.

Question 3: INTERMEDIATE

A student tries to run their script and gets this error: python: can't open file 'greet.py': [Errno 2] No such file or directory List three possible causes for this error and describe how to fix each one.
Show answer
There are three common causes for this error. First, the student might be in the wrong directory — they need to use cd to navigate to the folder where greet.py is actually saved. They can verify their current location with pwd or cd (alone on Windows). Second, the file name might be misspelled — perhaps it was saved as Greet.py (with a capital G) or greet.txt instead. They should use ls or dir to see the actual file names. Third, the file might not have been saved at all — the student should go back to their editor and confirm the file was saved with the correct .py extension.

Question 4: APPLIED

You want to create a Python script that calculates your grade percentage. The script should store your earned points (85) and total possible points (100), compute the percentage, and print a message like "Your grade: 85.0%". Write the complete Python script, then describe the exact steps to save and run it from the command line on your operating system.
Show answer
Here is the script: earned = 85 total = 100 percentage = (earned / total) * 100 print(f"Your grade: {percentage}%") Save this as grade.py in a convenient location like your Desktop. Open your terminal, type cd Desktop to navigate there, then run python grade.py (or python3 grade.py on macOS/Linux). The output will be "Your grade: 85.0%". You could also modify the earned and total variables to calculate different grades and re-run the script.

Question 5: CRITICAL THINKING

Imagine you have two Python files in the same folder: helper.py contains a function, and main.py imports and uses that function. If you move main.py to a different folder but leave helper.py behind, what will happen when you try to run python main.py from the new location? Why does this happen, and what does it reveal about how the Python interpreter finds files?
Show answer
When you run python main.py from the new folder, Python will raise a ModuleNotFoundError because it cannot find helper.py. This happens because when Python encounters an import statement, it searches for the module in several locations, starting with the directory where the script being executed lives. Since helper.py is no longer in the same folder as main.py, Python cannot locate it. This reveals that the interpreter uses the script's location (and the working directory) as the starting point for finding other files. To fix this, you would either move both files to the same folder or configure Python's module search path — a concept you will explore when studying packages and modules.

SUMMARY

Lesson Summary

Summary

Running a Python script from the command line is the most fundamental way to execute your code. You create a Python script (a text file with a .py extension), open your terminal or command prompt, use cd to navigate to the folder containing your file, and type python file.py to execute it. The Python interpreter reads your code line by line, translates it into machine instructions, and produces output in the terminal.

Key details to remember: use python3 on macOS/Linux if python does not work; check that Python is on your PATH if the command is not recognized; and use ls or dir to verify you are in the correct working directory. This skill is the foundation for everything from automation to professional software development, and mastering it now will serve you throughout your programming journey.

Varsity Tutors • Python • Running Python Scripts — Run a Python script from the command line (python file.py)