Python def Function Definition, use, and parameter transfer implementation code, pythondef
In Python programming, you can use functions to define some programs that require repeated calls. The basic form is:
Def function name (parameter 1, parameter 2 ,......, Parameter N ):
The name of the function called by the execution statement is the input parameter, which can be defined or not required.
# Example 1: Use a simple function # coding = gb2312 # define the function def hello (): print 'Hello python! '# Call the function hello () >>> hello python!
A function can contain parameters and return values. parameters are matched from left to right. default values can be set for parameters. When a function is used, values are assigned by default.
# Example 2: Accumulate calculated value # coding = gb2312 # define function def myadd (a = 1, B = 100): result = 0 I = a while I <= B: # The default value is 1 + 2 + 3 + ...... + 100 result + = I + = 1 return result # print 1 + 2 + ...... + 10 print myadd (1,100) print myadd () # use the default parameter print myadd (50) # a value of 50, B use the default value >>> 55 >>> 5050 >>> 3825
When passing parameters of a Python function, it is worth noting that if the input parameter is a variable, it will be temporarily assigned to the parameter variable. If it is an object, it will be referenced.
# Example 3: # coding = gb2312def testpara (p1, p2): p1 = 10 p2.append ('hello ') l = [] # define an array for image a = 20 # assign testpara (a, l) to variable) # input print a as a parameter between variable a and object array l # print the value of the running parameter for v in l: # print the print v >>> 20 # The a variable is not reset after the function is called >>> hello # The member hello is added to the l Array of the object.
How does python define functions?
Use the keyword def to declare that this is a function.
1def function name (parameter ):
2 Statement Blocks
There can be no or multiple parameters separated by commas (,). The first line is called the function header. A colon must be added to the end to start the function execution.
The statement block is the function body. It is the statement about the function to be implemented by the function. The return statement must be included in the statement. If no return statement exists, return none is returned.
How to define functions in python
Use the def keyword, which contains the parameter list in brackets.
Def add (a, B ):
Return a + B
# Call
Print add (1, 2)