当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python random.getrandbits()用法及代码示例


random模块用于在Python中生成随机数。实际上不是随机的,而是用于生成伪随机数的。这意味着可以确定这些随机生成的数字。

getrandbits()

getrandbits()方法的random模块用于返回具有指定位数的整数。结果中所需的位数作为方法中的参数传递。

例子:

Input:getrandbits(4)
Output:14
(the binary equivalent of 14 is 1110 which has 4 bits)

Input:getrandbits(16)
Output:60431
(the binary equivalent of 14 is 1110110000001111 
which has 16 bits)

范例1:

# import the random module 
import random 
  
# a random number with 4 bits 
print(random.getrandbits(4)) 
  
# a random number with 16 bits 
print(random.getrandbits(16))

输出:

10
49195

范例2:

# import the random module 
import random 
  
# 5 random number with 4 bits 
for i in range(4):
    print(random.getrandbits(4))

输出:

10
0
1
14

相关用法


注:本文由纯净天空筛选整理自Yash_R大神的英文原创作品 random.getrandbits() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。