Python“导入随机”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13813164/
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 09:40:59  来源:igfitidea点击:

Python "import random" Error

pythonrandom

提问by MalyG

As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:

您可能从我之前的帖子中了解到,我正在学习 Python。这次我有一个小错误,我认为是 Python 本身的构建。使用以下内容时:

import random
number = random.randint(1,10000)

Python gives me this error:

Python给了我这个错误:

File "C\Users\name\Documents\Python\random.py", line 5, in (module)
  print random.random()
TypeError: 'module' object is not callable

Every time I try to run it. Me no understand. Any help would be much appreciated!

每次我尝试运行它。我不明白。任何帮助将非常感激!

EDIT: The two lines of code I'm trying to run:

编辑:我试图运行的两行代码:

import random
print random.randint(1,100)

That's it. And it gives me the same error.

就是这样。它给了我同样的错误。

采纳答案by James Henstridge

By naming your script random.py, you've created a naming conflict with the randomstandard library module.

通过命名您的脚本random.py,您已经与random标准库模块产生了命名冲突。

When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does import random, you're effectively running a second copy of the script as the randommodule.

当您尝试运行脚本时,包含脚本的目录将被添加到模块导入路径的开头。因此,当您的脚本执行此操作时import random,您实际上是在将脚本的第二个副本作为random模块运行。

When the randommodule runs import random, it means that random.randomwill also be a reference to your module. So when you attempt to call the random.random()standard library function, you're actually attempting to call the module object resulting in the error you got.

random模块运行时import random,这意味着它random.random也将是对您的模块的引用。因此,当您尝试调用random.random()标准库函数时,实际上是在尝试调用导致错误的模块对象。

If you rename your script to something else, the problem should go away.

如果您将脚本重命名为其他名称,问题应该会消失。

回答by William Cheung

I am using pycharm and I had to take the additional step to import the methods from random. In my case:

我正在使用 pycharm,我不得不采取额外的步骤来导入方法from random。就我而言:

import random
 from random import choice

回答by Mounika

Even I faced the same problem. I have renamed my python file from random.py to shuffle.py. This didn't work out. Then I changed the version then it worked. This may help a bit. Python version : 3.6.7 replace import random; to import random2;

甚至我也面临同样的问题。我已将我的 python 文件从 random.py 重命名为 shuffle.py。这没有成功。然后我更改了版本然后它起作用了。这可能会有所帮助。Python 版本:3.6.7 替换导入随机;导入 random2;

回答by Shashank Sharma

The simple answer: Change your filename from "random.py" to something else as it is conflicting with random library.

简单的答案:将您的文件名从“random.py”更改为其他名称,因为它与随机库冲突。