Random module and pythonrandom Module
I. random common modules
1. random. random () randomly generates a decimal number
Print (random. random () # output 0.6060562117996784
2. random. randint (m, n) randomly generates an integer (including n) from m to n)
Print (random. randint (1, 5) # output 5
3. random. randrange (m, n) randomly generates a number from m to n, including m but not n
Print (random. randrange (1, 5) # output 3
4. random. smaple (source, n) randomly finds n values in the source to generate a list.
Print (random. sample (range (100), 5) # output [27, 49, 21, 81, 45]
Ii. string Module
2.1 string. ascii_letters # all uppercase/lowercase English letters
Letters = string. ascii_lettersprint (letters) # output abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
2.2 string. ascii_lowercase # All lowercase letters
2.3 string. ascii_uppercase # all uppercase letters
2.4 string. digit #1-9
2.5 string. punctuation # special characters
Sss = string. punctuationprint (sss) # output! "# $ % & '() * +,-./:; <=>? @ [\] ^ _ '{| }~
2.6 generate a random Verification Code
We use the random and string modules to generate a verification code containing special characters and uppercase/lowercase letters.
Import randomimport stringstr_source = {1: string. ascii_lowercase, 2: string. ascii_uppercase, 3: string. digits, 4: string. punctuation} check = [] for I in range (1, 5): y = random. sample (str_source [I], 1) check. append (y [0]) print ("". join (check) # output bV5-