Using Modules
A module is an external extension that can be loaded to a script. It can be seen as a plug-in. Many of them already come with the official Python distribution; others have to be loaded and installed manually. For Python, there are many modules available for all purposes, but how is it possible to find out what has already been installed? The easiest way is to directly call the Python interpreter from a terminal. Linux and OS X have easy access via Bash or the Terminal application. Open a shell editor, e.g. Bash, and type:
prompt> python
A message shows you the currently installed version of Python and a >>> prompt. At the prompt just enter “help(‘modules’)
”.
Screenshot from a terminal application with listed modules under OS X.
It takes a little time, but then you can look for “random” and “math”. These two are probably the most often used modules.
Python makes it very easy to load a module to a scene. Within your script you only have to type “import” and the name of the appropriate module:
import random
“Random” has a lot of features to generate different kinds of random numbers, strings or even ranges and the functions can be used in Python’s typical notation:
random.random() | Creates a float between 0 and 1 |
---|---|
random.randint(a, b) | Creates a random integer between a and b |
random.uniform(a, b) | Creates a random float between a and b |
random.choice([list]) | Picks a random number/element from a list |
random.randrange(start, stop, step) | Creates a random range between start and stop |
The other important module is math. Python is not capable of using functions like sine, cosine or square root. They are all provided by this extension and have to be imported:
import.math
Similar to the random module, the “math” prefix has to be written to a function before it can be executed:
math.sin() | math.cos() | math.sqrt() | math.exp() |
math.tan() | math.sinh() | math.cosh() | math.log() |
The math module does not only provide trigonometric and power or logarithmic functions. There are also functions for angular conversions and the constants "Pi" and "e" included. For complex numbers you can call
import cmath
If you have to load more than one module simply import them one after the other. With the PYTHONPATH
environment variable it is also possible to specify additional search paths. This is useful for 3rd party Python modules, because they do not have to be installed under Python’s default directory, but can be anywhere on your hard disk. The creation/modification of environment variables is different for each operating system, so please take a look at your system’s help documents.