Question 7.11: Using Modules You want to use a Python module in your progra......

Using Modules

You want to use a Python module in your program.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the import command:

import random

Discussion

There is a very large number of modules (sometimes called libraries) available for Python. Many are included with Python as standard and others can be downloaded and installed into Python.

Standard Python libraries include modules for random numbers, database access, various Internet protocols, object serialization, and many more.

One consequence of having so many modules is that there is the potential for conflict—for example, if two modules have a function of the same name. To avoid such conflicts, when importing a module, you can specify how much of the module is accessible.

For example, if you just use a command like this:

import random

there is no possibility of any conflicts because you will only be able to access any functions or variables in the module by prefixing them with random.. (Incidentally, we will be meeting the random package in the next recipe.)

If, on the other hand, you use the following command, everything in the module will be accessible without your having to put anything in front of it. Unless you know what all the functions are in all the modules you are using, there is a much greater chance of conflict.

from random import *

In between these two extremes, you can explicitly specify those components of a module that you need within a program so that they can be conveniently used without any prefix.

For example:

>>> from random import randint
>>> print(randint(1,6))
2
>>>

A third option is to use the as keyword to provide a more convenient or meaningful name for the module when referencing it.

>>> import random as R
>>> R.randint(1, 6)

See Also

For a definitive list of the modules included with Python, see http://docs.python.org/2/library/.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.4

Verified Answer:

Define a class and provide it with the member vari...