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())