Python random number random Module User Guide, python random number random
The random module is a Python module. In addition to generating the simplest random number, it also has many functions.
Random. random ()
Used to generate a 0 ~ Random floating point number between 1, in the range of [0, 10
>>> import random>>> random.random()0.5038461831828231
Random. uniform (a, B)
Returns a random floating point number between a and B. The value range is [a, B] or [a, B). It is determined that a is not necessarily smaller than B.
>>> random.uniform(50,100)76.81733455677832>>> random.uniform(100,50)52.98730193316595
Random. randint (a, B)
Returns an integer between a and B in the range of [a, B]. Note: The input parameter must be an integer, And a must be smaller than B.
>>> random.randint(50,100)54>>> random.randint(100,50) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> random.randint(100,50) File "C:\Python27\lib\random.py", line 242, in randint return self.randrange(a, b+1) File "C:\Python27\lib\random.py", line 218, in randrange raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)ValueError: empty range for randrange() (100,51, -49)>>> random.randint(50.5,100.6) Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> random.randint(50.5,100.6) File "C:\Python27\lib\random.py", line 242, in randint return self.randrange(a, b+1) File "C:\Python27\lib\random.py", line 187, in randrange raise ValueError, "non-integer arg 1 for randrange()"ValueError: non-integer arg 1 for randrange()
Random. randrang ([start], stop [, step])
Return an integer in the interval. You can set step. Only integers can be input. random. randrange (10,100, 2). The result is equivalent ,... 96, 98] obtain a random number from the sequence.
>>> random.randrange(100)58>>> random.randrange(10,100,2)54
Random. choice (sequence)
Obtain a random element from the sequence. The list, tuple, and string all belong to sequence. The sequence here must be of the ordered type. Random. randrange (10,100, 2) is equivalent to random. choice (range (10,100, 2) in the result.
>>> random.choice(("stone","scissors","paper"))'stone'>>> random.choice(["stone","scissors","paper"])'scissors'>>> random.choice("Random")'m'
Random. shuffle (x [, random])
Used to disrupt the elements in the list, commonly known as shuffling. The original sequence is modified.
>>> poker = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]>>> random.shuffle(poker)>>> poker['4', '10', '8', '3', 'J', '6', '2', '7', '9', 'Q', '5', 'K', 'A']
Random. sample (sequence, k)
Returns k elements from a specified sequence as a segment. The sample function does not modify the original sequence.
>>> poker = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]>>> random.sample(poker,5)['4', '3', '10', '2', 'Q']
These methods are commonly used in Python, but there are still many stories about random numbers. Next decomposition ~