Random number generation
First we need to introduce random in the program "import random as R"
R.random () is used to generate a random floating-point number,
Print (R.random ())
R.uniform (10,20), generates a random floating-point number, if A>b A is the upper bound and B is the lower limit. If a<b, then B is the upper limit
Print (R.uniform (10,20)) Print (R.uniform (20,10))
#如果没有给定a, b that would be an error.
>>> print (R.uniform ())
Traceback (most recent):
File "<pyshell#5>", line 1, in <module>
Print (R.uniform ())
Typeerror:uniform () Missing 2 required positional arguments: ' A ' and ' B '
>>> print (R.randint ())
R.randint (A, A, b), generates a random integer, A is the lower bound, and a is the upper limit. Lower limit must be less than upper limit
>>> print (R.randint ()) Traceback (most recent): File <pyshell# 6> , Line 1, in <module> Span style= "COLOR: #0000ff" >print (R.randint ()) Typeerror:randint () missing 2 Required positional arguments: " a " and " b " >>> print (R.randint (1,10 1
>>> Print (R.randint (10,1))
Traceback (most recent):
File "<pyshell#8>", line 1, in <module>
Print (R.randint (10,1))
File "D:\python\lib\random.py", line 222, in Randint
Return Self.randrange (A, b+1)
File "D:\python\lib\random.py", line $, in Randrange
Raise ValueError ("Empty range for Randrange () (%d,%d,%d)"% (Istart, istop, width))
Valueerror:empty range for Randrange () (10,2,-8)
>>>
R.randrange (A,B,1OR2), randomly extracting odd even numbers within a specified range, 1 odd 2 even
>>> R.randrange (0,10,2) 6>>> r.randrange (0,10,1) 1>>> R.randrange (0,10,1)
R.choice (' QWERTUIOPOLKJHGFFDSA ') and remove a character
Print (R.choice ('qwertyuiop[]lkjhgfdsazxcvbnm')) kprint(R.choice ( ' qwertyuiop[]lkjhgfdsazxcvbnm ' ) nprint(R.choice ('qwertyuiop[]lkjhgfdsazxcvbnm' ) )) T
R.sample (str,num), num characters are randomly output and num must be less than or equal to Len (str)
#is less than the character length>>> R.sample ('QWEASD', 2) ['D','Q']#is greater than the character length>>> R.sample ('QWEASD', 8) Traceback (most recent): File"<pyshell#25>", Line 1,inch<module>R.sample ('QWEASD', 8) File"D:\python\lib\random.py", line 319,inchSampleRaiseValueError ("Sample larger than population or is negative") valueerror:sample larger than populationor isNegative#is equal to the character length>>> R.sample ('QWEASD', 6) ['s','D','a','e','W','Q']>>>
Shuffle, that is, random sort
>>> items = [1,2,3,4,5,6] >>> r.shuffle (items) >>> Items [3, 6, 1, 5, 2, 4]
Acquisition of Python,random random numbers