Python 函数

6 阅读1分钟

1.函数定义

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

['''文档字符串''']

函数体

return语句

2.定义练习

def add():
    result = 11 + 22
    print(result)

def add_2(a,b):
    result = a + b
    print(result)


def add_3(a,b):
    result = a + b
    print(result)
    return result


c = a 会报错,函数内的参数不能在外部使用

3.调用练习

函数定义以后不会运行,调用才会运行

add_2(a=5, b=9)

add_2(b=10,a=2)

re3 = add_3(a=10,b=3)

4.嵌套扩展

嵌套函数不能被外部直接调用,只能由嵌套的外层调用

def add_4(a,b):
    result = a + b
    print(result)
    def test():
        print("内层函数")
    test()
add_4(a=10, b=20)

5.函数参数的传递

位置参数传递,按照位置顺序进行传递

def get_max(a,b):
    """
    获取两个数之间的最大值
    """
    if a>b:
        print(a,"是最大值")
    else:
        print(b,"是最大值")

get_max(a:10,b:5)