I\'m having problems with Python\'s import random function. It seems that import random
and from random import random
are importing different thing
import random
includes the module into the namespace under the name 'random'.
from random import random
includes the function'random' from the namespace 'random' into the global namespace.
So in the first example, you would call random.random, and in the second, you would call random. Both would access the same function.
Similarly,
from random import randint
would import randint into the global namespace, so you could simply call randint instead of random.randint.
The problem is that there are two things called random here: one is the module itself, and one is a function within that module. You can't have two things with the same name in your namespace so you have to pick one or the other.
The random module contains a function named random()
, so you need to be aware of whether you have imported the module into your namespace, or imported functions from the module.
import random
will import the random module whereas from random import random
will specifically import the random function from the module.
So you will be able to do one of the following:
import random
a = random.random()
b = random.randint(1, 5)
# you can call any function from the random module using random.<function>
or...
from random import random, randint # add any other functions you need here
a = random()
b = randint(1, 5)
# those function names from the import statement are added to your namespace