How to Execute a Python Script
Executing a Python script means running a .py file so the Python interpreter reads and executes the code inside it. There are several common ways to run Python scripts depending on your environment.
Below is a step-by-step tutorial covering the most common methods.
Execute a Python Script from the Command Line (Recommended)
This is the most common and platform-independent method.
Step 1 — Create a Python Script
Create a file named:
File Name
hello.py
Example code:
Python
# hello.py
# Print a simple message
print("Hello, World!")
# Define two variables
a = 10
b = 20
# Perform addition
result = a + b
# Display the result
print("Sum:", result) Step 2 — Open Terminal / Command Prompt
Navigate to the folder containing the script.
Example:
Windows Command Prompt
cd C:\Users\Ashish\Documents\python-scripts
Or in Linux / Mac:
Terminal
cd /home/ashish/python-scripts
Step 3 — Run the Script
Execute the script using:
Bash
python hello.py
The output of the above code is:
Output
Hello, World! Sum: 30
Key Points
- python → Python interpreter.
- hello.py → Python script file.
- The interpreter executes the file line by line.