Python函数与lambda 表达式(匿名函数)

Python函数

一、函数的作用

  • 函数是 组织好的可重复使用的,用来实现单一或相关联功能的代码段
  • 函数可以提高应用的模块化和代码的重用性
    [En]

    function can improve the modularity of the application and * the reuse of code * *

  • python 内置函数:https://docs.python.org/zh-cn/3.8/library/functions.html

二、函数的定义

def function_name([parameter_list]):        [''' comments ''']        [function_body]
  • def:函数定义关键词
  • function_name:函数名称
  • ():参数列表放置的位置,可以为空
  • parameter_list:可选,指定向函数中传递的参数
  • comments:可选,为函数指定 注释(如何打印函数中的注释)
  • function_body:可选,指定 *函数体
"""函数的定义""""""def function_name([parameter_list]):    [''' comments ''']  注释    [function_body]  函数体"""定义函数,参数为空(注释缩进)<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>Define the function, the argument is empty (note indentation)</font>*</details>def function_demo():  # 不要忘记冒号    print("我是一个函数")  # [function_body] 函数体定义函数,含有参数,注释def func_with_params(a, b, c):"""    这是一个携带参数和注释的函数  ---> comments"""    print(f"传入的参数为:a={a},b={b},c={c}") 打印函数comments(注释)1、__doc__  打印出注释print(func_with_params.__doc__)  # func_with_params()---->()没有括号2、help 打印函数和注释help(func_with_params)  # func_with_params()---->()没有括号空函数 (函数体未想好/功能暂时没想好怎么写)1、passdef filter_char(s):    pass2、commentsdef filter_char1(c):"""    功能:过滤铭感词"""
三、定义函数的注意事项:
  • 缩进:python 是通过严格的缩进来判断代码块儿
  • 函数体和注释相对于 def 关键字必须保持一定的缩进,一般都是 4 个空格
  • pycharm 自动格式化快捷键: ctrl+alt+L
  • 定义空函数
  • 使用 pass语句占位
  • 写函数注释 comments

四、函数的调用

function_name([parameter_value])
function_name:函数名称
parameter_value:可选,指定各个参数的值
"""函数的调用"""
无参函数调用
function_demo()
有参函数调用
func_with_params(1, 2, 3)

五、函数参数的使用

  • 形参:定义函数时,函数名后括号中的参数
    [En]

    formal parameter: when defining a function, the parameter in parentheses after the function name*

  • 实际参数:函数调用时,函数名称后面括号中的参数
    [En]

    actual parameters: the parameters in parentheses after the function name when the function is called*

"""函数参数的使用"""1、形式参数:定义函数时,函数名称后面括号中的参数def demo(a, b, v):  # a, b, v    print(f"传入的参数为:a={a},b={b},c={v}")2、实际参数:调用函数时,函数名称后面括号中的参数demo(1, 2, 4)  # 1,2,3实际参数
1、位置参数
  • 数量必须与定义时一致
  • 位置必须与定义时一致
"""位置参数"""def demo(a, b, v):    print(f"传入的参数为:a={a},b={b},c={v}")1、正确的demo(1, 2, 3)2、错误的例子,数量少了demo(1, 45)  # 有一个黄色提示  系统提示:TypeError: demo() missing 1 required positional argument: 'v'3、错误的例子,数量多了demo(1, 2, 3, 4)  # 有一个黄色提示  系统提示:TypeError: demo() takes 3 positional arguments but 4 were givendef person(name, age):    print(f"姓名{name}")    if age > 18:        print(f"{name}已成年")    else:        print(f"{name}未成年")4、顺序错person(22, 'tom')  # TypeError: '>' not supported between instances of 'str' and 'int'5、正常person('jack', 28)
2、关键字参数
  • 使用形参名称确定输入参数值
    [En]

    use the name of the formal parameter to determine the input parameter value*

  • 不需要与形参的位置完全相同
    [En]

    does not need to be exactly the same as the position of the formal parameter*

"""关键字参数"""def person(name, age):    print(f"姓名:{name}")    if age > 18:        print(f"{name}已成年")    else:        print(f"{name}:未成年")person(age=25, name='杨幂')
3、设置默认参数
  • 您可以在定义函数时指定形式参数的默认值
    [En]

    you can specify the default value of formal parameters when defining a function*

  • 指定默认值的形式参数 必须放在所有参数的最后,否则会产生语法错误
  • param=default_value:可选,指定参数并且为该参数设置默认值为 default_value
  • 注:设置形参的默认值。默认使用不变对象(整数、浮点、元组、布尔值、字符串)和变量对象(字典、列表)。默认值可能会提示呼叫中的更改。
    [En]

    Note: set default values for formal parameters. * default values use immutable objects * (integer, floating point, tuple, Boolean, string), and variable objects (dictionary, list). Default values may prompt changes in the call.*

注意:设置形参的默认值,形参使用不可变对象(整数、浮点、元组、布尔、字符串)和可变对象(字典、列表)。<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>Note: set default values for formal parameters, which use immutable objects (integer, floating point, tuple, Boolean, string) and mutable objects (dictionary, list).</font>*</details>错误演示。默认为空列表。<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>Error demonstration. Default is empty list.</font>*</details>def wrong_demo2(a, b, c=[]):    c.append(a)    c.append(b)    print(a, b, c)wrong_demo2(1, 2)wrong_demo2(3, 4)"""设置默认参数"""def person(name, age, international='中国'):    print(f"姓名:{name}")    print(f"国籍为{international}")    if age > 18:        print(f"{name}已成年")    else:        print(f"{name}:未成年")person(name='jace', age=30)person(name='tom', age=25, international='美国')错误,缺省值没有放在末尾<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>Wrong, the default value is not put at the end</font>*</details>def age(a=18, c, b):age(c, b)   # 系统报错:SyntaxError: non-default argument follows default argument
4、可变参数
  • 可变参数也称为无限长度参数
    [En]

    variable parameters are also known as indefinite length parameters*

  • 传入函数中的实际参数可以是任意数量的参数
    [En]

    the actual parameters in the passed-in function can be any number of arguments*

  • 常见形式()
  • *args 接收任意多个 实际参数,并将其放到一个 元组中 使用已经存在的 列表或元组作为函数的可变参数,可以在列表的名称前加 *
  • **kwargs 接收任意多个类似 关键字参数一样显式赋值的实际参数,并将其放到一个 字典中 使用已经存在字典作为函数的可变参数,可以在字典的名称前加 **
*args 接收任意多个实际参数,并将其放到一个元组中函数定义中的*args相当于打包def print_language(*args):    print(args)    for a in args:        print(a)调用该函数,传入不同数量的参数,并使用Position参数<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>Call the function, pass in a different number of parameters, and use the position parameter</font>*</details>print_language('python', 'java')print_language('python', 'java', 'php', "go")函数调用时*args相当于解包lis = ['python', 'java', 'php', "go"]相当于 print_language('python', 'java', 'php', "go")print_language(*lis)**kwargs 接收任意多个类似关键字参数一样显式赋值的实际参数,并将其放到一个**字典**中函数定义中的**kwargs相当于打包def print_info(**kwargs):    print(kwargs)    for a in kwargs.items():        print(a)print_info(tom=18, jack=24)print_info(tom=18, jack=24, Aice=25)函数调用时**kwargs相当于解包di = {'cat': 18, 'jace': 24, 'alict': 65}print_info(**di)

六、函数返回值

def function_name([parameter_list]):
    [''' comments ''']
    [function_body]
    return [value]

value:可选,指定要返回的值

"""函数返回值"""

定义加法函数
def sum(a, b):
    result = a + b
    # 函数返回值
    # return result, a, b  # 返回保存元组

r = sum(1, 2)
print(r)

lambda 表达式(匿名函数)

1、使用场景
  • 需要一个函数,但不必费心给它命名
    [En]

    need a function, but don’t bother to name it*

  • 通常在此函数仅使用一次的情况下
    [En]

    usually in scenarios where this function is used only once*

  • 可以指定短小的回调函数
2、语法
result = lambda [arg1 [, arg2, .... , argn]]: expression
  • result:调用 lambda 表达式
  • [arg1 [, arg2, …. , argn]]:可选,指定要传递的参数列表
  • expression:必选,指定一个实现具体功能的表达式
常规写法def circle_area(r):"""    计算圆的面积    r:半径"""    result = math.pi * r ** 2    return resultr = 10print(f"半径为{r}的面积为{circle_area(r)}")lanbda表达式result = lambda 参数 : expressionresult = lambda r: math.pi * r ** 2print(f"半径为{r}的面积为{circle_area(r)}")对获取到的信息进行排序book_info = [    ('python', 15),    ('javn', 100),    ('软件测试基础', 25)]print(book_info)指定规则排列lambda x: (x[1]) 返回了列表中每book_info.sort(key=lambdaprint(book_info)

Original: https://www.cnblogs.com/jiuyou-emperor/p/15807537.html
Author: 九幽帝君
Title: Python函数与lambda 表达式(匿名函数)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/510232/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球