2016/12/31 _ Python, 20161231_python
What I learned today:
Python:
1. with Statement (Supplement file operations yesterday)
Files opened with will be automatically closed after the script ends, in case you forget to close the file connection in normal mode.
Syntax: with open ("demo.txt", "r", encoding = "UTF-8") as file:
For line in file:
Print (line)
2. character encoding
1) In Python3.x, the default encoding is Unicode. In Python2.x, the default encoding is ascii.
The Red Arrow is decode and the Green Arrow is encoding)
UTF-8 → Unicode → GBK → Unicode → UTF-8;
2) import sys
Print (sys. getdefaultencoding () # obtain the encoding format
3. Functions
1) Use the keyword def to define a function. The use of the function improves code reusability, consistency, and scalability.
Def functionName ():
Pass
2) A function can contain parameters. This parameter is called a form parameter and the parameter used to call a function is called a real parameter.
Def functionName (arg1, arg2): # The parameter here is called a form parameter, which does not allocate space to the memory.
Print ("arg1 =" + arg1 + ", arg2" + arg2)
FunctionName () # error. Because two parameters are specified during function definition, two real parameters must be specified during the call.
FunctionName ("juncx", 17) # correct. The parameter here is called a real parameter, that is, the actual parameter. The memory will allocate space.
FunctionName (arg1 = "juncx", arg2 = 17) # correct. This is a keyword parameter passing.
FunctionName (juncx, arg2 = 17) # correct, as long as it matches the location of the Parameter
FunctionName (arg2 = 17, juncx) # error. parameter passing through keywords cannot be placed before unnamed parameters.
3) functions also return values
Def functionName (arg1, arg2 ):
Return arg1 + arg2
Result = functionName () # define a variable to receive the return value of the function.
Print (result) # result: 7
Def functionName2 ():
Return 1, "juncx", [1, 3, 5], {name: "age", "age": "name "}
Result = functionName2 ()
Print (result) # result :( 1, "juncx", [1, 3, 5], {name: "age", "age": "name "}) # If multiple parameters are returned, a single tuple is returned.
4) non-fixed parameters of the Function
Def functionNametu (* args) # indicates that a tuples are uploaded.
Pass
FunctionNametu (1, 2, 3, 4, 5)
FunctionNametu (* [1, 2, 3, 4, 5]) # The two call effects are equivalent.
Def functionNamekv (** kwargs) # indicates that a dictionary is uploaded.
Pass
FunctionNamekv (name = "juncx", age = 17)
FunctionNamekv ({name: "juncx", age: 17}) # The two call effects are equivalent.