Python random number module learning, and implementation of generating 6-bit verification code

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.