How to Write a Script in Python

A Python 3 script is a plain-text file ending in .py that contains instructions Python runs in order. For a new script, use Python 3 rather than deprecated Python 2, then write the file in a code editor and run it from a terminal. This guide walks through a working first script, a maintainable script layout, and the differences between Windows, Linux, and macOS.

What a Python Script Is

A Python script is a file containing Python code intended to run as a program. The Python interpreter reads that file and executes its instructions.

Scripts differ from the interactive Python prompt:

  • In the interactive prompt, you enter one statement at a time and see the result immediately. A prompt beginning with >>> means you are in this mode.
  • In script mode, you save several statements in a .py file and run the whole file when you are ready.

A script can be as small as one print() statement or as large as a command-line tool that processes files, calls web services, or automates a repetitive task. Python’s official tutorial covers the language features, such as functions, modules, and file handling, that let a simple script grow into a useful program.

How to Create and Run a Simple Python Script

Use a code editor and terminal for this process. A code editor preserves the plain text that Python needs, while a terminal shows errors and output clearly.

Step 1: Confirm That Python 3 Is Available

On Windows, open Command Prompt by searching for cmd in the Start menu. Then check the Python Launcher:

py --version

On macOS or Linux, open Terminal and check the Python 3 command:

python3 --version

The result should identify a Python 3 release. The precise Python 3 version for a project depends on the script’s documentation and on the compatibility requirements of any packages it uses.

If Python is not installed, install Python 3 before continuing. On Debian- or Ubuntu-based Linux systems, the apt package manager can install the interpreter with:

sudo apt install python3

The `sudo apt install python3` command is for Linux distributions that use apt; use your distribution’s package-manager documentation for the equivalent command elsewhere.

Step 2: Create a .py File

Create a new folder for your scripts, open that folder in a code editor, and create a file named program.py.

Paste in this code:

name = input("What is your name? ")
print(f"Hello, {name}!")

Save the code as program.py in the folder you created.

This short script does two things:

  1. input() pauses and waits for text from the person running the program.
  2. print() displays a greeting using an f-string, which inserts the value of name inside the text.

Use spaces, not tabs, for code indentation. The Python Windows FAQ recommends 4 spaces for Python code and warns that mixing tabs and spaces causes problems. In your editor settings, set the tab size to 4 and select Insert Spaces.

I use a code editor with a terminal for this step because it keeps the source file as plain text and lets me run it from the same project folder.

Step 3: Run the Script From the Folder Where You Saved It

Open a terminal in the folder containing program.py. Make sure you are at a normal system prompt, not the Python prompt that begins with >>>.

On Windows, run:

py program.py

On Linux or macOS, run:

python3 program.py

Using python3 program.py explicitly selects Python 3 on systems where more than one Python command may be available. Before running a project script, use `py –version` on Windows or `python3 –version` on macOS or Linux to confirm the command available on that machine.

Step 4: Test the Result

The terminal should ask for your name. Type a name and press Enter:

What is your name? Maya
Hello, Maya!

You have now written and run a Python script. Change the greeting in program.py, save it, and run `py program.py` on Windows or `python3 program.py` on macOS or Linux to confirm that Python is executing the saved version.

How to Organize a Python Script

Small scripts can place code directly in the file. As a script grows, use imports, functions, and a clear entry point.

Keep the executable behavior small and put reusable work in functions.

Put imports near the top of the file, before code that uses them. The basic form is:

import module_name

The main() function holds the program’s top-level workflow. The conditional:

if __name__ == "__main__":

runs main() when you execute the file directly, including with python3 program.py. It does not run automatically if another Python file imports this script, which makes the functions easier to reuse and test.

Use comments when they explain intent that the code itself cannot make clear:

# Ask the user for the name to display in the report.
name = input("Name: ")

Avoid comments that only restate obvious code.

Make a Python Script Executable on Linux or macOS

You do not need to make a script executable to run it with python3 program.py. Making it executable is optional, but it is useful when you want to start it directly with ./program.py.

Add a Shebang Line

Add this as the first line of the script:

#!/usr/bin/env python3

This is called a shebang. On Unix-like systems such as Linux and macOS, it tells the system to use the Python 3 interpreter when the file is launched directly. Without a shebang, a directly launched script does not specify the Python 3 interpreter your script needs.

Give the File Execute Permission

From the folder containing the script, run:

chmod +x program.py

Then start it directly:

./program.py

The script should display the same prompt and output as it did when started with Python explicitly.

Use Packages Without Mixing Project Dependencies

Python includes a large standard library, so many scripts need no additional installation. For example, datetime, pathlib, json, csv, and argparse are available with Python itself.

When a script needs an external package, install it in a virtual environment rather than into the system-wide Python installation.

A virtual environment keeps one project’s packages from changing another project’s Python setup.

Create a virtual environment from your project folder.

On Linux or macOS:

python3 -m venv .venv

Activate it:

source .venv/bin/activate

On Windows Command Prompt, create it with:

py -m venv .venv

Then activate it:

.venv\Scripts\activate

If pip is not installed on a Debian- or Ubuntu-based Linux system, install the Python 3 package-management tool with:

sudo apt install python3-pip

After activating the virtual environment, install the package your script requires. For example:

python -m pip install requests

A script can then import that installed package:

import requests

When you are finished working in the environment, leave it with:

deactivate

Keep the virtual environment folder out of source control when using Git. You can recreate it later from the project’s dependency list.

Test and Troubleshoot a Python Script

Run the script after each small change instead of writing a large amount of code before testing. Python reports errors with a traceback that usually identifies the file and line number involved.

Read the First Useful Error Message

Start at the bottom of a traceback. The final line usually names the error type and gives the clearest description.

Common examples include:

  • SyntaxError: Python cannot understand the code, often because of a missing quote, parenthesis, colon, or comma.
  • IndentationError: Lines in a code block do not line up correctly. Use 4 spaces consistently.
  • NameError: The script refers to a variable or function that has not been defined.
  • ModuleNotFoundError: Python cannot find an imported package or module.

Fix Common Setup Problems

If the terminal says Python or the py launcher cannot be found, Python 3 is either not installed or is not available through that terminal’s configured command path.

If an imported package cannot be found, make sure you activated the same virtual environment where you installed that package. A package installed under one Python environment is not automatically available in another.

Also avoid naming your own file after a standard-library module. A descriptive filename makes it easier to identify the script in its project folder.

Confirm That the Script Is Finished

Before relying on a script, check that:

  • The file is saved with a .py extension.
  • You run it from the intended project folder.
  • It accepts normal input without crashing.
  • Its output matches the expected result.
  • It finishes without a traceback.
  • It handles likely bad input when the script will be used by other people.

For scripts that rename, delete, or overwrite files, test first with copies of unimportant files.

Frequently Asked Questions

How do I create a .py file?

Create a new plain-text file named program.py in a code editor and save it in the folder for your scripts. Do not use a word processor such as Microsoft Word because it can add formatting that Python cannot read. A code editor with Python syntax highlighting makes indentation and mistakes easier to spot.

How do I start a Python script?

On Windows, open Command Prompt by searching for cmd, open the folder containing the file, and run:

py program.py

On macOS or Linux, open Terminal in the script’s folder and run:

python3 program.py

The script begins when the Python interpreter reads the file.

How do I write “I love you” in Python code?

Use print() to display the message:

print("I love you")

Save the code as love.py, then run `py love.py` on Windows or `python3 love.py` on macOS or Linux.

Is Python coding easy or hard?

Python is one of the more approachable programming languages because its syntax is designed to be readable. The difficult part is usually breaking a task into small steps, handling unexpected input, and learning how to read error messages. Start with short scripts that print output, accept input, and work with one file or one task at a time.

How do I write a Python script in Linux?

Create a plain-text .py file, write Python 3 code in it, and run it from Terminal. On Debian- or Ubuntu-based systems where Python 3 is not installed, use:

sudo apt install python3

Then run a saved file with:

python3 program.py

Once that works, add one small feature at a time, such as reading a file, accepting a command-line argument, or organizing repeated work into a function.