Random module and pythonrandom Module
As follows:
#! /Usr/bin/env python # encoding: utf-8import sysimport platformprint (platform. python_version () print (sys. version) import randomprint (random. random () #0.6445010863311293 # random. random () is used to generate a random number of points from 0 to 1: 0 <= n <1.0 print (random. randint (1, 7) #4 # random. randint () function prototype: random. randint (a, B) is used to generate an integer in the specified range. # Where parameter a is the lower limit, parameter B is the upper limit, and the generated random number n: a <= n <= bprint (random. randrange (1, 10) #5 # random. randrange function prototype: random. randrange ([start], stop [, step]), # obtain a random number from the set that increments by the specified base number within the specified range. For example: random. randrange (10,100, 2), # The result is equivalent to obtaining a random number from the [10, 12, 14, 16,... 96, 98] sequence. # Random. randrange (10,100, 2) is equivalent to random. choice (range (10,100, 2) in the result. Print (random. choice ('liukuni') # I # random. choice gets a random element from the sequence. # Its function prototype is random. choice (sequence ). The sequence parameter indicates an ordered type. # It should be noted that sequence is not a specific type in python, but a series of types. # List, tuple, and string all belong to sequence. For sequence, see the python manual data model chapter. # Below are some examples of using choice: print (random. choice ("Learn Python") # Learn print (random. choice (["JGood", "is", "a", "handsome", "boy"]) # Listprint (random. choice ("Tuple", "List", "Dict") # Listprint (random. sample ([1, 2, 3, 3], 3) # [1, 2, 5] # random. the sample function is prototype: random. sample (sequence, k), which randomly obtains a piece of the specified length from the specified sequence. The sample function does not modify the original sequence.
Practical application:
#! /Usr/bin/env python # encoding: utf-8import randomimport string # random INTEGER: print (random. randint (100) #70 # randomly select an even number from 0 to: print (random. randrange (0,101, 2) #4 # random floating point number: print (random. random () #0.2746445568079129 print (random. uniform (1, 10) #9.887001463194844 # random character: print (random. choice ('abcdefg & # % ^ * F') # f # select a specific number of characters from multiple characters: print (random. sample ('abcdefghj', 3) # ['F', 'h', 'D'] # randomly select a string: print (random. choice (['apple', 'pear ', 'peach', 'Orange ', 'lemon']) # apple # shuffling # items = [1, 2, 4, 5, 6, 7] print (items) # [1, 2, 3, 4, 5, 6, 7] random. shuffle (items) print (items) # [1, 4, 7, 2, 5, 3, 6]
Generate a Random verification code:
checkcode = ''for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp)print (checkcode)
#AX85