简体   繁体   English

random.randint 错误

[英]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' .出于某种原因,在运行它时,我收到以下错误: AttributeError: 'module' object has no attribute 'randint' However, I have no problems when running the same random.randint queries in IDLE.但是,在 IDLE 中运行相同的 random.randint 查询时我没有问题。 How can I fix this?我怎样才能解决这个问题?

You have another module called "random" somewhere.您在某处有另一个名为“随机”的模块。 Did you name your script "random.py"?您是否将脚本命名为“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.py更改为任何其他名称,例如random_number.py可以解决您的问题。

Code works fine for me, so you must have another module called "random" on your PYTHONPATH代码对我来说很好用,所以你的 PYTHONPATH 上必须有另一个名为“random”的模块

Try a dir(random) to see whats in it.尝试 dir(random) 以查看其中的内容。 This might make it easier to remember why you have another module named random and where it is.这可能会使您更容易记住为什么有另一个名为 random 的模块以及它的位置。

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.如果您正在处理的文件名或项目中的另一个文件名为“random.py”,则您的程序会尝试在该位置查找 randint 函数,但找不到它。

You should change any filenames random.py to something else.您应该将任何文件名 random.py 更改为其他名称。 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.在此之后,“import random”将解析为“实际”random.py 模块,您将成功使用randint或模块中的任何其他函数。

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可能你项目中的python文件或其他文件的名字是random.py,所以改了之后就不会出错了

You can easily solve the problem using numpy array , just doing as follows您可以使用 numpy array 轻松解决问题,只需执行以下操作

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 AttributeError: 'module' object has no attribute 'randint' 同样的错误也显示给我,所以我做错了 import random 但我的文件名也是 random.py 所以我将文件名更改为 ranom_data.py 所以它的工作简单示例与共享你

import random
x = random.randint(1,10)
print(x)

so it's work所以这是工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM