English
/

Writing Your First Python Script with Functions

Last edited Oct 9, 2026 · 3 min read

Save Python code in a file and run it as a script to keep it between interpreter sessions. If you quit the interpreter and open it again, the functions and variables defined there are gone.

On this page▾
  1. From interpreter to file
  2. Using it from the interpreter
  3. Making the file runnable on its own
  4. Why this pattern matters once your code grows
  5. A minimal checklist for your first script

From interpreter to file

The Python tutorial defines a module as a file containing Python definitions and statements, with the file name being the module name plus .py. Any file you write and save this way can be both run directly and reused by other files through import.

Save the following as fibo.py, exactly as shown in the official tutorial's own example:

"""Fibonacci numbers module."""

def fib(n):
    """Write Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()

def fib2(n):
    """Return Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a + b
    return result

This defines two functions. fib prints the Fibonacci sequence up to a limit n. fib2 does the same calculation but returns a list instead of printing, which is useful when you want to use the numbers in more code rather than just see them.

Using it from the interpreter

With fibo.py saved in your current directory, you can import and use it:

import fibo

fibo.fib(1000)
print(fibo.fib2(100))

Running this with python3 prints:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

The fib call prints numbers directly, stopping once the next number would reach or exceed 1000. The fib2 call builds and returns a list of every Fibonacci number under 100, which the print() then displays as a list.

Making the file runnable on its own

Right now, fibo.py only does something if another program imports it. The Python tutorial shows a specific pattern for also letting a file run directly from the command line, using a special variable called __name__:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

Add that block to the bottom of fibo.py. According to the tutorial, when you run a module directly with python3 fibo.py <arguments>, Python sets __name__ to "__main__" for that file, so the code inside this if block runs. But when the same file is imported from somewhere else, __name__ is set to the module's actual name instead, so that block is skipped.

This means the file now works two different ways, and both are testable immediately:

python3 fibo.py 1000

This runs the script directly from the command line, reading 1000 from sys.argv[1], and prints:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

And importing it from another file or the interpreter still works the same as before, without that command-line block running:

import fibo
print(fibo.fib2(100))

which prints:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Why this pattern matters once your code grows

The Python tutorial explains the practical reason for the __name__ check: it lets one file serve two purposes, a convenient command-line tool and an importable library of functions, without those two uses interfering with each other. This is a pattern you will see in nearly every real Python project, not just toy examples like fibo.py.

A second detail from the tutorial worth knowing early: each module is only imported once per interpreter session, for efficiency. If you edit fibo.py while your interpreter session is still open and import fibo again, you will not see your changes. The tutorial's documented fix is to restart the interpreter, or to use importlib.reload() if you only want to reload that one module during an interactive session.

Keeping a script's packages separate with a virtual environment is covered in What Is a Python Virtual Environment, and How Do You Use pip?.

A minimal checklist for your first script

  1. Write your functions in a .py file, with clear docstrings describing what each one does (the triple-quoted string right under the def line).
  2. Test the functions by importing the file from the interpreter first.
  3. Add an if __name__ == "__main__": block at the bottom if you also want the file runnable directly from the command line.
  4. Restart the interpreter (or use importlib.reload()) any time you edit the file during an active session, since Python will not pick up changes automatically.

Sources

  1. Python Software Foundation, The Python Tutorial, Modules
  2. Python Software Foundation, The Python Tutorial, Defining Functions
  3. Python Software Foundation, importlib, The implementation of import

About this guide

Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.

AboutEditorial standardsCorrectionsReport an error

Edit history

  • Updated
  • Updated
  • Updated
  • Updated
  • Published