In Python programmingProgram, Which can be defined using functions. The basic form is:
Def Function Name (parameter 1, parameter 2 ,......, Parameter n ):
Execution statement
The name of the function is called, and the parameter is the input parameter, which can be defined or not.#Example 1: simple function usage
#Coding = gb2312
#Define functions
DefHello ():
Print 'Hello python!'
#Call a 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 calculation value
# Coding = gb2312
# Define functions
Def Myadd (a = 1, B = 100 ):
Result = 0
I =
While I <= B: # The default value is 1 + 2 + 3 + ...... + 100
Result + = I
I + = 1
Return Result
#Print 1 + 2 + ...... + 10
PrintMyadd (1, 10)
PrintMyadd ()#Use the default parameter 1,100
PrintMyadd (50)#A is assigned 50 values. B uses 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 = gb2312
Def Testpara (P1, P2 ):
P1 = 10
P2.append ( ' Hello ' )
L = [] # Define an array of Objects
A = 20# Assign a value to variable
Testpara (A, L) # Variable A and object array L are passed as parameters
Print A # Print the value after running parameters
For V In L: # Print members of an array object
Print V
>>> 20 # Variable A is not reset after the function is called.
>>> Hello # The object L Array adds the member hello.