Why can I get a TypeError object: 'module' cannot be called when trying to import a random module?

I am using Python 2.6 and 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) 

Now I get 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 looked at Python docs and this version of Python supports random ones. Is there anything else I am missing?

+4
source share
4 answers

Call your file something else. In Python, a script is a module whose name is determined by the name of the file. Therefore, when you start your random.py file with import random , you create a loop in the module structure.

+15
source

Rename your sample program file to myrandom.py or something like that. You mix imports, I would supply.

+5
source

Change It looks like you have the same name with a built-in random module, so you should change the file name to something else as others suggested

but after that you still need to change the codes to run the Random class

 rand=random.Random() rand.uniform(10, 20) 

as well as for others, because you are calling the module itself, not the 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 >>> 
+2
source

You script import yourself, as it is called random.py , and then it tries to call itself as a method. Rename the script to something else (e.g. test.py ) and it will work.

+1
source

Source: https://habr.com/ru/post/1307408/


All Articles