The most important purpose of the function is to make it easy for us to reuse the same program.
Some operations are subordinate to a function, and in the future when you want to implement the same operation, you can simply invoke the function name, without having to repeatedly knock all the statements.
Definition of a function
First, we'll define a function to illustrate the function.
Def square_sum (A, B):
c = a**2 + b**2
Return C
The function is to find the sum of squares of two numbers.
First of all. def this keyword informs Python: I'm defining a function. Square_sum is the function name.
A in parentheses, B is the parameter of the function, it is the input to the function, the argument can have more than one, or it can be completely without (but the parentheses to keep).
We have seen in loops and choices the affiliation of the colon and the indented representation.
c = a**2 + b**2 # This sentence is an operation inside a function
Return C # Returns the value of C, which is the function of the output, and the Python function allows no return value.
Return can return multiple values, separated by commas. Equivalent to returning a tuple (fixed value table)
Return A,b,c # equals return (A,B,C)
In Python, when the program executes to return, the program stops executing the remaining statements within the function. Return is not a must, when there is no return
, or no return value after return, the function will automatically return None,none is a special data type in Python to indicate what
No, the equivalent of Null,none in C is used for the default value passed by the keyword parameter.
function calls and parameter passing
Once you have defined the function, you can use it in later programs
Print Square_sum (3,4)
Python passes the location, knowing that 3 corresponds to the first parameter of the function definition a,4 corresponds to the second parameter B, and then passes the argument to the function square_sum.
(Python has rich parameter passing methods, as well as keyword passing, table passing, and dictionary passing.) Basic tutorial will only involve location passing)
The function is calculated and returns a value of 25, and the 25 is printed by print.
Python basic 07 functions