简体   繁体   中英

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

You have another module called "random" somewhere. Did you name your script "random.py"?

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 .

将您的文件名从random.py更改为任何其他名称,例如random_number.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.

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.

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

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

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