Scripts and modules

A collection of statements in a file (which usually has a py extension), is called a script. Suppose we put the contents of the following code into a file named smartscript.py:

def f(x):
    return 2*x + 1
z = []
for x in range(10):
    if f(x) > pi:
        z.append(x)
    else:
        z.append(-1)
print(z)

In a Python or IPython shell, such a script can then be executed with the exec command after opening and reading the file. Written as a one-liner it reads:

exec(open('smartscript.py').read())

The IPython shell provides the magic command %run as a handy alternative way to execute a script:

%run smartscript

Simple modules - collecting functions

Often one collects functions in a script. This creates a module with additional Python functionality. ...

Get Scientific Computing with Python 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.