The random module is a Python self-contained module that has many functions in addition to generating the simplest random numbers.
Random.random ()
Used to generate a random floating-point number between a 0~1, the range [0,10
>>> import Random
>>> random.random ()
0.5038461831828231
Random.uniform (A,B)
Returns a random floating-point number between a,b, a range [a,b] or [a,b], depending on rounding, and 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, range [a,b] between a,b, note: The incoming argument must be an integer, and a must be smaller than B
>>> random.randint (50,100) >>> random.randint (100,50) traceback (Mo St recent called 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 Randrang E raise ValueError, "empty range for Randrange () (%d,%d,%d)"% (Istart, istop, width) valueerror:empty range for Randr Ange () (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 F" or Randrange () "Valueerror:non-integer Arg 1 for Randrange ()
Random.randrang ([start], stop[, step])
Returns an integer in a range that can be set by step. Only integers can be passed in, Random.randrange (10, 100, 2), resulting in the equivalent from [10, 12, 14, 16, ... 96, 98] sequence to obtain a random number.
>>> random.randrange
>>> random.randrange (10,100,2)
54
Random.choice (Sequence)
Randomly get an element from a sequence, list, tuple, string belong to sequence. The sequence here need to be an ordered type. Random.randrange (10,100,2) is equivalent to Random.choice (range (10,100,2) on the result.
>>> Random.choice ("Stone", "scissors", "paper"))
' stone '
>>> random.choice (["Stone,"] Scissors "," paper "])
' scissors '
>>> random.choice (" random ")
' m '
Random.shuffle (X[,random])
Used to upset the elements in the list, commonly known as shuffle. Will modify the original sequence.
>>> poker = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "Ten", "J", "Q", "K"]
>>> random.shuffle (poker)
>>> Poker
[' 4 ', ' Ten ', ' 8 ', ' 3 ', ' J ', ' 6 ', ' 2 ', ' 7 ', ' 9 ', ' Q ', ' 5 ', ' K ', ' A ']
Random.sample (Sequence,k)
A random fetch of k elements from a specified sequence is returned as a fragment, and the sample function does not modify the original sequence.
>>> poker = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "Ten", "J", "Q", "K"]
>>> random.sample (poker,5
[' 4 ', ' 3 ', ' Ten ', ' 2 ', ' Q ']
These are some of the methods used by Python, but there are a lot of stories about random numbers. Let's ~