How to Run a Python Script – A Beginner's Guide

1. Running a Python Script from the Command Line

The most common way to run a Python script is through the command line (Terminal or Command Prompt).

Step 1: Create a Python Script

Create a simple Python script and save it as hello.py.

 
 
# hello.py
print("Hello, World!")

Step 2: Open the Command Line

  • Windows: Press Win + R, type cmd, and press Enter.
  • macOS: Open Terminal from Applications.
  • Linux: Open a terminal window.

Step 3: Navigate to the Script Directory

Use the cd command to move to the folder where your script is saved.

cd path/to/your/script

Example (Windows):

cd C:\Users\YourName\Documents

 

Example (macOS/Linux):

cd /Users/YourName/Documents

Step 4: Run the Python Script

Use the following command to run your script:

python hello.py

If you have multiple versions of Python installed, you might need to use:

python3 hello.py

🎉 Output:

Hello, World!

💡 Best Practice: Use absolute paths to avoid navigation issues.

2. Running a Python Script in VS Code

Step 1: Install VS Code and Python Extension

  1. Download and install VS Code.
  2. Open VS Code and install the Python Extension from the Extensions Marketplace.

Step 2: Open Your Python Script

  • Open VS Code and go to File > Open Folder.
  • Select the folder containing your script (hello.py).

Step 3: Run the Script

  1. Open the script in VS Code.
  2. Click on the Run button at the top (▶ Run).
  3. Or press Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (macOS), then type Run Python File in Terminal.

🎉 Output appears in the terminal below!

💡 Best Practice: Use a virtual environment in VS Code for managing dependencies.

3. Running a Python Script in PyCharm

Step 1: Install PyCharm

Download and install PyCharm.

Step 2: Open or Create a Python Script

  1. Open PyCharm and create a new Python project.
  2. Inside the project folder, create a new file (hello.py).

Step 3: Run the Script

  1. Right-click on hello.py.
  2. Click Run ‘hello’.
  3. The output will appear in the Run window.

💡 Best Practice: Use PyCharm’s built-in terminal (Alt + F12) to run scripts manually.

4. Running a Python Script as an Executable (.pyw or .exe)

If you don’t want to use the terminal, you can run Python scripts in different ways:

Method 1: Double-Click the Script (Windows)

  • Rename hello.py to hello.pyw (removes the console window).
  • Double-click it to run!

Method 2: Convert to an Executable (.exe) using PyInstaller

pip install pyinstaller
pyinstaller --onefile hello.py

This creates an .exe file inside the dist/ folder.

💡 Best Practice: Use PyInstaller’s --noconsole option to hide the terminal window.