Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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.

...

“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

...

Code Block
themeEclipse
languagepython
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

...

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 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.