Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a TypeError: 'module' object is not callable when trying to import the random module?

Tags:

python

I am using Python 2.6 and am trying to run a simple random number generator program (random.py):

import random

for i in range(5):

    # random float: 0.0 <= number < 1.0
    print random.random(),

    # random float: 10 <= number < 20
    print random.uniform(10, 20),

    # random integer: 100 <= number <= 1000
    print random.randint(100, 1000),

    # random integer: even numbers in 100 <= number < 1000
    print random.randrange(100, 1000, 2)

I'm now receiving the following error:

C:\Users\Developer\Documents\PythonDemo>python random.py
Traceback (most recent call last):
  File "random.py", line 3, in <module>
    import random
  File "C:\Users\Developer\Documents\PythonDemo\random.py", line 8, in <module>
    print random.random(),
TypeError: 'module' object is not callable

C:\Users\Developer\Documents\PythonDemo>

I've looked at the Python docs and this version of Python supports random. Is there something else I'm missing?

like image 533
coson Avatar asked Apr 20 '10 03:04

coson


3 Answers

Name your file something else. In Python a script is a module, whose name is determined by the filename. So when you start out your file random.py with import random you are creating a loop in the module structure.

like image 69
David Winslow Avatar answered Nov 07 '22 06:11

David Winslow


Rename your sample program file to myrandom.py or something. You are confusing import I would bet.

like image 39
Charles Avatar answered Nov 07 '22 05:11

Charles


Edit: Looks like you have same name with built-in random module, so you should change filename to something else as others suggested

but after that, you still need to change your codes to initiate Random class

rand=random.Random()

rand.uniform(10, 20)

and also for others because you are calling module itself, instead of Random class

>>> for i in range(5):
...     # random float: 0.0 <= number < 1.0
...     print rand.random(),
...
...     # random float: 10 <= number < 20
...     print rand.uniform(10, 20),
...
...     # random integer: 100 <= number <= 1000
...     print rand.randint(100, 1000),
...
...     # random integer: even numbers in 100 <= number < 1000
...     print rand.randrange(100, 1000, 2)
...
0.024357795662 12.3296648076 886 478
0.698607283236 16.7373296747 245 638
0.69796131038 14.739388574 888 482
0.543171786714 11.3463795339 106 744
0.752849564435 19.4115177118 998 780
>>>
like image 31
2 revs Avatar answered Nov 07 '22 07:11

2 revs