Python introductory tutorial - basic functions (4)

Table of contents

1. What is a function

2. Customize the function and use it


1. What is a function

Earlier we learned things like input(), print(), type(), etc. They are all functions. These are actually defined for us internally by Python. We can just use it directly.

Regarding functions, in addition to using internally defined functions, we can also define functions ourselves and then use them.

So, let’s summarize:

Function: It is an organized, reusable code segment used to implement a specific function.

So, if it's like customization, how to define a function?

2. Customize the function and use it

Definition of function:
def function name (incoming parameters):
    Function body
    return return value

① If the parameters are not needed, they can be omitted (explained in subsequent chapters)
② If the return value is not needed, they can be omitted (explained in subsequent chapters)
③ Functions must be defined first and then used

# 定义
def substract():
    result = 10 - 2
    print("10 - 2 = %s" % result)
# 使用
substract()
10 - 2 = 8
def substract(a,b):
    result = a - b
    print("差值为: %s" % result)

substract(10, 8)
差值为: 2
def substract(a,b):
    result = a - b
    return result
print(substract(19, 8))
11
def test():
    print("测试")
print(test())
测试
None

None means: empty, meaningless
The None returned by the function means that the function does not return any meaningful content.
means that empty is returned.

In addition, if you define a variable, but you do not need the variable to have a specific value for the time being, you can use None instead.

Let me mention again, you can use comments inside the function to explain the parameter methods, as follows:

"""
函数的说明文档:
如下:
"""
def ok_add(a,b):
    """
    :param a:第一个参数
    :param b:第二个参数
    :return: 返回值
    """
    print("okkkk", a, b)
    return a + b

Guess you like

Origin blog.csdn.net/YuanFudao/article/details/132648382