Writing Your First Python Script with Functions
A beginner walkthrough of turning interactive Python code into a reusable script, using the official Python tutorial's own module example.
Typing code directly into the Python interpreter is a fine way to test an idea, but the official Python documentation makes an important point about it: if you quit the interpreter and open it again, every function and variable you defined is gone. The fix, according to the Python tutorial, is to put your code in a file and run that file, which Python calls a 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.
A minimal checklist for your first script
- Write your functions in a
.pyfile, with clear docstrings describing what each one does (the triple-quoted string right under thedefline). - Test the functions by importing the file from the interpreter first.
- Add an
if __name__ == "__main__":block at the bottom if you also want the file runnable directly from the command line. - 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.
Key takeaways
- A Python script is just a
.pyfile; anything you can type into the interpreter can be saved and reused this way. import module_nameloads your functions without running any code gated behindif __name__ == "__main__":.- Running
python3 file.pydirectly sets__name__to"__main__"in that file, which is how the same file can work as both a script and an importable module. - Python only imports a given module once per session; edits require restarting the interpreter or using
importlib.reload(). - This article's commands were run with
python3and produced the exact output shown above.