Back to Contents

Using Scripts

From now on, instead of showing the actual Python session…

>>> def factorial(n):
...     if n == 1:
...         return n
...     else:
...         return n * factorial(n - 1)

…we will usually just show the program in a box:


In fact, this is just how Python programs are normally written, in a text file with the .py extension, rather than typed directly into Python.

We can use the from … import … construct to access the program from Python. Assuming we have a file which looks like the contents of the box above, we can write:

>>> from script import factorial
>>> factorial(4)

We can use from … import * to import all definitions from a script. When we have made a change to the file in our text editor (and saved the file), Python must be restarted and the script imported anew.

You will notice that, after running the import statement, the directory __pycache__ has appeared alongside This is for Python’s internal use, and you may discard it if you like.