Python 随机函数

16 投票
9 回答
139694 浏览
提问于 2025-04-17 16:31

我在使用Python的随机数功能时遇到了一些问题。看起来 import randomfrom random import random 导入的东西不太一样。我现在使用的是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'
>>> 

9 个回答

9

问题在于这里有两个东西都叫“random”:一个是模块本身,另一个是这个模块里面的一个函数。在你的命名空间里不能有两个同名的东西,所以你必须选择一个来使用。

21

在Python中,有一个叫做random模块,里面有一个函数叫做random()。所以你需要注意一下,自己是否已经把这个模块导入到你的代码里,或者是只导入了模块里的某些函数。

如果你写import random,那么就是把整个random模块都导入进来了;而如果你写from random import random,那就是只把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
32

import random 是用来引入一个叫做 random 的模块,这个模块里面有很多和随机数生成有关的功能。其中一个功能就是 random() 函数,它可以生成0到1之间的随机数。

用这种方式引入模块后,你需要用 random.random() 这种写法来调用它。

你也可以单独从这个模块引入 random 函数:

from random import random

这样的话,你就可以直接使用 random() 来调用它了。

撰写回答