In Python programming, you can use functions to define some programs that require repeated calls. in Python, def is used to define functions, for python programming programs that require repeated calls, you can use functions to define them. The basic form is as follows:
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.