Python study note 17: base64 encoding and scope and md5, pythonbase64

Source: Internet
Author: User

Python study note 17: base64 encoding and scope and md5, pythonbase64
I. Python Base64 encoding

The Base64 module is used for base64 encoding and decoding in Python. Sample Code:

#-*- coding: utf-8 -*-import base64str = 'cnblogs'str64 = base64.b64encode(str)print str64                     #Y25ibG9ncw==print base64.b64decode(str64)   #cnblogs
Ii. Python variable scope local variables

When you declare variables in the function definition, they have no relationship with other variables with the same name outside the function, that is, the variable name isLocal. This is called VariableScope. The scope of all variables is the block they are defined, starting from the point where their names are defined.

a = 1def fun(a):    print a    a = 2    print afun(x)print a

Result:

121

Explanation:

In the function, we use a for the first timePython uses the parameter value declared by the function.

Next, we set the value2Assign to. A is the local variable of the function. Therefore, when we change the value of a in the function, the defined in the main block will not be affected.

In the lastprintStatement, we prove that the value of a in the main block is indeed not affected.

Use global statements

If you want to assign a value to a variable defined outside the function, you have to tell Python that the variable name is not local,Global, We useglobalStatement to complete this function.

a=1def fun():    global a    print a    a = 2    print afun()print a

Output:

122

Explanation:

globalStatement is used to declareIs Global -- therefore, when we assign the value to a in the function, this change is also reflected in the use of a in the main block..

Iii. MD5

 

#Python 2.ximport hashlibprint hashlib.md5("whatever your string is").hexdigest()#Python 3.ximport hashlibprint(hashlib.md5("whatever your string is".encode('utf-8')).hexdigest())

 

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.