简体   繁体   中英

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

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?

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.

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

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
>>>

You script is importing itself since it is named random.py and then trying to call itself as a method. Rename your script to something else (like test.py ) and it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM