Function is equivalent to a tool to do a specific thing
Function in the separation of various tools, and does not reduce the amount of codes
Function Syntax
def (definition of a tool out) function name (with variable tool name --- the same naming convention):
<Function can realize the function>
Use function
function()
The first stage is only a function of detecting the code, the code does not perform
Here the definition of a simple function
def sum(a,b)
x = a+b
y = x*b
print(y)
sum (5,6)
Three forms' defined function
Empty function
When you only know the function you want to achieve, but do not know how to achieve it is possible to define an empty function, and for other functions, and so on back to write again
def func():
pass
No-argument function
Function definition stage brackets nothing, that is, no-argument function, if you define a function with no parameters, the call is not incoming parameters
def sum()
x = 1+2
y = 2*3
print(y)
sum ()
There are function parameters
Function definition stage there is something inside the brackets, there is a reference function, the definition of a parametric function, when you call must pass parameters
def sum(a,b)x = a+by = x*bprint(y)sum (5,6)
Function's return value
What is the return value
The results obtained through the operation function
Why use the return value
If you need to get the result of the processing functions for further processing in the program, you will need to function must have a return value.
As long as the implementation of the return, the function will be executed.
return return value can return any data type
The number of non-return return value limitations, which can return multiple values separated by commas
0: return None
1: Returns the value itself
More: Back to list
def max_num(x, y):
if x > y:
return x
else:
return y
max_salary = max_num(20000, 30000)
print(max_salary*12)
Function parameters
Katachisan
Parameters defined in parentheses function definition stage, called the formal parameters, parameter referred to, is essentially the variable name
Arguments
Passed in the function call stage parentheses parameters, known as actual parameters, referred to the argument, in essence, is the value of the variable
Positional parameters
A write from left to right a past, called the location parameter, corresponding to the position that argument, one more one less will not work.
The default parameter
During the definition phase has already been assigned, when calling would not give it a value of
def compare(num1, num2=140):
if num1 > num2:
print(num1)
else:
print(num2)
Location parameter must be placed in the default parameter left.