Today, let's talk about functions in python. There are a lot of things to pay attention to, sort them out slowly.
First, let's see what python's functions look like?
Definition
# Define a function def my_func(a): a += 1 return a
Notice that def is used at the beginning of the function instead of the function in other languages. There is a colon at the end of the first line. Then, notice that there is no {} bracket in the function type. How can python judge whether the statement belongs to this function? It is judged by indentation, so pay attention to indentation when writing.
The specific contents of this function are not detailed here, but will be discussed later.
call
# Calling function print(my_func(2))
The call is very simple.
However, it should be noted that if the number of parameters is wrong, an error will be reported during operation.
Return value
The return value can be one, multiple, or none.
When the return value is 1, it doesn't need to be mentioned. The situation of multiple return values is as follows:
# Multiple return values def my_multy(x): y = x+1 z = x-1 return y,z r = my_multy(3) print(r)
The results of the implementation are:
(4, 2)
In other words, when multiple values are returned, they are actually returned in the form of tuple, or tuple.
What if you don't write the return value?
# Do not write return value def none_return(): pass x = none_return() print(x)
The results of the implementation are:
None
In other words, if you don't write the return value, it will return None by default. Of course, you can return None manually
parameter
This one is the most complex, with many things, but it is very important.
Position parameter
Location parameter is the most common parameter we encounter. When calling, the number must be the same as the number of defined parameters, otherwise an error will be reported. This is relatively simple. There is nothing to say.
Default parameters
The default parameter is to set a default value for the parameter when defining the function. If the parameter is not given when calling the function, the function will automatically call the default value, such as:
# Default parameters def default_param(a,b=3): return a + b x = default_param(1) print(x)
The results of the implementation are:
4
Here we extend a concept, variable parameter and immutable parameter
Variable parameters are: list, set, dictionary
Immutable parameters are: number, string, tuple
The default parameter must be immutable! If you use variable parameters, there will be problems, such as:
def add_end(L=[]): L.append('END') return L print(add_end()) print(add_end()) print(add_end()) print(add_end())
The result is:
The reason is that when the function is defined, the value of the default parameter has been calculated, and a point has been given. The point is constant, but the content of the point has been changing
Variable parameters
Variable parameters allow you to pass in 0 or any parameters, which are automatically assembled into a tuple when a function is called
Usage:
Definition:
# Variable parameters def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
Call:
print(calc(1,2,3))
or
a = [1,2,3] print(calc(*a))
or
a = (1,2,3) print(calc(*a))
Key parameters
Keyword parameter allows you to pass in 0 or any parameter with parameter name. These keyword parameters are automatically assembled into a dict within the function
Usage:
Definition:
# Key parameters def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw)
Call:
a = {'weight':130,'height':175} person('sun',27,**a)
or
person('sun',27,weight=130,height=175)
Execution result:
Named key parameters
If you want to restrict the names of key parameters, you can use named key parameters, for example, only city and job are accepted as key parameters. The functions defined in this way are as follows:
Definition:
# Named key parameters def person2(name, age, *, city, job): print(name, age, city, job)
Call: key parameters can only be city and job
Call:
person2('Jack', 24, city='Beijing', job='Engineer')
or
b = {'city':'Beijing', 'job':'Engineer'} person2('Jack', 24, **b)
Order of parameter combination
The order of parameter definition must be: required parameter, default parameter, variable parameter, named key parameter and key parameter
For example:
def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
Be careful:
For any function, it can be called in the form of func(*args, **kw), no matter how its parameters are defined, such as:
def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) def f3(a, b, c=0): print('a =', a, 'b =', b, 'c =', c) a = (1,2,3) b = {'name':'sun','weight':130} c = {'d':8,'name':'sun','weight':130} f1(*a,**b) f2(*a,**c) f3(*a)
The execution result is:
Examples of built-in functions
python has a lot of built-in functions, so let's remember when we encounter them.
Finding absolute value function
# Finding absolute value function print(abs(10)) #10 print(abs(-28)) #28
Find the maximum function
# Find the maximum function print(max(1,-3,10)) #10
Data type conversion function
# Data type conversion function print(int('1111')) #1111 print(str(12.3)) #'12.3' print(bool(1)) #True