Python random number random module use guide

  • 2020-05-10 18:23:41
  • OfStack

The random module is the built-in module of Python, which has many functions besides generating the simplest random number.

random.random()

Used to generate a random floating point number between 0 and 1 in the range [0,10]


>>> import random
>>> random.random()
0.5038461831828231

random.uniform(a,b)

Returns a random floating point number between a,b, in the range [a,b] or [a,b], depending on the rounding of 4 and 5, a must be smaller than b.


>>> random.uniform(50,100)
76.81733455677832
>>> random.uniform(100,50)
52.98730193316595

random.randint(a,b)

Return an integer between a,b, range [a,b], note: the incoming parameter must be an integer, a1 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])

Returns an integer with an interval. You can set step. You can only pass in integers, random.randrange (10, 100, 2), which is equivalent to getting a random number from a sequence of [10, 12, 14, 16,... 96, 98].


>>> random.randrange(100)
58
>>> random.randrange(10,100,2)
54

random.choice(sequence)

Get a random element from the sequence, list, tuple, string all belong to sequence. Here sequence needs to be an ordered type. random.randrange (10,100,2) is equivalent in results to random.choice (range(10,100,2)).


>>> random.choice(("stone","scissors","paper"))
'stone'
>>> random.choice(["stone","scissors","paper"])
'scissors'
>>> random.choice("Random")
'm'

random.shuffle(x[,random])

Used to shuffle elements in a list, commonly known as shuffling. It changes the original sequence.


>>> 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)

The k 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']

The above methods are commonly used by Python, but there are many stories about random Numbers. Next time, I'm going to decompose


Related articles: