Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (47.6k points)

I'm having problems with Python's import random function. It seems that import random and from random import random are importing different things. I am currently using Python 2.7.3

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 

Type "copyright", "credits" or "license()" for more information. >>> random() 

Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> random() 

NameError: name 'random' is not defined 

>>> random.randint(1,5) 

Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> random.randint(1,5) 

NameError: name 'random' is not defined 

>>> import random 

>>> random() 

Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> random() 

TypeError: 'module' object is not callable

>>> random.randint(1,5) 

>>> from random import random 

>>> random() 

0.28242411635200193 

>>> random.randint(1,5) 

Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> random.randint(1,5)

AttributeError: 'builtin_function_or_method' object has no attribute 'randint' 

>>>

1 Answer

0 votes
by (106k points)

The problem you are getting because of 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.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
4 answers
asked Mar 31, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Feb 26, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)

Browse Categories

...