Python programming basics: functions (1)

1. Basic concepts of functions

When using Python to implement certain complex functions, it is easy to encounter some code with a high repetition rate. In order to reuse the code and improve the neatness of the code, functions are often used. Functions can be used to decompose complex problems into several sub-problems. Once a function is written for a certain sub-problem, this function can be called at any time to implement specific sub-functions.
There is the concept of function in mathematics, which represents the mapping relationship from independent variables to dependent variables. Functions in Python are similar, representing the process of obtaining a predetermined output after certain changes and processing of the input.
For example, the function sorted() used in list sorting has the following syntax:

sorted(列表,reverse)

The function name is sorted, and the formal parameters are list and reverse. When a specific list and a specific value of reverse are given, the specific actual parameters are given, and then the sorted content of the list can be returned.
Therefore, there are two concepts of functions: formal parameters and actual parameters.
The formal parameters represent the parameter forms given when defining the function, and the actual parameters represent the specific values ​​of the parameters given when the defined function is called.
In the Python language, functions can be divided into four categories:

  1. Built-in functions, such as abs(), sorted(), etc., can be used directly when writing programs;
  2. Standard library functions, functions in the standard library that come with Python installation, such as math, random, etc., need to be imported into the standard library using import, and then used;
  3. For third-party library functions, the Python community provides many other high-quality libraries, such as pandas, numpy, etc., which can be downloaded and installed separately and then imported using import.
  4. Custom functions are functions written by users themselves.

2. Definition and use of functions

1. Definition and calling of functions

The syntax format for defining functions is as follows:

def 函数名([形参列表]):
    函数体

In the above content, the formal parameter list part in parentheses can have no parameters, one parameter or multiple parameters. If there are multiple parameters, each parameter should be separated by commas, and the [] part needs to be deleted when actually writing. In addition, the ":" after the parentheses is required, and there is a space indentation between the following function body and def.
If the defined function has a return value, a return statement needs to be added to the function body. There can be multiple return statements, but once the first return statement is executed, the function will terminate immediately. The return statement can appear anywhere in the function body.
The syntax for calling a function is as follows:

函数名([实参列表])

In the above content, the actual parameter list refers to the parameter content actually passed to the function. The [] part needs to be deleted when actually writing. The actual parameter list generally needs to correspond one-to-one with the formal parameter list in the function.

Note: Generally speaking, formal parameter variables can only receive the value of the actual parameter variable, but cannot access the actual parameter variable. However, when the actual parameter variable is a list type (variable object), the formal parameter will be a reference to the object. The value of the elements inside it can be modified directly in the function.

If there is a return value in the function, it can be used in the expression. If not, it can be used as an expression statement alone.
Insert image description here
In the above example, the function name is max, and the parameters in the formal parameter list are x1, x2, and x3. In the function body, the incoming parameters are mainly compared, and finally the return statement is used to return the maximum value. The input function is used below to pass Enter the three keyboard input numbers, then pass these three numbers as actual parameters to the function max, then assign the return value to the variable y, enter y to get the corresponding maximum value.

2. Function parameters

The parameter settings in the function determine the result after the function is run. There are four main ways to set parameters, default value parameters, positional parameters, name passing parameters and variable parameters.

Default value parameters
When declaring parameters, if you want some parameters of the function to be optional, you can specify default values ​​for these parameters when declaring the function. When calling the function, if the corresponding actual parameter value is not passed in, the function uses the default value. The parameter value, the default value parameter needs to be written on the rightmost side of the formal parameter list.
Insert image description here
In the above example, x3 does not pass in the corresponding parameter value when calling the function, so the function uses the default parameter value 1.

Positional parameters
Positional parameters mainly mean that when calling a function, they are passed in the order of position by default.
Insert image description here
In the above example, the actual parameters are passed to the formal parameters in the order of position by default, that is, x1, x2, and x3 correspond to int(num1), int(num2), and int(num3) respectively.

Name-passing parameters
Name-passing parameters mainly refer to passing in specified parameters through the names of formal parameters when calling a function, also known as keyword parameters.
Insert image description here
Variable parameters
When defining a function, using parameters with an asterisk, such as *param, means passing a variable number of parameters, and all parameters passed in from this parameter will be combined into a tuple.
Insert image description here
In the above example, there are two calls to the function. When the function count() is called for the first time, there are 4 scores in each subject passed; when the function count() is called the second time, there are 6 scores in each subject passed. Each time the "extra" actual parameters passed to the function are collected as tuple fractions of formal parameters, the corresponding total score and average score are calculated.
In addition, if you use a parameter with two asterisks, such as **param, it means passing a variable number of parameters, and all parameters passed in from this parameter will be combined into a dictionary.
Insert image description here

In the above example, a function named stu was written, which has two parameters, one is the positional parameter term, and the other is the parameter **pern, which is a parameter used to receive the passed dictionary.

The function of this function is to first pass the incoming actual parameters into the formal parameters term and **pern respectively. The elements in the latter will be automatically saved as a dictionary, then sorted and output in ascending order according to the key, and finally selected from pern. Find out those who failed, form a new dictionary fail, and output the number of failed students and their list at the same time.

3. Return multiple values

Use the return statement in the function body to jump out and return a value during execution. If you want to return multiple values, you can return a tuple.
Insert image description here
Python programming basics: functions (2)

Guess you like

Origin blog.csdn.net/weixin_42051846/article/details/131828485