Back to Contents

Using Scripts

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

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

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

image

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 script.py which looks like the contents of the box above, we can write:

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

We can use from … import * to import all definitions from a script. When we have made a change to the file script.py 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 script.py. This is for Python’s internal use, and you may discard it if you like.