Python随机函数 [英] Python random function
问题描述
我遇到Python的导入随机函数问题。似乎随机导入随机中的 import random
和正在导入不同的东西。我目前正在使用Python 2.7.3
I'm having problems with Python's import random function. It seems that import random
and from random import random
are importing different things. I am currently using Python 2.7.3
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> random()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
random()
NameError: name 'random' is not defined
>>> random.randint(1,5)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
random.randint(1,5)
NameError: name 'random' is not defined
>>> import random
>>> random()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
random()
TypeError: 'module' object is not callable
>>> random.randint(1,5)
2
>>> from random import random
>>> random()
0.28242411635200193
>>> random.randint(1,5)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
random.randint(1,5)
AttributeError: 'builtin_function_or_method' object has no attribute 'randint'
>>>
推荐答案
随机导入
导入随机模块,其中包含与随机数生成有关的各种事项。其中有random()函数,它生成0到1之间的随机数。
import random
imports the random module, which contains a variety of things to do with random number generation. Among these is the random() function, which generates random numbers between 0 and 1.
以这种方式进行导入这需要你使用语法 random.random()
。
Doing the import this way this requires you to use the syntax random.random()
.
随机函数也可以单独从模块导入:
The random function can also be imported from the module separately:
from random import random
这样你就可以直接调用 random()
。
This allows you to then just call random()
directly.
这篇关于Python随机函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!