Python教程
Python 基础手册
Python 英语
Python 简介
Python 入门
Python 语法
Python 注释
Python 变量
Python 关键字
Python 快捷键
Python 数据类型
Python 布尔
Python 运算符
Python 占位符
Python If语句
Python For循环
Python While循环
Python 数字
Python 字符串
字符串 capitalize()
字符串 casefold()
字符串 center()
字符串 count()
字符串 encode()
字符串 endswith()
字符串 expandtabs()
字符串 find()
字符串 format()
字符串 format_map()
字符串 index()
字符串 isalnum()
字符串 isalpha()
字符串 isdecimal()
字符串 isdigit()
字符串 isidentifier()
字符串 islower()
字符串 isnumeric()
字符串 isprintable()
字符串 isspace()
字符串 istitle()
字符串 isupper()
字符串 join()
字符串 ljust()
字符串 lower()
字符串 lstrip()
字符串 maketrans()
字符串 partition()
字符串 replace()
字符串 rfind()
字符串 rindex()
字符串 rjust()
字符串 rpartition()
字符串 rsplit()
字符串 rstrip()
字符串 split()
字符串 splitlines()
字符串 startswith()
字符串 strip()
字符串 swapcase()
字符串 title()
字符串 translate()
字符串 upper()
字符串 zfill()
Python 列表
列表 append()
列表 clear()
列表 copy()
列表 count()
列表 extend()
列表 index()
列表 insert()
列表 pop()
列表 remove()
列表 reverse()
列表 sort()
Python 数组
Python 元组
元组 count()
元组 index()
Python 集合
集合 add()
集合 clear()
集合 copy()
集合 difference()
集合 difference_update()
集合 discard()
集合 intersection()
集合 intersection_update()
集合 isdisjoint()
集合 issubset()
集合 issuperset()
集合 pop()
集合 remove()
集合 symmetric_difference()
集合 symmetric_difference_update()
集合 union()
集合 update()
Python 字典
字典 clear()
字典 copy()
字典 fromkeys()
字典 get()
字典 items()
字典 keys()
字典 pop()
字典 popitem()
字典 setdefault()
字典 update()
字典 values()
Python 函数
内建函数 abs()
内建函数 all()
内建函数 any()
内建函数 ascii()
内建函数 bin()
内建函数 bool()
内建函数 bytearray()
内建函数 bytes()
内建函数 callable()
内建函数 chr()
内建函数 classmethod()
内建函数 compile()
内建函数 complex()
内建函数 delattr()
内建函数 dict()
内建函数 dir()
内建函数 divmod()
内建函数 enumerate()
内建函数 eval()
内建函数 exec()
内建函数 filter()
内建函数 float()
内建函数 format()
内建函数 frozenset()
内建函数 getattr()
内建函数 globals()
内建函数 hasattr()
内建函数 hash()
内建函数 help()
内建函数 hex()
内建函数 id()
内建函数 input()
内建函数 int()
内建函数 isinstance()
内建函数 issubclass()
内建函数 iter()
内建函数 len()
内建函数 list()
内建函数 locals()
内建函数 map()
内建函数 max()
内建函数 memoryview()
内建函数 min()
内建函数 next()
内建函数 object()
内建函数 oct()
内建函数 open()
内建函数 ord()
内建函数 pow()
内建函数 print()
内建函数 property()
内建函数 range()
内建函数 repr()
内建函数 reversed()
内建函数 round()
内建函数 set()
内建函数 setattr()
内建函数 slice()
内建函数 sorted()
内建函数 @staticmethod()
内建函数 str()
内建函数 sum()
内建函数 super()
内建函数 tuple()
内建函数 type()
内建函数 vars()
内建函数 zip()
Python 类和对象
Python 继承
Python 迭代器
Python 作用域
Python 模块
Python 日期
Python JSON
Python 正则表达式
Python PIP
Python Try Except
Python 命令行输入
Python 文件处理
文件处理 close()
文件处理 detach()
文件处理 fileno()
文件处理 flush()
文件处理 isatty()
文件处理 read()
文件处理 readable()
文件处理 readline()
文件处理 readlines()
文件处理 seek()
文件处理 seekable()
文件处理 tell()
文件处理 truncate()
文件处理 writeable()
文件处理 write()
文件处理 writelines()
Python 模块手册
Python 随机模块(Random)
Python OS模块
Python 请求模块(Requests)
Requests.delete()
Requests.get()
Requests.head()
Requests.post()
Python 数学模块(cmath)
Python math模块
Python 网络爬虫
HTTP 教程
HTTP/HTTPS 简介
HTTP 消息结构
HTTP 请求方法
HTTP 响应头信息
HTTP 状态码
Python 实例练习
练习001.算术运算
练习002.数字阶乘
练习003.计算面积
练习004.求取素数
练习005.计算平方
练习006.列表求和
练习007.数字偶数
练习008.列表删除
练习009.列表去重
练习010.列表排序
练习011.文件读写
练习012.计算分数
本文档使用 MrDoc 发布
-
+
首页
Python 函数
**函数是一种仅在调用时运行的代码块。 您可以将数据(称为参数)传递到函数中。 函数可以把数据作为结果返回。** ## 创建函数 在 Python 中,使用 def 关键字定义函数: 实例 ``` > def my_function(): > print("Hello from a function") ``` ### 调用函数 如需调用函数,请使用函数名称后跟括号: 实例 ``` > def my_function(): > print("Hello from a function") > > my_function() ``` ### 参数 信息可以作为参数传递给函数。 参数在函数名后的括号内指定。您可以根据需要添加任意数量的参数,只需用逗号分隔即可。 下面的例子有一个带参数(fname)的函数。当调用此函数时,我们传递一个名字,在函数内部使用它来打印全名: 实例 ``` > def my_function(fname): > print(fname + " Gates") > > my_function("Bill") > my_function("Steve") > my_function("Elon") ``` ### 默认参数值 下面的例子展示如何使用默认参数值。 如果我们调用了不带参数的函数,则使用默认值: 实例 ``` > def my_function(country = "China"): > print("I am from " + country) > > my_function("Sweden") > my_function("India") > my_function() > my_function("Brazil") ``` ### 以 List 传参 您发送到函数的参数可以是任何数据类型(字符串、数字、列表、字典等),并且在函数内其将被视为相同数据类型。 例如,如果您将 List 作为参数发送,它到达函数时仍将是 List(列表): 实例 ``` > def my_function(food): > for x in food: > print(x) > > fruits = ["apple", "banana", "cherry"] > > my_function(fruits) ``` ### 返回值 如需使函数返回值,请使用 return 语句: 实例 ``` > def my_function(x): > return 5 * x > > print(my_function(3)) > print(my_function(5)) > print(my_function(9)) ``` ### 关键字参数 您还可以使用 key = value 语法发送参数。 参数的顺序无关紧要。 实例 ``` > def my_function(child3, child2, child1): > print("The youngest child is " + child3) > > my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory") ``` 在 Python 文档中,“关键字参数”一词通常简称为 kwargs。 ### 任意参数 如果您不知道将传递给您的函数多少个参数,请在函数定义的参数名称前添加 *。 这样,函数将接收一个参数元组,并可以相应地访问各项: 实例 如果参数数目未知,请在参数名称前添加 *: ``` > def my_function(*kids): > print("The youngest child is " + kids[2]) > > my_function("Phoebe", "Jennifer", "Rory") ``` ### pass 语句 函数定义不能为空,但是如果您出于某种原因写了无内容的函数定义,请使用 pass 语句来避免错误。 实例 ``` > def myfunction: > pass ``` ### 递归 Python 也接受函数递归,这意味着定义的函数能够调用自身。 递归是一种常见的数学和编程概念。它意味着函数调用自身。这样做的好处是可以循环访问数据以达成结果。 开发人员应该非常小心递归,因为它可以很容易地编写一个永不终止的,或者使用过量内存或处理器能力的函数。但是,在被正确编写后,递归可能是一种非常有效且数学上优雅的编程方法。 在这个例子中,tri_recursion() 是我们定义为调用自身 ("recurse") 的函数。我们使用 k 变量作为数据,每次递归时递减(-1)。当条件不大于 0 时(比如当它为 0 时),递归结束。 对于新的开发人员来说,可能需要一些时间来搞清楚其工作原理,最好的方法是测试并修改它。 实例 递归的例子: ``` > def tri_recursion(k): > if(k>0): > result = k+tri_recursion(k-1) > print(result) > else: > result = 0 > return result > > print("\n\nRecursion Example Results") > tri_recursion(6) ``` ## 匿名函数 Lambda **lambda 函数是一种小的匿名函数。 lambda 函数可接受任意数量的参数,但只能有一个表达式。** 语法 ``` > lambda arguments : expression ``` 1. 实例 一个 lambda 函数,它把作为参数传入的数字加 10,然后打印结果: ``` > x = lambda a : a + 10 > print(x(5)) ``` 2. 实例 lambda 函数可接受任意数量的参数: 一个 lambda 函数,它把参数 a 与参数 b 相乘并打印结果: ``` > x = lambda a, b : a * b > print(x(5, 6)) ``` 3. 实例 一个 lambda 函数,它把参数 a、b 和 c 相加并打印结果: ``` > x = lambda a, b, c : a + b + c > print(x(5, 6, 2)) ``` 4. 实例 好像lambda就是省略了一个函数名,省略了一个return的关键词单词,然后把def替换为lambda ,再把函数的()前后两个括号去掉,把两行代码改为一行 ``` #普通函数 def add(a, b): return a+b print(add(2,3)) #匿名函数 add = lambda a, b: a + b print(add(2,3)) ``` 5. 实例 ``` #一维整数列表,把所有奇数都放到前面,偶数都放到后面 list1 = [19,32,76,82,23,63,38,50,20,30,39,14,19,50,81,27,77,12,55,29] a = sorted(list1,key=lambda x:x%2==0) print(a) 如果上面的 lambda函数改为常规的写法则是如下: list1 = [19,32,76,82,23,63,38,50,20,30,39,14,19,50,81,27,77,12,55,29] def demo(x): return x % 2==0 a = sorted(list1,key=demo) print(a) ``` ### 为何使用 Lambda 函数? 当您把 lambda 用作另一个函数内的匿名函数时,会更好地展现 lambda 的强大能力。 假设您有一个带一个参数的函数定义,并且该参数将乘以未知数字: ``` > def myfunc(n): > return lambda a : a * n ``` 使用该函数定义来创建一个总是使所发送数字加倍的函数: 实例 ``` > def myfunc(n): > return lambda a : a * n > > mydoubler = myfunc(2) > > print(mydoubler(11)) ``` 或者,使用相同的函数定义来创建一个总是使您发送的数字增加三倍的函数: 实例 ``` > def myfunc(n): > return lambda a : a * n > > mytripler = myfunc(3) > > print(mytripler(11)) ``` 或者,在同一程序中使用相同的函数定义来生成两个函数: 实例 ``` > def myfunc(n): > return lambda a : a * n > > mydoubler = myfunc(2) > mytripler = myfunc(3) > > print(mydoubler(11)) > print(mytripler(11)) ``` 如果在短时间内需要匿名函数,请使用 lambda 函数。 ## Python 内建函数 | 函数 | 描述 | | --- | --- | | [abs()](http://www.yunku.fun/doc/2124/) | 返回数的绝对值 | | [all()](http://www.yunku.fun/doc/2125/) | 如果可迭代对象中的所有项均为 true,则返回 True。 | | [any()](http://www.yunku.fun/doc/2126/) | 如果可迭代对象中的任何项为 true,则返回 True。 | | [ascii()](http://www.yunku.fun/doc/2127/) | 返回对象的可读版本。用转义字符替换 none-ascii 字符。 | | [bin()](http://www.yunku.fun/doc/2128/) | 返回数的二进制版本。 | | [bool() ](http://www.yunku.fun/doc/2129/)| 返回指定对象的布尔值。 | | [bytearray()](http://www.yunku.fun/doc/2130/) | 返回字节数组。 | | [bytes()](http://www.yunku.fun/doc/2131/) | 返回字节对象。 | | [callable()](http://www.yunku.fun/doc/2132/) | 如果指定的对象是可调用的,则返回 True,否则返回 False。 | | [chr()](http://www.yunku.fun/doc/2133/) | 返回指定 Unicode 代码中的字符。 | | [classmethod()](http://www.yunku.fun/doc/2134/) | 把方法转换为类方法。 | | [compile()](http://www.yunku.fun/doc/2135/) | 把指定的源作为对象返回,准备执行。 | | [complex() ](http://www.yunku.fun/doc/2136/)| 返回复数。 | | [delattr()](http://www.yunku.fun/doc/2137/) | 从指定的对象中删除指定的属性(属性或方法)。 | | [dict()](http://www.yunku.fun/doc/2138/) | 返回字典(数组)。 | | [dir() ](http://www.yunku.fun/doc/2139/)| 返回指定对象的属性和方法的列表。 | | [divmod()](http://www.yunku.fun/doc/2140/) | 当参数1除以参数2时,返回商和余数。 | | [enumerate()](http://www.yunku.fun/doc/2141/) | 获取集合(例如元组)并将其作为枚举对象返回。 | | [eval()](http://www.yunku.fun/doc/2142/) | 评估并执行表达式。 | | [exec()](http://www.yunku.fun/doc/2143/) | 执行指定的代码(或对象)。 | | [filter()](http://www.yunku.fun/doc/2144/) | 使用过滤器函数排除可迭代对象中的项目。 | | [float() ](http://www.yunku.fun/doc/2145/)| 返回浮点数。 | | [format() ](http://www.yunku.fun/doc/2146/)| 格式化指定值。 | | [frozenset()](http://www.yunku.fun/doc/2147/) | 返回 frozenset 对象。 | | [getattr()](http://www.yunku.fun/doc/2148/) | 返回指定属性的值(属性或方法)。 | | [globals()](http://www.yunku.fun/doc/2149/) | 以字典返回当前全局符号表。 | | [hasattr()](http://www.yunku.fun/doc/2150/) | 如果指定的对象拥有指定的属性(属性/方法),则返回 True。 | | [hash()](http://www.yunku.fun/doc/2151/) | 返回指定对象的哈希值。 | | [help()](http://www.yunku.fun/doc/2152/) | 执行内建的帮助系统。 | | [hex()](http://www.yunku.fun/doc/2153/) | 把数字转换为十六进制值。 | | [id()](http://www.yunku.fun/doc/2154/) | 返回对象的 id。 | | [input()](http://www.yunku.fun/doc/2155/) | 允许用户输入。 | | [int()](http://www.yunku.fun/doc/2156/) | 返回整数。 | | [isinstance()](http://www.yunku.fun/doc/2157/) | 如果指定的对象是指定对象的实例,则返回 True。 | | [issubclass()](http://www.yunku.fun/doc/2158/) | 如果指定的类是指定对象的子类,则返回 True。 | | [iter()](http://www.yunku.fun/doc/2159/) | 返回迭代器对象。 | | [len()](http://www.yunku.fun/doc/2160/) | 返回对象的长度。 | | [list() ](http://www.yunku.fun/doc/2161/)| 返回列表。 | | [locals()](http://www.yunku.fun/doc/2162/) | 返回当前本地符号表的更新字典。 | | [map()](http://www.yunku.fun/doc/2163/) | 返回指定的迭代器,其中指定的函数应用于每个项目。 | | [max()](http://www.yunku.fun/doc/2164/) | 返回可迭代对象中的最大项目。 | | [memoryview()](http://www.yunku.fun/doc/2165/) | 返回内存视图(memory view)对象。 | | [min()](http://www.yunku.fun/doc/2166/) | 返回可迭代对象中的最小项目。 | | [next()](http://www.yunku.fun/doc/2167/) | 返回可迭代对象中的下一项。 | | [object()](http://www.yunku.fun/doc/2168/) | 返回新对象。 | | [oct()](http://www.yunku.fun/doc/2169/) | 把数转换为八进制。 | | [open()](http://www.yunku.fun/doc/2170/) | 打开文件并返回文件对象。 | | [ord()](http://www.yunku.fun/doc/2171/) | 转换表示指定字符的 Unicode 的整数。 | | [pow()](http://www.yunku.fun/doc/2172/) | 返回 x 的 y 次幂的值。 | | [print() ](http://www.yunku.fun/doc/2173/)| 打印标准输出设备。 | | [property()](http://www.yunku.fun/doc/2174/) | 获取、设置、删除属性。 | | [range()](http://www.yunku.fun/doc/2175/) | 返回数字序列,从 0 开始且以 1 为增量(默认地)。 | | [repr()](http://www.yunku.fun/doc/2176/) | 返回对象的可读版本。 | | [reversed()](http://www.yunku.fun/doc/2177/) | 返回反转的迭代器。 | | [round()](http://www.yunku.fun/doc/2178/) | 对数进行舍入。 | | [set()](http://www.yunku.fun/doc/2179/) | 返回新的集合对象。 | | [setattr()](http://www.yunku.fun/doc/2180/) | 设置对象的属性(属性/方法)。 | | [slice()](http://www.yunku.fun/doc/2181/) | 返回 slice 对象。 | | [sorted()](http://www.yunku.fun/doc/2182/) | 返回排序列表。 | | [@staticmethod()](http://www.yunku.fun/doc/2183/) | 把方法转换为静态方法。 | | [str()](http://www.yunku.fun/doc/2184/) | 返回字符串对象。 | | [sum()](http://www.yunku.fun/doc/2185/) | 对迭代器的项目进行求和。 | | [super()](http://www.yunku.fun/doc/2186/) | 返回表示父类的对象。 | | [tuple()](http://www.yunku.fun/doc/2187/) | 返回元组。 | | [type()](http://www.yunku.fun/doc/2188/) | 返回对象的类型。 | | [vars()](http://www.yunku.fun/doc/2189/) | 返回对象的 __dict__ 属性。 | | [zip()](http://www.yunku.fun/doc/2190/) | 从两个或多个迭代器返回一个迭代器。 |
admin
2025年4月26日 15:16
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
分享
链接
类型
密码
更新密码