Python study notes (four): function definition and call

1. Define function and call function

The specific usage is shown in the following code:

'''
1.定义函数和调用函数
'''
# 定义一个函数,声明两个形参
def my_max(x, y) :
    # 定义一个变量z,该变量等于x、y中的最大值
    z = x if x > y else y
    # 返回变量z的值
    return z

# 定义一个函数,声明一个形参
def say_hi(name) :
    print("=====正在执行say_hi()函数=====")
    return "你好," + name

a = 6
b = 9
# 调用my_max()函数,将函数返回值赋值给result变量
result = my_max(a, b)
print("result:", result)
# 调用say_hi()函数,直接输出该函数的返回值
print(say_hi("李焕英"))

2.help() function

help() function: can be used to view the help document of the specified function. The code is as follows:

'''
2.help()函数:可用于查看指定函数的帮助文档
'''
def my_max(x, y) :
    '''
    获取两个数值之间较大数的函数
    :param x:
    :param y:
    :return:
    '''

    # 定义一个变量z,该变量等于x、y中较大的值
    z = x if x > y else y
    # 返回变量z的值
    return z

# 使用help()函数查看my_max()的帮助文档
help(my_max)
print(my_max.__doc__)

3. Multiple return values

If the Python function returns multiple values, Python will automatically encapsulate the multiple return values ​​into tuples.

Requirement: the sum and average value of the numerical elements in the statistics list. The code is as follows:
 

'''
3.如果Python函数返回多个值,Python会自动将多个返回值封装成元组

需求:统计列表中数值元素的总和、平均值
'''
def sum_and_avg(list) :
    sum = 0
    count = 0
    for ele in list :
        if isinstance(ele, int) or isinstance(ele, float) :
            sum += ele
            count += 1

    return sum, sum / count
my_list = [20, 15, 2.8, 'a', 35, 5.9, -1.8]
# 第一种方式:获取sum_and_avg()函数返回的多个值,多个返回值被封装成元组
# my_tuple = sum_and_avg(my_list)
# print(my_tuple)

# 第二种方式:使用序列解包来获取多个返回值
s, avg = sum_and_avg(my_list)
print("总和:", s)
print("平均值:", avg)

4. Recursive function

Recursive function: call itself in a function body

Requirements: Know a sequence: f(0)=1, f(1)=4, f(n+2)=2*f(n+1)+f(n), where n is an integer greater than 0, Find the value of f(10). The code is as follows:
 

'''
4.递归函数:在一个函数体内调用它自身
需求:已知一个序列:f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n),其中n是大于0的整数,求f(10)的值。
'''
def fn(n) :
    if n == 0 :
        return 1
    elif n ==1 :
        return 4
    else :
        return 2 * fn(n - 1) + fn(n - 2)
# 输出fn(10)的结果
print("fn(10)的结果是:", fn(10))

 

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/113830684