import random imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.
Doing the import this way this requires you to use the syntax random.random().
The random function can also be imported from the module separately:
from random import random
This allows you to then just call random() directly.
Videos
» pip install random2
import random imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.
Doing the import this way this requires you to use the syntax random.random().
The random function can also be imported from the module separately:
from random import random
This allows you to then just call random() directly.
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
By naming your script random.py, you've created a naming conflict with the random standard library module.
When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does import random, you're effectively running a second copy of the script as the random module.
When the random module runs import random, it means that random.random will also be a reference to your module. So when you attempt to call the random.random() standard library function, you're actually attempting to call the module object resulting in the error you got.
If you rename your script to something else, the problem should go away.
Even I faced the same problem. I have renamed my python file from random.py to shuffle.py. This didn't work out. Then I changed the version then it worked. This may help a bit. Python version : 3.6.7 replace import random; to import random2;