Declaring and calling functions:
The way to declare a function is to use the DEF keyword, the function name, and the argument list inside the parentheses.
def foo (x): print X
Call functions: Give the function name and a small pair of parentheses, and put the required parameters:
#!/usr/bin/env pythonimport httplibdef check_web_server (host,port,path): h=httplib. Httpconnection (Host,port) h.request (' Get ', path) resp=h.getresponse () print ' Http Response: ' print ' status = ', Resp.status print ' Resson = ', Resp.reason print ' Http Headers: ' for hdr in Resp.getheaders (): print ' %s:%s '% hdr ' execution results: check_web_server (' Www.python.org ', M, '/') Http Response: status = Resson = okhttp Headers: content-length:417 x-powered-by:php/5.3.3-7+squeeze14 server:apache connection:close Date: Tue, Feb 2013 02:39:16 GMT content-type:text/html;
Keyword parameters:
You can omit the need for a fixed order, and keyword parameters are specified by the form "key = value", for example:
Check_web_server (port=80,path= '/', host= ' www.pyton.org ')
Default parameters:
To provide a default value for a parameter, you do not have to pass variable values to it, such as:
def check_web_server (host,port=80,path= '/')
Note: The difference between the default and key parameters:
Keyword parameters can only be used for function calls, default parameters are used for function declarations, and for default functions, all required parameters must be present before any optional parameters, and they cannot be mixed together to reverse the order.
def Check_web_server (Host,port=80,path) This is wrong.
Common errors:
1, the list and dictionary as the default parameters;
Since lists and dictionaries are variable variables, it can be dangerous to look at them, especially if they are continuously passing through multiple function calls.
def func (arg=[]): arg.append (1)
print arg
func () [1] func () [1,1] func () [ 1,1,1]
A reference to a function in an object:
In Python, you can use functions (or methods) as you would with other objects, put them in a container, assign them to other variables, pass them to a function, and so on.
When the function is called, the parentheses are added, and when it is passed as a variable or object, only the function name is required.
anonymous function:
The method created is to use the Lambda keyword, which consists of an expression,
Syntax: Lambda args: When an expression executes, the lambda returns a function object that can be used immediately, either by saving it as a variable or by a callback function for later execution.
*args and **kwargs
Whether a function invokes a Korean declaration, a single asterisk indicates a ganso or list as an argument, and two asterisks represent the argument as a dictionary.
* and * * in the function call
def Check_web_server (Host,port,path):