"Learning Python with You Hand in Hand" 28-the return value of a custom function

In the previous article "Learning Python with You Hand in Hand" 27-Parameters of Custom Functions , we learned several types of parameters of custom functions. In this article, we will learn the return value of a custom function and introduce the application of the return value.

We already know that a custom function is a code block that starts with the keyword def and ends with the keyword return. The return is the keyword that returns the return value.

In the first two articles, although there is no focus on explaining, in fact, several examples of using return return values ​​have been listed in the examples, such as returning the result of throwing a dice, returning the name of the winner, returning the result of summation or area calculation and many more.

But we also found that not every custom function has a return value. For example, in the several instances of variable-length parameters in the previous article, the custom function only has the def keyword instead of the return keyword. At this time, the custom function will only be executed until the last command line of the function (such as printing in the variable-length parameter example), and will not return any results to the main program, or only return control None.

Due to the above two cases, one is relatively simple, with only one return value, and there are examples introduced before; the other does not involve return values ​​and return statements, and does not introduce too much. Today, we will focus on how to return multiple values, which is also a Python feature that we often need to use in subsequent data analysis.

There is a very simple example to show how to return multiple values:

In [1]: def f(): 
            a = 1
            b = 2
            c = 3
            return a, b, c

        a, b, c = f()
        print(a, b, c)

Out[1]: 1 2 3

In this example, the custom function f() achieves two purposes, one is to define the value of abc, and the other is to return the value of abc.

The most important line of command in the main program is to assign abc, and it is assigned in a one-to-one correspondence with the return value of the function. Although the variable names used here are the same, in fact, the process of assignment is not based on the variable name. The key is the order. For example, we can slightly modify the variable name and order to see what happens?

In [2]: def f():
            a = 1
            b = 2
            c = 3
            return a, b, c

        b, a, d = f()
        print(b, a, d)

Out[2]: 1 2 3

We can see that although the variable name and order have changed, the result is still assigned and printed out in the order of the return value, without being changed by the adjustment of the variable name or position.

So, from this feature of the return value, I wonder if you can think of a data structure we have learned before? Yes, it is a tuple, a fixed-length and immutable data structure.

So, it seems that the function returns multiple values, but in fact it returns only an object, which is a tuple. Therefore, the return value in the above example can be received with a variable name. The variable after the assignment is a tuple, and it has all the characteristics of a tuple for us to use.

In [3]: def f():
            a = 1
            b = 2
            c = 3
            return a, b, c

        tup = f()
        print(tup)

Out[3]: (1, 2, 3)

In addition to tuples, custom functions can also return multiple values ​​through a dictionary.

In [4]: def f():
            a = 1
            b = 2
            c = 3
            return {'A': a, 'B': b, 'C': c}

        dic = f()
        print(dic)
        print(dic['C'])   # 可以应用字典的各类特性

Out[4]: {'A': 1, 'B': 2, 'C': 3}
        3

The method of returning multiple values ​​is of course indispensable for lists.

In [5]: def f():
            a = 1
            b = 2
            c = 3
            return [a, b, c]

        lst = f()
        print(lst)

Out[5]: [1, 2, 3]

At present, we have introduced several situations in which values ​​are returned in the form of tuples, dictionaries, and lists. Among the data structures we have learned, there is still a lack of form, that is, sets. We already know that the biggest difference between a collection and other centralized data structures is that it does not contain duplicate values. So, let's take a look at what happens if a function returns a value as a set, and the return value includes repeated elements?

In [6]: def f():
            a = 1
            b = 1
            c = 3
            return {a, b, c}

        set = f()
        print(set)

Out[6]: {1, 3}

As we thought, if the result of the custom function includes repeated elements, and the value is returned as a collection, the repeated elements will be eliminated and a collection that does not contain the repeated elements will be returned.

The above are several situations where a custom function returns multiple return values.

In fact, in addition to assigning values ​​to multiple different variables in sequence in the first example, the other way to return multiple values ​​is to "pack" multiple return values ​​through different data structures in the return statement.

If you show this process in another way, everyone will understand it better. Also return multiple instances of values ​​through the dictionary.

In [7]: def f():
            a = 1
            b = 2
            c = 3
            dic = {'A': a, 'B': b, 'C': c}
            return dic

        dic = f()
        print(dic)

Out[7]: {'A': 1, 'B': 2, 'C': 3}

By "packing" multiple return values ​​in advance, multiple return values ​​will eventually become one return value.

So, knowing this truth, there is no mystery about multiple return values, it's just that one line of sentences is missing, which makes it even more cool.

The above is our introduction to the return value of the custom function. Although there are various forms, the key is to find the most suitable way for us to return one or more values ​​from the custom function to the line of code we need.

At this point, the introduction of the custom function part has come to an end.

Because functions are too important, although the introduction of custom functions is over, we can't leave the function yet. In the next article, we will introduce a special function called "anonymous function", so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

"Learning Python with You Hand in Hand" 21-Tuples

"Learning Python with You Hand in Hand" 22-Dictionary

"Learning Python with You Hand in Hand" 23-Built-in Sequence Function

"Learning Python with You Hand in Hand" 24-Collection

"Learning Python with You Hand in Hand" 25-List Comprehension

"Learning Python with You Hand in Hand" 26-Custom Functions

"Learning Python with You Hand in Hand" 27-Parameters of Custom Functions

For Fans: Follow the "also said Python" public account, reply "Hand 28", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/110679573