Python function basics and python Basics
I. Function Basics
Simply put, a function is a combination of Python statements that can be run once or multiple times in a program. Functions in Python are also called procedures or subroutines in other languages, so these encapsulated statements are called by a function name.
With functions, we can greatly reduce the number of times code is copied and pasted (I believe many people have this experience at the beginning ). We can extract the same code into a function and call it as needed. This improves the code reuse rate. The overall code looks concise and not so bloated.
Functions are the most basic program structure in Python to maximize the reuse of our code. At the same time, functions can divide a complicated system into manageable parts, simplified programming and code reuse.
Next, let's take a look at what functions are and how to define them. There are two methods to define a function: def and lambda keywords.
1. Function Definition
First, I would like to summarize why the function is used?
Maximize code reuse and minimize redundant code;
Process decomposition (disassembly ). Split a complex task into multiple small tasks.
Function Syntax:
def func_name(arg1, arg2, arg3, ..., argN): statement return value
According to the above definition, it can be simply described that a function in Python has zero or multiple parameters, several rows of statements, and return values (the return value is optional) (note the indentation ).
Then we define a simple function with no parameters to enter the ipython interactive environment:
In[1]: def hello(): ...: print('Leave me alone, the world') ...:
Call (execute) This function:
In[2]: hello()Leave me alone, the world
We found that the hello () function does not have a return statement. In Python, if the return statement is not explicitly executed, the return value of the function is None by default.
As we have said, there are two types of udfs, and the other is defined using lambda. The function defined by lambda is an anonymous function. We will explain it later. It is not shown here.
Ii. Function Parameters
When defining a function, we can determine the parameter name and position, and define the function interface. For a function caller, you only need to know how to pass the correct parameters and what values the function will return. The complex logic inside the function is encapsulated, And the caller does not need to know.
Python functions are easy to define, but flexible. In addition to the required parameters, you can also use default parameters, variable parameters, and keyword parameters, so that the interface defined by the function can not only process complex parameters, it also simplifies the caller's code.
1. Default Parameters
Default parameters make the API concise, but flexible. When a parameter has a default value, the default value is used if this parameter is not passed.
Def inc (init, step = 1): return init + step # Call this function >>> inc (3) 4 >>> inc (3, 2) 5
The default parameter has a pitfall, that is, the non-default parameter must be placed before the default parameter (otherwise, the Python interpreter will report a syntax error ). Multiple default parameters are allowed, but the default parameters must be placed at the end of the parameter list.
def append(x, lst=[]): return lst.append(x)
This function has a problem. (Is the form parameter in the function a global variable? Lst is called lst in the append function, but in the global scope, we do not know what the lst is called .)
The modified function is:
def append(x, lst=None): if lst is None: lst = [] lst.append(x) return lst
Generally, when the default parameter is variable, you need to pay special attention to the scope problem. We need the above technique (the variable data type is value transfer, the variable data type is reference transfer .). Currently, the variable objects are list, dict, set, and bytearray.
Default parameters are useful, but improper use may also result in pitfalls. The default parameter has the largest pitfall, as shown below:
# Define a function first, input a list, add an END, and then return def add_end (L = []): L. append ('end') return L
When we call it normally, the results seem to be good:
>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']
When we use the default parameter call, the initial result is also correct:
>>> add_end()['END']
However, when add_end () is called again, the result is incorrect:
>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']
The reasons are as follows:
When defining a Python function, the value of the default parameter L is calculated, that is, []. Because the default parameter L is also a variable, it points to the object [], every time you call this function, if the content of L is changed, the content of the default parameter will change next time. It is no longer the [] of the function definition.
Therefore, to define default parameters, remember that the default parameters must point to unchanged objects!
To modify the example above, we can use the unchanged object None to implement:
def add_end(L=None): if L is None: L = [] L.append('END') return L
Why do we need to design immutable objects such as str and None? Because once a constant object is created, the data in the object cannot be modified, which reduces errors caused by data modification. In addition, because the object remains unchanged, there is no need to lock the object to be read at the same time in the multi-task environment. When writing a program, if we can design a constant object, we should try to design it as a constant object.
2. location parameters
First, write a function to calculate x ^ 2:
def power(x): return x * x
For power (x) functions, parameter x is a positional parameter. When we call the power function, we must pass in one and only one parameter x:
>>> power(5)25>>> power(15)225
What if we want to calculate x ^ 3? You can define another power3 function, but what if you want to calculate x ^ 4, x ^ 5, x ^ n? It is impossible to define an infinite number of functions. We can change power (x) to power (x, n) to calculate x ^ n, and write it as soon as we say:
def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s
3. Keyword Parameters
Variable parameters allow us to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function. Example:
def person(name, age, **kwargs): print('name:', name, 'age:', age, 'other:', kwargs)
In addition to the required parameter name and age, the function person also accepts the key word parameter kwargs. When calling this function, you can only input the required parameters:
>>> person('LavenLiu', 25)name: LavenLiu age: 25 other: {}
You can also input any number of keyword parameters:
>>> person('LavenLiu', 25)name: LavenLiu age: 25 other: {}>>> person('Taoqi', 25, city='Hebei')name: Taoqi age: 25 other: {'city': 'Hebei'}>>> person('James', 31, gender='M', job='NBA player')name: James age: 31 other: {'gender': 'M', 'job': 'NBA player'}
What is the use of keyword parameters? It can expand functions of functions. For example, in the person function, we ensure that the two parameters name and age can be received. However, if the caller is willing to provide more parameters, we can also receive them. Imagine that you are working on a user registration function. Except that the user name and age are mandatory, other functions are optional. Using Keyword parameters to define this function can meet the registration requirements.
Similar to variable parameters, You can assemble a dict and then convert the dict into a keyword parameter:
>>> kwargs = {'city': 'Hebei', 'job': 'Test'}>>> person('Taoqi', 25, **kwargs)name: Taoqi age: 25 other: {'city': 'Hebei', 'job': 'Test'}4. Location and keyword Parameters
Location parameters and keyword parameters are concepts used in function calls.
It is useful when the default parameters and keyword parameters are combined.
Keyword parameters must be written after the location parameter; otherwise, a syntax error is thrown.
Def minus (x, y): return x-yminus (3, 5) # location parameter, location parameter minus (5, 3) # location parameter, location-Based Parameter minus (x = 5, y = 3) # keyword parameter, keyword-based parameter minus (y = 3, x = 5) # keyword parameter, keyword-based parameter passing
The location parameter and the keyword parameter can coexist, but the keyword parameter must be written after the location parameter.
5. Variable location parameters
The variable location parameter is defined by *. In the function body, the variable location parameter is a tuple.
Variable location parameter.
In[1]: def fn(*args): ...: print(args) ...: In[2]: fn((1, 2, 3, 4))((1, 2, 3, 4),)In[3]: tup01 = (1, 2, 3, 4)In[4]: fn(tup01)((1, 2, 3, 4),)In[5]: fn(*tup01)(1, 2, 3, 4)
Variable parameters can also be defined in python functions. A Variable Parameter means that the number of input parameters is variable.
In [6]: def cacl (* numbers ):...: sum = 0...: for n in numbers :...: sum = sum + n * n...: return sum...: In [7]: nums = [1, 2, 3] In [8]: cacl (* nums) # if it is not added before nums, is there a problem? Out [8]: 14
6. Variable keyword Parameters
Variable keyword parameters are defined by **. In a function, variable keyword parameters are a dictionary. The key of a variable keyword parameter is a string and complies with the identifier definition specification.
def fn(**kwargs): print(kwargs)dict01 = {'name': 'Laven Liu', 'age': 29}fn(**dict01)# fn(dict01)fn(name='Laven Liu', age=29){'name': 'Laven Liu', 'age': 29}{'name': 'Laven Liu', 'age': 29}
Variable-location parameters can only be called as location parameters
Variable keyword parameters can only be called as keyword Parameters
The variable location parameter must be before the variable keyword Parameter
In[18]: def fn(*args, **kwargs): ...: print(args) ...: print(kwargs) ...: In[19]: fn(1, 2, 3, a=1, b=2)(1, 2, 3){'a': 1, 'b': 2}In[20]: def fn(*args, x, y): ...: print(args) ...: print(x, y) ...: In[21]: fn(1, 2, 3, 4)---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-21-0ab4fbc96a17> in <module>()----> 1 fn(1, 2, 3, 4)TypeError: fn() missing 2 required keyword-only arguments: 'x' and 'y'In[22]: fn(1, 2, x=3, y=4)(1, 2)3 4
Variable Parameter rear
Variable parameters do not appear together with default parameters
7. parameter combination
Define functions in Python. You can use required parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together or only use some of them, the order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, and keyword Parameter
For example, defining a function includes the preceding four parameters:
>>> Def func (a, B, c = 0, * args, ** kwargs ):
... Print ('a = ', a,' B = ', B, 'c =', c, 'args = ', args, 'kwargs =', kwargs)
When a function is called, the Python interpreter automatically transmits the corresponding parameters according to the parameter location and parameter name.
>>> func(1, 2)a = 1 b = 2 c = 0 args = () kwargs = {}>>> func(1, 2, c=3)a = 1 b = 2 c = 3 args = () kwargs = {}>>> func(1, 2, 3, 'a', 'b')a = 1 b = 2 c = 3 args = ('a', 'b') kwargs = {}>>> func(1, 2, 3, 'a', 'b', x=99)a = 1 b = 2 c = 3 args = ('a', 'b') kwargs = {'x': 99}>>>
The most amazing thing is that through a tuple and dict, we can also call this function:
>>> args = (1, 2, 3, 4)>>> kwargs = {'x': 99}>>> func(*args, **kwargs)a = 1 b = 2 c = 3 args = (4,) kwargs = {'x': 99}
Therefore, any function can be called in a way similar to func (* args, ** kwargs), regardless of how its parameters are defined.
8. Parameter deconstruct
Parameter deconstruct occurs when a variable parameter is defined in a function call. There are two types of parameter deconstruct: Location Parameter deconstruct and keyword parameter deconstruct.
Two Parameter structures:
Position parameter deconstruct, using an asterisk. The deconstruct object is an iterative object, and the deconstruct result is a location parameter.
Keyword parameter deconstruct, using two asterisks. The deconstruct object is a dictionary and the result is a keyword parameter.
An example of Location Parameter deconstruct:
In [23]: def fn (a, B, c ):...: print (a, B, c )...: In [24]: lst = [1, 2, 3] In [25]: fn (lst [0], lst [1], lst [2]) 1 2 3 # Call In [26]: fn (* lst) # This method is called parameter deconstruct 1 2 3 # *. The linear structure can be unwrapped into the location parameter lst = [1, 2, 3, 4] fn (* lst) #-> fn (lst [0], lst [1], lst [2], lst [3]) TypeError: fn () takes 3 positional arguments but 4 were given # Here an error is reported. Originally, this function can only receive three location parameters. lst has four elements. After the parameter is reconstructed, it is changed to four parameters, so an error is reported.
Next, let's look at the dictionary deconstruct example:
In[27]: d = {'a': 1, 'b': 2, 'c': 3}In[28]: fn(**d)1 2 3
# ** Dictionary decoding can constitute a keyword Parameter
Parameter deconstruct occurs when a function is called. In terms of deconstruct, the deconstruct of a linear structure is a positional parameter, and the dictionary deconstruct is a keyword parameter.
Sequence of passing parameters: location parameter, linear structure deconstruct; keyword parameter, Dictionary deconstruct. Try to use two types of deconstruct as few as possible, unless you really know what to do.
In[29]: def fn(a, b, c, d): ...: print(a, b, c, d) ...: In[30]: fn(0, *[2], c=1, **{'d': 3})0 2 1 39. Parameter slot (keyword-only parameter)
Introduced in Python3.
def fn(a, b, c): print(a, b, c)fn(a=1, b=2, c=3)
If the parameter to be forcibly input is a keyword parameter:
def fn(*, a, b, c): print(a, b, c)>>> fn(1, 2, 3)Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> fn(1, 2, 3)TypeError: fn() takes 0 positional arguments but 3 were given>>> fn(a=1, b=2, c=3)1 2 3
# * Parameters must be passed in the form of keyword parameters, which are called parameter slots.
The parameter slot is usually used with the default parameter.
>>> def fn(a, b, *, x, y): print(a, b) print(x, y)>>> fn(1, 2, 3, 4)Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> fn(1, 2, 3, 4)TypeError: fn() takes 2 positional arguments but 4 were given>>> fn(1, 2, x=3, y=4)1 23 4>>> fn(1, 2, **{'x': 3, 'y': 4})1 23 4def fn(a, b, *): print(a, b)def fn(a, b, *):... print(a, b)File "<stdin>", line 1SyntaxError: named arguments must follow bare *
Examples:
def fn01(*, x=1, y=5): print(x) print(y)>>> fn01()15def fn02(x=1, *, y): print(x) print(y)>>> fn02(y=3)13
Parameter slot:
* Parameters must be included later.
If a non-naming parameter has a default value, the name parameter can have no default value.
The default parameter must be at the end of each parameter segment.
Variable location parameters cannot be used when parameter slots are used. Variable key parameters must be placed after named parameters.
Iii. Advanced usage 1. recursive functions
You can call other functions within a function. If a function calls itself internally, this function is a recursive function.
def fact(n): if n==1: return 1 return n*fact(n-1)
The advantage of using recursive functions is that the logic is simple and clear, and the disadvantage is that too many calls may cause stack overflow.
Languages optimized for tail recursion can prevent Stack Overflow through tail recursion. Tail recursion is actually equivalent to a loop. A programming language without a loop statement can only implement a loop through tail recursion.
2. Anonymous function lambda
Python uses lambda to create anonymous functions.
Lambda is just an expression, and the function is much simpler than def.
The body of lambda is an expression rather than a code block. Only limited logic can be encapsulated in lambda expressions.
A lambda function has its own namespace and cannot access parameters outside its own parameter list or in a global namespace.
Although lambda functions seem to be able to write only one row, they are not equivalent to C or C ++ inline functions. The latter aims to call small functions without occupying the stack memory to increase the running efficiency.
Fib = lambda n, x = 0, y = 1: x if not n else fib (n-1, y, x + y)
Print (fib (20 ))
3. polymorphism in Python Functions
The meaning of an operation depends on the type of the object to be operated:
Def times (x, y): return x * y >>>> times (2, 4) >>> 8 times ('python', 4) # The data type 'pythonpythonpythonpython' is passed'Iv. Summary
Python functions have a flexible parameter form, which can be used for simple calls and very complex parameters.
The default parameter must use an immutable object. If it is a mutable object, a logic error occurs during running!
Pay attention to the syntax for defining variable parameters and keyword parameters:
* Args is a variable parameter, and args receives a tuple;
** Kwargs is a keyword parameter, and kwargs receives a dict.
And how to pass in the Variable Parameter and keyword parameter syntax when calling the function:
Variable parameters can be passed in directly: func (1, 2, 3), list or tuple can be assembled first, and then passed in through * args: func (* (1, 2, 3 ));
Keyword parameters can be passed in directly: func (a = 1, B = 2), dict can be assembled first, and then passed in through kwargs: func ({'A': 1, 'B': 2 }).
The use of * args and ** kwargs is a habit of writing in Python. Of course, you can also use other parameter names, but it is best to use them in Regular usage.