Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "import random" Error

Tags:

python

random

As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:

import random
number = random.randint(1,10000)

Python gives me this error:

File "C\Users\name\Documents\Python\random.py", line 5, in (module)
  print random.random()
TypeError: 'module' object is not callable

Every time I try to run it. Me no understand. Any help would be much appreciated!

EDIT: The two lines of code I'm trying to run:

import random
print random.randint(1,100)

That's it. And it gives me the same error.

like image 543
MalyG Avatar asked Dec 16 '22 16:12

MalyG


1 Answers

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.

like image 186
James Henstridge Avatar answered Jan 02 '23 01:01

James Henstridge