Learn the main content today:
Python:
1. With statement (Supplement yesterday's file operation)
Files opened with with are automatically closed at the end of the script, in case the normal open mode forgot to close the file connection
Syntax: With open ("Demo.txt", "R", encoding= "Utf-8") as File:
For line in file:
Print (line)
2, the operation of character encoding
1) in python3.x, the default encoding is the Unicode code; in python2.x, the default encoding is the ASCII code
Red Arrows are decoded (decode), green arrows are encoded (encode)
UTF-8→ Unicode→ GBK GBK→Unicode→UTF-8;
2) Import sys
Print (Sys.getdefaultencoding ()) #获取编码格式
3. Functions
1) Define a function using the keyword DEF, which improves the reusability, consistency and extensibility of the code.
def functionname ():
Pass
2) The function can take parameters, which are called formal parameters, and the arguments used to invoke the function are called arguments.
def functionname (ARG1,ARG2): #这里的参数叫做形参, which is the form parameter, memory does not allocate space
Print ("arg1=" +arg1+ ", arg2" +arg2)
functionname () #错误 because two parameters are specified when the function is defined and two arguments are specified on invocation
functionname ("Juncx", +) #正确, where the parameters are called arguments, i.e. actual parameters, memory allocates space
functionname (arg1= "Juncx", arg2=17) #正确, this is the keyword argument
functionname (juncx,arg2=17) #正确, as long as it matches the position of the formal parameter
functionname (ARG2=17,JUNCX) #错误, keyword arguments cannot be placed in front of unnamed parameters
3) function also has return value
def functionname (ARG1,ARG2):
Return ARG1+ARG2
result = functionname (2,5) #定义一个变量来接收函数的返回值
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"}) #返回多个参数时将返回一个元组
4) Non-fixed parameters of the function
def functionnametu (*args) #表示传一个元组
Pass
Functionnametu (1,2,3,4,5)
Functionnametu (*[1,2,3,4,5]) #两种调用效果时等效的
def functionnamekv (**kwargs) #表示传一个字典
Pass
FUNCTIONNAMEKV (name= "Juncx", age=17)
FUNCTIONNAMEKV ({name: "Juncx", age:17}) #两种调用效果是等效的
2016/12/31_python