Importing specific names from a module

suggest change

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))      # one possible result: 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.141592653589793

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

try:
    random.randrange(1, 10)  # works only if "import random" has been run before
except NameError:
    print("NameError: name 'random' is not defined")
NameError: name 'random' is not defined

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

import random
random.randrange(1, 10)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents