Python --- random module Usage Details, python --- random
Common Methods of random modules related to random operations:
Random () --- return 0-1 to see a random floating point number.
Call: random. random ()
For example:
>>> random.random()0.027383887147843344>>> random.random()0.5061348573341105>>> random.random()0.015448646863463922
Randint () --- returns a random integer.
Call: random. randint (a, B) (a <= B) returns the random number n, a <= n <= B
For example:
>>> random.randint(1, 10)6>>> random.randint(1, 10)3>>> random.randint(1, 10)7>>> random.randint(1, 10)8>>> random.randint(1, 10)9>>> random.randint(1, 10)9
Randrange () --- returns a random integer.
Call: random. randrange ([start], stop [, step]) to obtain a random value (the maximum value of this random value is stop-1) from the specified range according to the specified incremental count ),
For example, random. randrange (1, 10, 2) obtains a random number from [1, 3, 5, 7, 9 ].
>>> random.randrange(1,10, 2)3>>> random.randrange(1,10, 2)5>>> random.randrange(1,10, 2)7>>> random.randrange(1,10, 2)5>>> random.randrange(1,10, 2)3>>> random.randrange(1,10, 2)7
Choice () --- randomly obtain an element from a sequence.
Call: random. choice (sequence) (sequence refers to ordered sequence)
For example:
>>> random.choice([1,2,3,4,5,6])2>>> random.choice([1,2,3,4,5,6])3>>> random.choice([1,2,3,4,5,6])4>>> random.choice([1,2,3,4,5,6])4>>> random.choice([1,2,3,4,5,6])6>>> random.choice('hello word!')'d'>>> random.choice('hello word!')'w'>>> random.choice('hello word!')'r'>>> random.choice('hello word!')'o'>>> random.choice('hello word!')'o'>>> random.choice('hello word!')'l'>>> random.choice('hello word!')'!'
Sample () --- obtain the random value of the specified number from a sequence.
Call: random. sample (sequence, n)
For example:
>>> random.sample([1,2,3,4,5,6], 3)[4, 3, 2]>>> random.sample([1,2,3,4,5,6], 3)[3, 2, 6]>>> random.sample([1,2,3,4,5,6], 3)[3, 4, 5]>>> random.sample("hello world!", 3)['l', 'o', 'r']>>> random.sample("hello world!", 3)['!', 'd', 'e']>>> random.sample(("hello world!"), 3)['l', 'e', 'l']>>> random.sample(("hello world!"), 3)['l', 'o', 'w']>>> random.sample(("hello world!"), 3)['l', 'd', 'o']