Python functions
Defining functions
In Python, a function is defined with a DEF statement that writes out the function name, the arguments in parentheses, and the colon: the function returns using the return statement.
def myDef(x): if x >= 0: return x; else: return -x;print(myDef(12));
Function call
Python has a number of functions built into it, and we can call them directly, calling them: function names (parameters). You need to pass in the correct parameters according to the function definition
Data type Conversion Functions
- Parameters of the function
Position parameters
Functions like the calculation of x^2
def power(x): return x * x;
X is a positional parameter, and when we call the function, we must pass in the only one parameter x. (To tell the truth, it is not very well understood the meaning of positional parameters, do not know whether you understand it, in the slowly experience it), you can also such power (x, N), calculate the value of x^n.
- Default parameters
def power (x, n=2), such a function calls Power (5), you think you default to 2,x to 5.
Variable parameters (*args)
That is, the number of incoming parameters is variable.
Calculate a^2 + b^2 + c^2 + ...
def cale(numbers): sum = 0; for n in numbers: sum = sum + n*n; return sum; #但是我们调用的时候,需要县组装出一个list或tuple print(cale([1, 2,2])); #9 print(cale((1, 3, 4, 7))); #75
Keyword parameter: Allows you to pass in 0 or more parameters with parameter names, which are automatically assembled into a dict (map) inside the function. (**KW)
def person(name, age, **kw): print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)
- Named keyword parameters
Keyword parameter **kw, the named keyword parameter requires a special delimiter , and subsequent arguments are treated as named keyword parameters.
Combination parameters
To define a function in Python, you can use the required parameters, default parameters, variable parameters, keyword arguments, and named keyword parameters, which can all be combined using 5 parameters. the order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.
def f1(a, b, c=0, *args, **kw):
- Recursive functions
That is, the function weight is called on the function itself.
- Summarize
Basic grammar Learning for Python functions requires a constant practice of examples in order to better understand them.
Python function Syntax Learning