Python Language Importing modules Importing specific names from a module


Instead of importing the complete module you can import only specified names:

from random import randint # Syntax "from MODULENAME import NAME1[, NAME2[, ...]]"
print(randint(1, 10))      # Out: 5

from random is needed, because the python interpreter has to know from which resource it should import a function or class and import randint specifies the function or class itself.

Another example below (similar to the one above):

from math import pi
print(pi)                  # Out: 3.14159265359

The following example will raise an error, because we haven't imported a module:

random.randrange(1, 10)    # works only if "import random" has been run before


NameError: name 'random' is not defined

The python interpreter does not understand what you mean with random. It needs to be declared by adding import random to the example:

import random
random.randrange(1, 10)