1. Function definition and call
函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段,
它能够提高应用的模块化和代码的重复利用率。
Python安装包、标准库中自带的函数统称为内置函数,
用户自己编写的函数称为自定义函数,
不管是哪种函数,其定义和调用方式都是一样的。
1.1 Define function
A function must have three important elements: the function name, and the function parameters and return value. The basic format of defining a function is as follows:
Example: Define a function to print information
def printInfo():
"""定义一个函数,能够完成打印信息的功能。"""
print('------------------------------------')
print(' 不忘初心,牢记使命 ')
print('------------------------------------')
1.2 Calling functions
After the function is defined, it is equivalent to a piece of code with certain functions. If you want these codes to be executed, you need to call it. Calling syntax:
Example: Call the printlnfo function.
def printInfo():
"""定义一个函数,能够完成打印信息的功能。"""
print('------------------------------------')
print(' 不忘初心,牢记使命 ')
print('------------------------------------')
printInfo()
operation result:
1.3 Nested function calls
在一个函数中调用了另外一个函数,这就是函数嵌套调用。
其执行流程为如果函数A中,调用了另外一个函数B,
则执行函数B中的任务后再回到上次函数A执行的位置。
# 计算三个数之和
def sum_num(a, b, c):
return a + b + c
# 求三个数平均值
def average_num(a, b, c):
sum_result = sum_num(a, b, c)
return sum_result / 3
result = average_num(1, 2, 3)
print(result)
operation result:
1.4 The return value of the function
The "return value" is the final result given to the caller after the function in the program completes one thing. grammar:
一般情况下,每个函数都有一个return语句,如果函数没有定义返回值,
那么返回值就是None.
Example: Define a function that adds two numbers.
def add_two_num(num_01, num_02):
return num_01 + num_02
number = add_two_num(1, 2)
print("num_01 + num_02 = ", number)
operation result: