Python def function definition usage and parameter passing implementation code
- 2020-04-02 13:55:22
- OfStack
In Python programming, some programs that need to be repeatedly called can be defined by using functions. The basic form is:
Def function name (argument 1, argument 2... , the parameter N) :
The execution statement function is called by the name of the representation, and the arguments are passed in and can be more or less defined.
# case 1 : simple function to use
# coding=gb2312
# Define a function
def hello():
print 'hello python!'
# Call a function
hello()
>>> hello python!
The function can take parameters and return values. The parameters will be matched from left to right. The parameters can be set to default values.
# case 2 : cumulative calculated value
# coding=gb2312
# Define a function
def myadd(a=1,b=100):
result = 0
i = a
while i <= b: # The default value is 1+2+3+ ... +100
result += i
i += 1
return result
# print 1+2+ ... +10
print myadd(1,10)
print myadd() # Using default parameters 1 . 100
print myadd(50) # a The assignment 50 . b Use default values
>>> 55
>>> 5050
>>> 3825
When passing arguments to Python functions, it is important to note that when arguments are passed in as variables they are temporarily assigned to parameter variables, and if they are objects they are referenced.
# case 3 :
# coding=gb2312
def testpara(p1,p2):
p1 = 10
p2.append('hello')
l = [] # Define an array array
a = 20 # To the variable a The assignment
testpara(a,l) # variable a And object array l Pass in as a parameter
print a # Print the value after the run parameter
for v in l: # Prints the members of the array object
print v
>>> 20 # After calling the function a The variable is not complex
>>> hello # The object l The array adds members hello