Several random function usages in the random module.
Introduce the Random module:
1 Import Random
1.random.random ()
This function is used to generate a random floating-point number from 0 to 1:0 <= N < 1.0, which is within the range of [0,1].
1 Print (Random.random ()) 2 Print (Random.random ())
0.45076499722734553
0.05150313289840169
2.random.uniform (A, B)
Used to generate a random floating-point number within a specified range of two parameters one of which is the upper limit and one is the lower limit. If a>b, the generated random number n:b <= n <= A. If a < b, then a <= n <= b.
1 Print (Random.uniform (2, 8)) 2 Print (Random.uniform (8, 2))
4.83958910395014
7.55945593444834
3.random.randint (A, B)
Used to generate an integer within a specified range, where parameter A is the lower bound, parameter B is the upper bound, and the generated random number n:a <= n <= B.
1 Print (Random.randint (2, 8)) 2 Print (Random.randint (2, 8)).
4
3
4.random.randrange
The function prototype for Random.randrange is: Random.randrange (Start, stop[, step]), which gets a random number from the specified range, in the collection incremented by the specified cardinality. such as: Random.randrange (10, 100, 2), equivalent from [10, 12, 14, 16, ... 96, 98] gets a random number in the sequence. Random.randrange (10, 100, 2) is equivalent to Random.choice (range (10, 100, 2)) on the result.
1 Print (Random.randrange (Ten, 2)) 2 Print (Random.randrange (10, 50, 2))
46
18
5.random.choice
Random.choice gets a random element from the sequence. Its function prototype is: Random.choice (sequence). The parameter sequence represents an ordered type. Sequence is not a specific type in Python, but rather refers to a series of types, List,tuple, strings belong to sequence.
1name = ['Mrs. Chow .','Mr. Li','boss Sun','Money Boss','Harry','Zhao Four','Zhang San']2 Print(Random.choice (name))
Mr. Li
6.random.shuffle
The function prototype for random.shuffle is: random.shuffle (x[, Random]), which is used to disrupt elements in a list.
1 li = [1, 2, 3, 4, 5, 6, 7, 8, 9]2random.shuffle (LI)3print(LI)
[2, 1, 9, 5, 7, 4, 6, 3, 8]
7.random.sample
The function prototype for random.sample is: random.sample (sequence, k), which randomly fetches fragments of the specified length from the specified sequence. The sample function does not modify the original sequence.
1 li = [1, 2, 3, 4, 5, 6, 7, 8, 9]2 s = Random.sample (Li, 4)3print
(s)
4
print(LI)
[2, 7, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
This article is from the link: http://www.360doc.com/content/14/0430/11/16044571_373443266.shtml
python--Random number function