Python“导入随机"错误 [英] Python "import random" Error

查看:89
本文介绍了Python“导入随机"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可能从我以前的文章中知道,我正在学习Python.这次我有一个小错误,我认为是与此Python本身的版本有关.使用以下命令时:

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:

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

Python给我这个错误:

Python gives me this error:

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!

我尝试运行的两行代码:

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.

推荐答案

通过命名脚本random.py,您已经与random标准库模块创建了命名冲突.

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

当您尝试运行脚本时,包含该脚本的目录将被添加到模块导入路径的开头.因此,当脚本执行import random时,您将有效地运行脚本的第二个副本作为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 random module.

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

When the random module runs import random, it means that random.random will 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.

如果将脚本重命名为其他名称,则问题应消除.

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

这篇关于Python“导入随机"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆