Hello, I am Ma Nongfei ge, thank you for reading this article, welcome one button three lian oh. This article introduces Python functions, their definition, usage, variable arguments, and so on. Dry goods full, suggested collection, need to use often look. If you have any questions or needs, please feel free to leave a message.
[TOC]
preface
The previous chapters covered many Python functions, such as print(), range(), len(), and so on. These are Python’s built-in functions and can be used directly. Of course, in addition to using built-in functions directly, Python also supports custom functions, where a regular, reusable piece of code is defined as a function. Thus achieve a write, many times the purpose of the call.
The function definitions
Functions are reusable code segments organized in a fixed format. It can improve application modularity and code reuse. The syntax for a function definition is:
defFunction name (argument list) :The code block [return[Return value]]Copy the code
Function name: This is a Python identifier. The function name should reflect the function’s function, such as save_user. Parameter list: Sets how many arguments the function can accept, separated by commas (,). If there are no arguments, leave a pair of empty () [return[return value]] : the whole function as an optional argument, used to set the return value of the function. That is, a function can have a return value or no return value.
A function call
The syntax for calling a function is:
Return value = function name ([parameter value])Copy the code
The function name refers to the name of the function to be called, and the parameter value refers to the values of the parameters that were passed in when the function was created. If the function has a return value, we can use a variable to receive the value, or not. Note that the number of parameters a function takes depends on how many values are passed in the call, in the same order as when the function was created. Even if the function has no arguments, the parentheses after the function name cannot be omitted. Here’s an example:
def my_abs(x) :
Return absolute value :param x: :return: ""
if not isinstance(x, (int.float)) :raise TypeError('Incorrect data type passed in')
if x >= 0:
return x
else:
return -x
Copy the code
The calling code is:
x = my_abs(-3)
print(x)
print(my_abs.__doc__)
Copy the code
The results are as follows:
Param x: :return:Copy the code
This is a function that takes the absolute value, and its name is my_abs, which gives you a sense of what the function does. The formal parameter is x. The function documentation can be viewed with __doc__. The return value is the processed value. Today is still a day of learning for Mynongfei.
Function value Passing and reference Passing (An introduction to parameters and arguments)
Before introducing function value passing and reference passing, you need to understand two concepts.
- Formal parameters (parameters for short) : When defining a function, the parameters in parentheses after the function name are formal parameters. You can think of parameters as characters in a play.
- Actual arguments: When a function is called, the arguments in parentheses after the function name are called actual arguments, which are the arguments given to the function by the function caller. You can think of the arguments as actors playing a role.
There are two ways to pass function parameters: value pass and reference pass respectively:
- Value passing: applies to arguments of immutable type (string, number, tuple)
- Reference (address) passing: applies to arguments of mutable type (list, dictionary)
The difference between value passing and reference passing is that when a function parameter is passed by value, the value of the argument is not affected if the parameter is changed. If we change the value of the parameter, the value of the argument changes. Again, as an example, the function param_test changes the parameter obj to obj+obj. In the case of value passing, the parameter value remains the same after the function param_test is called. When param_test is called, the value of the argument becomes obj+obj.
def param_test(obj) :
obj += obj
print('Parameter values are :', obj)
print('******* value passed *****')
a = 'Code Nongfei'
print(The value of 'a 'is:, a)
param_test(a)
print(The value of the argument is:, a)
print("******* reference pass *****")
b = [1.2.3]
print(The value of 'b 'is:, b)
param_test(b)
print(The value of the argument is:, b)
Copy the code
The results are as follows:
Pass * * * * * * * value * * * * * a value is: code farmers flying elder brother parameter value is: code flying elder brother code farmers flying elder brother of the argument value is: code farmers flying elder brother reference * * * * * * * * * * * * b value is: [1, 2, 3] parameter value is: [1, 2, 3, 1, 2, 3] The argument values are: [1, 2, 3, 1, 2, 3]Copy the code
Python positional arguments
Positional arguments, sometimes called required arguments, refer to the fact that the arguments must be passed to the function in the correct order. In other words, the number and positions of arguments passed to the function must be the same as when the function was defined. If they are inconsistent, the Python interpreter raises TypeError while the program is running. As an example, the following example shows the case of calling a function with the wrong number of arguments.
def girth(width , height) :
return 2 * width+height
When calling a function, you must pass two arguments, otherwise an error will be raised
print(girth(3))
Copy the code
A Traceback error is reported after the command is run.
Traceback (most recent call last):
File "/Volumes/Develop/Python_learn/PycharmProjects/python_demo_1/demo/function/locate_fun.py", line 6, in <module>
print(girth(3))
TypeError: girth() missing 1 required positional argument: 'height'
Copy the code
If the position of the passed parameter is not correct, in this case, the value of name is intended to be Code Nongfego, and the value of age is 18. Result The entry order is not correct, resulting in incorrect results.
def print_info(name, age) :
print('name =' + name + "Age =" + str(age))
print_info(18.'Code Nongfei')
Copy the code
So how do you handle this situation? There are two ways:
- Parameters are entered strictly by the number and position of the parameters.
- Parameters are entered as keyword arguments, which use the parameter name to determine the input parameter value. When you write function arguments in this way, you no longer need to have exactly the same position as the parameter, just write the parameter names correctly. Take the above function as an example:
To call a function with a keyword argument, write:
def print_info(name, age) :
print('name =' + name + "Age =" + str(age))
print_info(age=18,name='Code Nongfei')
Copy the code
The results are as follows:
Name = Age =18Copy the code
As you can see, there is no need to ensure that the order of the keyword parameters is the same as that of the parameters.
Default Parameter Settings
The positional argument introduced earlier means that it must be passed in when a function is called. But there are scenarios where we don’t want to pass in all the parameters. In this case you can use the default parameters. Note, however, that formal parameters with default values must be at the end of all parameters that do not have default values, otherwise a syntax error will occur. The syntax format is:
defThe function name (. , parameter name, parameter name = default) : code blockCopy the code
Here is an example of a function that records information about a student with two default parameters, age and city. They are placed at the end of the function’s parameter list.
def enroll(name, gender, age=6, city='Beijing') :
print('name:', name)
print("gender:", gender)
print("age:", age)
print("city:", city)
print(enroll('Joe'.'First year'))
print('* * * * * * * * * * * * * * * * * * * * * * * * * *')
print(enroll('bill'.'Second year'.7))
Copy the code
The results are as follows:
Name: Zhang SAN Gender: grade 1 Age: 6 City: Beijing None ************************** Name: Li Si Gender: Grade 2 age: 7 City: Beijing NoneCopy the code
1. You don’t need to pass in a parameter with a default value. 2. If you pass in a default parameter, the default value will be overwritten.
Variable parameter
Python function variable arguments (*args,**kwargs), also known as variable arguments, that is, the actual arguments in the function can be as many as you want. Python definitions can change arguments in two main forms:
- Add one before the parameter
*
The format is*args
. Represents the creation of an empty tuple named args that can accept any number of non-keyword arguments passed in from outside.You must pass values to ordinary arguments as non-keyword arguments, or the Python interpreter will pass all arguments to mutable arguments first. **kwargs
Represents the creation of an empty dictionary named kwargs that can accept any number of arguments assigned as keyword arguments. For example 🌰, here is the sum from the values passed in.
def calc(*numbers) :
sum = 0
for n in numbers:
sum = sum + n
return sum
print(calc(10.9))
Copy the code
The result of the run is: 19. Here’s another example:
def record(str, **kwargs) :
print('str='.str)
print('kwargs=', kwargs)
record('test', name='Code Nongfei', age=20)
record('test 2')
Copy the code
The results are as follows:
STR = test kwargs= {'age': 20, 'name': 0} STR = test 2 kwargs= {}Copy the code
As you can see from the code above, mutable parameters can be passed without creating an empty tuple or an empty dictionary.
Reverse parameter collection
Not only does Python have mutable arguments, packing multiple arguments into a single tuple or dictionary, it also supports reverse argument collection, which takes lists, tuples, and dictionaries directly as function arguments. However, the function is called with an asterisk. Like this:
def param_test(name, age) :
print('name=', name)
print('age=', age)
data = ['Code Nongfei'.18]
param_test(*data)
Copy the code
The results are as follows:
Name = nongfei age= 18Copy the code
Return The value returned by the function
A function may or may not return a value. The syntax for a function with a return value is:
return[Return value]Copy the code
The return value can be specified or omitted. It defaults to None, which is null, if not written.
A method by which a Python function returns multiple values
Normally, a function returns only one value, and in fact Python does the same, except that Python functions can indirectly return multiple values by saving them to a sequence by returning a list or tuple.
- In a function, multiple values to be returned are stored in a list or tuple in advance, and the function returns the list or tuple
- The function returns multiple values directly, separated by commas (,). Python automatically wraps multiple values into a tuple, and the return value is still a tuple. Here are some examples:
def multi_return() :
return_tuple = ('Joe'.12)
return return_tuple
def multi_return2() :
return 'Joe'.12
print(multi_return())
result = multi_return2()
print('multi_return2 returns value = and type =', result, type(result))
Copy the code
The run result is
(' tuple', 12) <class 'tuple'> (' tuple', 12)Copy the code
conclusion
This article took a detailed look at functions in Python, from their definition to their invocation. This paper focuses on the knowledge of parameters and arguments. In general, Python functions can have no input arguments and no return values. You can pass in mutable arguments. Value is passed when the parameter is of immutable type, and reference is passed when the parameter is of mutable type.
I am Mynongfei and thank you again for reading this article. The whole network with the same name [code nongfei brother]. Thank you again for reading this article.