Search notes:
Python standard library: random
The random
library is used to generate pseudo random numbers.
In order to create random numbers for cryptographic uses, the secrets
module should be used.
Properties and methods import random
for e in sorted(dir(random), key=lambda s: s.lower()): print(e)
__all__
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
__spec__
_accumulate
_acos
_bisect
_ceil
_cos
_e
_exp
_floor
_index
_inst
_isfinite
_log
_ONE
_os
_pi
_random
_repeat
_Sequence
_Set
_sha512
_sin
_sqrt
_test
_test_generator
_urandom
_warn
betavariate
BPF
choice
Choose a random element from a sequence.
choices
expovariate
gammavariate
gauss
getrandbits
getstate
The current internal state of the generator. The returned object can be passed to setstate
.
LOG4
lognormvariate
normalvariate
NV_MAGICCONST
paretovariate
randbytes
Generate n
random bytes.
randint
Random
random
Generate a uniformly distributed random float in the range 0 <= X < 1
using Mersenne Twister .
randrange
RECIP_BPF
sample
seed
setstate
SG_MAGICCONST
shuffle
SystemRandom
triangular
TWOPI
uniform
vonmisesvariate
weibullvariate
random()
random.random()
returns a random number in the range 0 … 1.
import random
random.seed('tq84')
for _ in range(10):
print(random.random())
#
# 0.15919424924070613
# 0.4948802376988537
# 0.6212905728914367
# 0.5917838981303569
# 0.9762144093757996
# 0.22690315108652592
# 0.27237380613393625
# 0.6180574649914569
# 0.34173704578994535
# 0.7690121980201846
choice
random.choice(seq)
returns a random element from a sequence.
#!/usr/bin/python3
import random
lst = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
for i in range(0, 10):
print(random.choice(lst))
sample
import random
#
# Choose two (distinct) random fruits, in random order:
#
for fruit in random.sample( ['apple', 'pear', 'orange', 'cherry', 'banana'], 2):
print(fruit)