Running Python Scripts
Learn how to write, save, and execute Python programs from the command line using the python file.py command.
What Is a Python Script?
A Python script is a plain text file containing Python code, saved with the .py extension. Instead of typing commands one by one into an interactive prompt, you write all your instructions in a file and run them together.
The Big Picture: From Code to Output
The workflow is simple: write your code in a .py file, run it with the python command in a terminal, and see the results on screen.
Why Run Scripts Instead of Typing Live?
The Core Command
Anatomy of python file.py
Interactive vs Script Mode
| Interactive (REPL) | Script Mode | |
|---|---|---|
| How to start | Type python alone | Type python file.py |
| Code saved? | No: lost when you quit | Yes: stored in .py file |
| Best for | Quick tests, math | Real programs, projects |
| Runs how? | One line at a time | Whole file, top to bottom |
How to Run Your First Script
Example 1: Hello, World!
print("Hello, World!")
In the terminal:
Hello, World!
Example 2: Multiple Lines
name = "Alice"
age = 16
print("Hi, I'm", name)
print("I am", age, "years old")
Hi, I'm Alice
I am 16 years old
Example 3: Navigating to Your File
If your script is in a folder called projects on your Desktop, you must cd (change directory) there first.
C:\Users\you> cd Desktop\projects
C:\Users\you\Desktop\projects> python greet.py
# Mac / Linux
$ cd ~/Desktop/projects
$ python3 greet.py
What Happens Under the Hood?
python vs python3
$ python --version
Python 3.12.1
$ python3 --version
Python 3.12.1
Reading Error Messages
File "hello.py", line 1
print("Hello)
^
SyntaxError: unterminated string literal
Common Mistakes
Quick Reference Table
| Task | Command | Example |
|---|---|---|
| Check Python version | python --version | Python 3.12.1 |
| Run a script | python file.py | python hello.py |
| Navigate folders | cd path | cd Desktop/projects |
| List files | ls / dir | hello.py greet.py |
| Open interactive mode | python (no file) | >>> |
| Exit interactive mode | exit() | back to $ |
Question 1 of 5
Which command correctly runs a Python script called app.py from the terminal?
Question 2 of 5
You type python hello.py and get the error: "No such file or directory". What is the most likely cause?
Question 3 of 5
What is the difference between typing python alone and python file.py in the terminal?
Question 4 of 5
A student saves their code in a file called mycode.py but types python mycode (without the .py extension) in the terminal. What will most likely happen?
Question 5 of 5
You see the >>> prompt and type python hello.py. You get a SyntaxError. Why?