I have some code that looks something like this:
import random
n = 0
while n <= 50:
n = n+1
a = random.randint(1, 16)
b = random.randint(1, 5)
print n, ". ", a, "-", b, "= "
For some reason, when running it, I get the following error: AttributeError: 'module' object has no attribute 'randint'
. However, I have no problems when running the same random.randint queries in IDLE. How can I fix this?
Change your file name from
random.py
to any thing else likerandom_number.py
that resolve your issue.You have another module called "random" somewhere. Did you name your script "random.py"?
If the filename you are working on or another file in your project is named "random.py", your program tries to find the randint function in that location, and can't find it.
You should change any filenames random.py to something else. After this, "import random" will resolve to the "actual" random.py module and you will successfully use randint or any other function in the module.
You can easily solve the problem using numpy array , just doing as follows
Check your files name! In your case “random” is key word, you can not use "random" as a file name. Take care that no files are named
random.py
.Code works fine for me, so you must have another module called "random" on your PYTHONPATH
Try a dir(random) to see whats in it. This might make it easier to remember why you have another module named random and where it is.