Running Python from the Command Line

Back to Home Page


Before You Begin

This guide assumes you have:


Two Ways to Use Python

There are two main ways to use Python from the command line:

  1. Interactive Mode: Type Python code directly and see results immediately
  2. Script Mode: Run Python programs saved in .py files

Interactive Mode (Python Shell)

Starting the Python Shell

Open your terminal and type:

You should see something like this:

Python 3.13.1 (main, Jun 7 2023, 00:00:00)
[GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
  

Or, on Windows, you'll probably see:

Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
  

The >>> prompt means Python is ready for your commands!

Using the Python Shell

Try these commands:

>>> print("Hello, World!")
Hello, World!

>>> 2 + 2
4

>>> name = "Coder"
>>> print(f"Hello, {name}!")
Hello, Coder!
  

Exiting the Python Shell

To exit the Python shell, type:

>>> exit()

Or press Ctrl+D (Mac/Linux) or Ctrl+Z then Enter (Windows)


Script Mode (Running .py Files)

Running a Python File

To run a Python file, navigate to its folder in the terminal, then:

Example: Running Your First Script

  1. Create a file called greet.py with this content:
    name = input("What's your name? ")
    print(f"Nice to meet you, {name}!")
    print("Welcome to Python programming!")
          
  2. Save the file
  3. In the terminal, navigate to the file's location
  4. Run it:

Common Python Commands

Check Python Version

python --version

Or on Mac/Linux:

python3 --version

Run a Script with Arguments

You can pass information to your Python script:

python script.py argument1 argument2

Get Help

python --help

Troubleshooting Common Issues

"Python is not recognized"

This means Python isn't in your system's PATH. Try:

"No such file or directory"

This means Python can't find your file. Make sure:

SyntaxError

This means there's a mistake in your Python code. Check for:


Practice Exercises

Exercise 1: Calculator in Interactive Mode

Open the Python shell and try these calculations:

>>> 15 + 7
>>> 100 - 33
>>> 12 * 8
>>> 50 / 5
>>> 2 ** 10  # This means 2 to the power of 10
  

Exercise 2: Create and Run a Script

  1. Create a file called calculator.py
  2. Add this code:
    print("Simple Calculator")
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    
    print(f"{num1} + {num2} = {num1 + num2}")
    print(f"{num1} - {num2} = {num1 - num2}")
    print(f"{num1} * {num2} = {num1 * num2}")
    print(f"{num1} / {num2} = {num1 / num2}")
          
  3. Run the script from your terminal

Tips for Command Line Python


What's Next?

Now that you can run Python from the command line, try:


Back to Home Page