Section 7****Function
Hello, everyone, have you realized that since we learned the program flow control statement in the last class, we have improved our problem-solving ability by an order of magnitude, from the category of points to the field of lines (or even countless lines) In fact, with these skills, we can already write complete Python programs.
However, let's take a closer look. We rely on existing grammatical tools (constants, variables, operators, expressions, flow control statements, etc.), and basically can only provide some linear-based solutions. In other words, the grammatical tools that we can use to implement the code are nothing more than the category that can be controlled by the flow control statement, and the maximum granularity of the objects handled by the code is still "variable". No matter how many lines of code you write, you can only follow or judge from top to bottom, or branch, or loop, or process all the variables that need to be processed in the process of calculation to complete any transaction logic to be processed. Therefore, all our code processing procedures are still limited to one-dimensional linear space.
**If our tools cannot break through the limitations of one dimension, cognition will not rise to a new dimension and will not be able to see a new world. **
In actual application development, we are often faced with intricate application requirements. So, does Python have more efficient language tools? The answer is: yes! This is the function we are going to learn today.
Simply put, a function is a named block of code.
It looks nothing new, but it adds a name to the code block. Yes, its meaning is definitely not how beautiful its name is, but because:
**1、 Such code blocks are allowed to contain any executable code. **
**2、 Can be used repeatedly and unlimitedly. **
Ever wondered what this actually means?
**It means that because of the introduction of functions, your application has expanded to a new dimension. Any useful code you have ever written, no matter how large or powerful it is (although usually limited), it can be encapsulated in a function, and this function will constitute a new application process A part, and it can be called repeatedly. Function as a new object, just like the previous variable, it will constitute a new part of your program code. It allows the maximum granularity of the object processed by your code from a single point (constant or variable), Become a face (function code block). Your code efficiency and reusability immediately get a qualitative leap. **
**So, don't underestimate the concept of functions. **
PS: This includes the idea of code reuse that a programmer must have. On the surface, it just reduces the programmer's labor and improves programming efficiency. In essence, it extends the application's problem-solving ability to a new dimension, from one-dimensional linear processing flow to two-dimensional or even higher dimensions. Maybe you need to actually write some time in the above text to truly understand its meaning and the essence of thought, but it does not matter, it is enough to attract your attention now.
1、 Function definition
(1) Use the def keyword.
(2) After the keyword, create a function name (identifier).
(3) After the function name, there is a pair of parentheses, which can include some variable names (parameters).
(4) Finally, end this line with a colon.
(5) Actually, the function does not end. The actual body of the function is behind, and a new line must be started and the code block of the function must be indented. The function that the code block can realize determines the meaning of the function.
def say_hello():
print('hello world')
say_hello() # call function
say_hello() # call the function again
**Note: **Please note that we can call the same function twice, which means we don't have to rewrite the code again.
PS: Students with experience in other languages may have discovered that the function definition method of Python is much more concise than the function (or method) of C/C++ or Java and C#, just like the definition of process control statements.
2、 Function parameters
The concept of function is probably the most important part of any complex software (no matter what programming language is used), so we will explore various aspects of functions in this section. The naming of functions, as a kind of identifier, has been discussed above. Here we focus on the issue of function parameters.
In the brackets after the function name, the function is allowed to get parameters through the variable name. The value of this parameter is assigned to it by the caller of the function. This forms a channel for passing variable values between the calling and the called. The concept of invocation will be discussed shortly below. Therefore, functions can use these values to do what they need. Multiple parameters are separated by commas.
**Please note that there is a term here: **
(1) The parameter name given when the function is defined is called "formal parameter" Parameters),
(2) When calling a function, provide valuable parameters to the function, called "** actual parameters**" (Arguments).
PS: If you want to be a professional programmer, these commonly used terms are best to blurt out.
def print_num(a, b):
if a > b:
print(a,'is a larger number!')
elif a == b:
print(a,'equal to', b)
else:
print(b,'is a smaller number!')
print_num(3, 4)
x = 5
y = 6
print_num(x, y)
**Explanation: **In the above example, a function named print_num is defined first, and this function is called twice. Please note that the function print_num has two formal parameters a and b. When we call this function, the (valued) actual parameters are passed to the formal parameters in order, that is, 2 and x are passed to a, and 4 and y are passed to it. It is important to emphasize this point, because below we will talk about another special case parameter called "key parameter", which passes the value not by order but by name. Please pay attention to the following.
3、 Local variables of functions
Please note that the variables we define in the function are local variables. In other words, it can only be valid within the scope of the function definition. In other words, the scope of variables in a function is the code block of this function.
x = 10
def func_3(x):
print('x is', x) #First print
x = 5
print('The value of the variable x inside the function:', x) #The second print
func_3(x)
print('The value of the variable x outside the function:', x) #The third print
**Description: **Please note that in this example, two variables named x are created at the same time outside and inside the function, but they are not the same variable in essence. Any custom variables inside the function are local variables of the function and are only valid within the function. However, even so, we still have to try to avoid this naming convention, because it is very easy to confuse the programmer, so that the program is wrong or produces inexplicable bugs. The above case is only set to illustrate that local variables cannot affect external variables.
4、 Function's global statement
In addition to local variables, there is also something called global variables. It is a top-level variable that does not limit any scope.
So, inside the function, what if you want to assign a value to a global variable? We need to use the global statement to accomplish this. Because it is impossible to assign a value to a variable defined outside the function without using the global statement.
x = 10 #This is a global variable
def func_4():
global x# where x is declared as a global variable
print('x value is:', x)
x = 5
print('The value of the global variable after the change is:', x)
func_4()
print('Display the value of x again:', x)
**Description: **
Please note that here are the three printed results:
(1) The first print, the output is the value of global variable x (10).
(2) The second printing, the output is the modified x value (5).
(3) The third time is a print statement, and the output is the current value of x (5), which has been modified by the function.
5、 Default parameters of the function
The parameters of a function are essentially variables. When the function is called, if there are parameters, the parameters should be assigned, that is, the formal parameters are assigned through the actual parameters. However, what happens if the parameter is not assigned a value during the call? According to Python's variable definition rules, the program will report an error when using an unassigned variable. For this reason, for some parameters, you can set default values for it to avoid errors when the user does not provide actual parameters when calling them.
**Please note that the default parameters of the ** function can only be located at the end of the parameter list. This order is mandatory.
**In fact, to set default values for the parameters of a function is to assign initial values to the parameters. However, please be careful not to assign mutable objects to default parameters. **
6、 Keyword parameters of the function
If your function has multiple parameters, and you only want to assign values to some of them when you call, then you can assign values to these parameters by naming them. This is the Keyword Arguments
Key parameters use names (keywords) rather than positions (the way we have always used them as mentioned above) to specify parameters in functions. This has two major advantages:
First, we no longer need to consider the order of the parameters, the use of functions will be easier.
Second, if other parameters have default parameter values, we can only assign values to those parameters that we want to assign.
def func_4(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func_4(3,7) #call one
func_4(25, c=24) #Call two
func_4(c=50, a=100) #Call three,
**Description: **
(1) The function func_4 has three formal parameters, but b and c have been assigned default values (also called initial values).
(2) Call one: By default, assign values to a and b in sequence.
(3) Call two: the first value is assigned to a in order, and the second value is assigned to c by the specified keyword.
(4) Call three: Regardless of the order, only assign values to the designated key parameters.
**Please note that ** When calling such a function with default parameters, no matter whether the key parameter assignment is specified or not, the non-default parameters of the function cannot be ignored. Values must be assigned and cannot be omitted.
7、 The return statement of the function
(1) The return statement of the function is used to return from the function, which is the interrupt function.
(2) When using the return statement, you can also choose to return a value from the function while interrupting the function. This return value can be received by the object that called the function. This is also an important feature of functions that we will use a lot.
def func_5(x, y):
if x > y:
return x
elif x == y:
return'These two numbers are equal! '
else:
return y
print(func_5(3, 3))
**Explanation: **The function contains a conditional branch statement. If any condition is met, the function will terminate and return the corresponding value.
8、 Function DocString
The function documentation string (docstring) is the documentation string used to describe the function at the beginning of the function. In short, it is the help document for the function, and you can use the help() built-in function to view the document. Even more amazing is that you can also use the doc attribute of the function to get the content of the document. In some advanced code editors, when calling a function, we move the mouse to the function name, it will help us display the function description text, which brings us great convenience in writing code. Therefore, we should get used to using function docstrings as much as possible. Generally, the description document should contain the following information:
1、 Basic information of the function
2、 Function description of the function
3、 The type and purpose of each formal parameter
def func_6(x, y):
''' Print the largest number of x and y.
Both x and y should be integers'''
x = int(x)
y = int(y)
if x > y:
print(x,'is a larger number!')
else:
print(y,'is a larger number!')
func_6(3, 5)#Call the function
print(func_6.doc)#Display (print) the description document of the function
Instructions:
1、 Placed in the first line of the function.
2、 Use triple quotation marks, such as ``'''', to compose a multi-line text string.
3、 The first line of the function document is generally a function overview, the second line is empty, and the third line is a detailed description. Please try to abide by this agreement.
View method
1、 In interactive mode, you can use help() to view the help documentation of the function.
2、 Use the doc attribute to view, you can get the description document of the function.
summary
In this lesson, we learned about functions. Not only learned the grammatical rules of function definitions, but more importantly, tried the methods of writing and using functions. Although it did not traverse all the function types of Python, it was enough to help us complete another leap in programming knowledge.
Recommended Posts