Python random.randint 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4178648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:38:18  来源:igfitidea点击:

random.randint error

pythonpython-2.x

提问by foobar

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?

出于某种原因,在运行它时,我收到以下错误:AttributeError: 'module' object has no attribute 'randint'. 但是,在 IDLE 中运行相同的 random.randint 查询时我没有问题。我怎样才能解决这个问题?

回答by Ignacio Vazquez-Abrams

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

您在某处有另一个名为“随机”的模块。您是否将脚本命名为“random.py”?

回答by toc777

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. This might make it easier to remember why you have another module named random and where it is.

尝试 dir(random) 以查看其中的内容。这可能会使您更容易记住为什么有另一个名为 random 的模块以及它的位置。

回答by Sebastien

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

回答by Murat Simav

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. After this, "import random" will resolve to the "actual" random.py module and you will successfully use randintor any other function in the module.

您应该将任何文件名 random.py 更改为其他名称。在此之后,“import random”将解析为“实际”random.py 模块,您将成功使用randint或模块中的任何其他函数。

回答by Vivekanand Panda

Change your file name from random.pyto any thing else like random_number.pythat resolve your issue.

将您的文件名更改random.py为任何其他类似的名称,以random_number.py解决您的问题。

回答by Fastest_Smartest

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, "= "