First, preface
Learn the use of the Python random number module, and use the functions in the module to achieve 6-bit verification code generation
Ii. Random Module 1, random.random ()
Returns 0-1 direct random number, type float
>>>print(random.random())0.1259184691662908
2, Random.randint (1, 8)
Returns 1-8 direct random numbers, including 8
>>>print(random.randint(1, 8))3
3, Random.choice ()
Randomly fetching elements from a sequence
>>>print(random.choice(‘hello‘)) >>>‘h‘>>>print(random.choice([1, 2, 3, 4]))>>>2>>>print(random.choice((1, 2, 3, 4)))>>>3
4, Random.sample ()
Randomly returns the specified number of elements from an iterative object
>>>print(random.sample([1, ‘allen‘, [2, 3], (4, 5)], 2))>>>[‘allen‘, 1]
Generate 6-digit random numbers using the random implementation
Random number requirement: randomly generated using numbers, uppercase and lowercase letters
import randomdef get_code(): code = ‘‘ for i in range(6): add = random.choice([random.randrange(10), chr(random.randrange(65, 91)), chr(random.randrange(97, 123))]) code += str(add) print(code) return code get_code()
Results:
8sE9o3 ixH0o4 337o2W ...
Implementation ideas:
1. Use Random.randrange (10) to get 0-9 10 digits
2, lowercase letters corresponding to ASCII code in 65-90
3, uppercase letters corresponding to ASCII code in 97-122
4. Convert ASCII code to letters via CHR (int)
5, the number of steps, uppercase and lowercase letters list, by calling Random.choice () random selection of numbers, uppercase and lowercase letters
6, through for loop, make 6 times choice, use string splicing 6 times compose 6 bit random verification code
Python random number module learning, and implementation of generating 6-bit verification code