Python随机函数

2024-04-26 00:45:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python的import random函数有问题。似乎import randomfrom random import random正在导入不同的内容。我目前正在使用Python2.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'
>>> 

Tags: inimportmostislinenotrandomcall
3条回答

import random导入random模块,其中包含与随机数生成有关的各种操作。其中有random()函数,它生成0到1之间的随机数。

以这种方式进行导入需要使用语法random.random()

随机函数也可以从模块中单独导入:

from random import random

这允许您直接调用random()

random module包含一个名为random()的函数,因此您需要知道是已将模块导入到命名空间中,还是已从模块导入函数。

import random将导入随机模块,而from random import random将专门从模块导入随机函数。

因此,您将能够执行以下操作之一:

import random
a = random.random()
b = random.randint(1, 5)
# you can call any function from the random module using random.<function>

或者。。。

from random import random, randint   # add any other functions you need here
a = random()
b = randint(1, 5)
# those function names from the import statement are added to your namespace

问题是这里有两种东西叫做随机:一种是模块本身,另一种是模块内的函数。名称空间中不能有两个同名的对象,因此必须选择其中一个。

相关问题 更多 >