Last modified: Jan 21, 2026 By Alexander Williams

How Python Runs Code: Scripts, REPL, and __main__

Python is a versatile language. You can run code in different ways. Understanding these methods is key. It helps you write better programs. It also helps you debug effectively.

This guide explains three core execution modes. We will cover scripts, the REPL, and the __main__ module. You will learn when to use each one. You will also see practical code examples.

Running Python Scripts from Files

A script is a file containing Python code. It has a .py extension. You run it from your terminal or command line. The Python interpreter reads the file. It then executes the commands line by line.

This is the most common way to run Python programs. It is ideal for automation, data processing, and building applications. For instance, you might write a script to monitor AWS with Python.

Let's create a simple script. Save the following code in a file named `hello.py`.


# hello.py - A simple Python script
def greet(name):
    """A function to greet a user."""
    return f"Hello, {name}!"

# This line calls the function
message = greet("Alice")
print(message)
    

To run this script, open your terminal. Navigate to the script's directory. Then type:


python hello.py
    

You should see this output:


Hello, Alice!
    

The interpreter started. It read the `hello.py` file. It defined the greet function. It then executed the call to that function and the print statement. The script runs from top to bottom.

The Interactive Python REPL

REPL stands for Read-Eval-Print Loop. It is an interactive shell. You type Python code directly. The interpreter reads it, evaluates it, prints the result, and loops back for more.

It is a powerful tool for learning and testing. You can try small code snippets instantly. You don't need to create a file. To start the REPL, just type python in your terminal.


$ python
Python 3.9.0 (default, Oct  6 2020, 00:00:00)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
    

The `>>>` is the prompt. You can type any valid Python code here.


>>> 5 + 7
12
>>> import math
>>> math.sqrt(16)
4.0
>>> def test():
...     print("REPL is great!")
...
>>> test()
REPL is great!
    

Notice the `...` prompt for multi-line blocks. The REPL is perfect for quick experiments. For example, you can test a parsing function before adding it to a larger web scraping script.

Understanding the __main__ Module

This is a crucial concept for script organization. In Python, every module has a name. When a module is run directly, its special `__name__` variable is set to the string `"__main__"`. If it is imported by another module, `__name__` is set to the module's actual name.

This allows you to control the execution flow. You can write code that only runs when the file is executed as a script. This is done with an `if __name__ == "__main__":` block.

Consider this file, `calculator.py`.


# calculator.py

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

# Code inside this block runs only when executed as a script
if __name__ == "__main__":
    print("Running as the main program!")
    result = add(10, 5)
    print(f"10 + 5 = {result}")
    

Run it as a script:


$ python calculator.py
Running as the main program!
10 + 5 = 15
    

Now, create another file `app.py` that imports `calculator`.


# app.py
import calculator

sum_result = calculator.add(20, 30)
print(f"Sum from imported module: {sum_result}")
    

Run `app.py`:


$ python app.py
Sum from imported module: 50
    

Notice the `"Running as the main program!"` message is gone. The code inside the `if __name__ == "__main__":` block did not execute. This is because for the `calculator` module, `__name__` was `"calculator"`, not `"__main__"`.

This pattern is essential for creating reusable modules. It lets you keep your function definitions clean. It also provides a clear entry point for your script. This structure is common in libraries for neural networks and other complex projects.

Putting It All Together: A Practical Example

Let's build a small utility that uses all three concepts. It will be a module you can import. It will also run as a standalone script. We'll test parts of it in the REPL first.

First, open the REPL to design a function.


>>> def analyze_text(text):
...     """Returns word count and character count."""
...     words = text.split()
...     char_count = len(text.replace(" ", ""))
...     return len(words), char_count
...
>>> analyze_text("Python is awesome")
(3, 14)
    

Great! Now, let's put it into a script file `text_utils.py`.


# text_utils.py
"""A module for basic text analysis."""

def analyze_text(text):
    """Returns word count and character count."""
    words = text.split()
    char_count = len(text.replace(" ", ""))
    return len(words), char_count

def main():
    """The main function executed when run as a script."""
    sample = input("Enter a sentence to analyze: ")
    words, chars = analyze_text(sample)
    print(f"Words: {words}, Non-space Characters: {chars}")

if __name__ == "__main__":
    main()
    

You can run this as a script. It will prompt the user for input.


$ python text_utils.py
Enter a sentence to analyze: Learning Python is fun
Words: 4, Non-space Characters: 18
    

You can also import the `analyze_text` function into another program without triggering the user input prompt. This separation of concerns is the power of the `__main__` pattern.

Conclusion

Python offers flexible ways to execute code. Each method serves a distinct purpose.

Scripts are for full programs and automation. The REPL is for instant testing and exploration. The __main__ pattern is for creating professional, reusable modules.

Master these three concepts. You will write more organized and effective Python code. You will seamlessly switch between testing ideas and building robust applications. Remember to use `if __name__ == "__main__":` in your script files. It is a best practice that defines a clear starting point for your program.