random.randint error
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 e开发者_如何学Pythonrror: 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?
You have another module called "random" somewhere. Did you name your script "random.py"?
error is related to file Name
probably name of the python file or other file in your project is random.py, So after changing it, there wont be any error
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
.
Change your file name from random.py
to any thing else like random_number.py
that resolve your issue.
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.
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
import numpy as np
n = 0
while n <= 50:
n = n+1
a = np.random.randint(1, 16)
b = np.random.randint(1, 5)
print n, ". ", a, "-", b, "= "
AttributeError: 'module' object has no attribute 'randint' same error show me too so that i'm doing mistake import random but my file name also random.py so i change file name to ranom_data.py so it's work simple example share with you
import random
x = random.randint(1,10)
print(x)
so it's work
精彩评论