python random number random

 

# (1) a random decimal
Import Random
Print (random.random ()) # random decimal between greater than 0 and less than 1
'' '
0.9441832228391154
' ''

print (random.uniform (0,9)) # 0 is greater than a random decimal less than 9, "0" as the lower limit, "9" is the upper limit
'' 'results:
1.646583891572416
' ''
 

# (2) random integer
print (random.randint (1,5)) # is greater than a random integer equal to 1 and less than 5
'' 'results:
5
' ''
 

print random.randint (12,20) # random number generated by a: 12 <= a = <20

print random.randint (12,20) # random number generated by a: 结果永远是20

print random.randint(12,20)      #该语句是错误的

 

 

 

print (random.randrange (1,10,2)) # a random greater than or equal to 1 and less than or equal to an odd number between 10, wherein the 2 represents the base increment
'' 'results:
3
' ''


 

# (3) returns a random
print (random.choice ([ '123' , 'abc', 52, [1,2]])) # Returns any random parameter list element
'' 'results:
ABC
' ''

print (random.sample ([ '123' , 'abc', 52, [1,2]], 2)) # Returns the list of arguments of any random two elements, two parameters specify the number of returned
'' 'results:
[ '123', 52]
'' '


 

# (4) disrupt the order of the list
LIS = [1,2,5,7,9,10]
random.shuffle (LIS)
Print (LIS)
'' 'results:
[2, 1, 10, 5, 9, 7 ]
'' '

(5) the verification code generator

import random

def random_num():
    code = ''
    for i in range(4):
        ran1 = random.randint(0,9)
        ran2 = chr(random.randint(65,90))
        add = random.choice([ran1,ran2])
        code = ''.join([code,str(add)])
    return code

rand_n = random_num ()
print (rand_n)

 

Random character:
>>> Import Random
>>> The random.choice ( 'ABCDEFG #% ^ & * F')
'D'

Selecting a plurality of characters specified number of characters:
>>> Import Random
random.sample ( 'ABCDEFGHIJ',. 3) 
[ 'A', 'D', 'B']

 

Selecting a plurality of characters consisting of a certain number of new string of characters:
>>> Import Random
>>> Import String
>>> string.join (random.sample ([ 'A', 'B', 'C', 'D ',' E ',' F ',' G ',' H ',' I ',' J '],. 3)). R & lt
eplace ( "", "")
' FIH '

Randomly selected strings:
>>> Import Random
>>> The random.choice ([ 'Apple', 'PEAR', 'Peach', 'Orange', 'Lemon'])
'Lemon'

洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]

Guess you like

Origin blog.csdn.net/Jiazengzeng/article/details/90607530