Python函数

5 函数

5.1 定义函数

模块化编程指把程序进行封装(函数封装,面向对象,文件)

什么是函数?

函数==>功能:就是具有特定功能的代码块

函数的作用?

函数就是把代码进行封装,以提高代码的重用性,提高开发效率,并且降低了后期的维护成本。

函数的定义和使用?

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n13" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 定义函数[基本函数]
def 函数名([参数列表]):
当前函数的具体功能代码
当前函数的具体功能代码
...

函数封装完并不会执行,只是把函数定义了而已。如果想使用已经定义的函数,那么就需要函数调用

函数调用

函数([参数列表])</pre>

  • 函数定义---普通参数

  • 函数定义---默认参数

  • 函数定义---收集参数

  • 函数定义---命名关键字参数

  • 函数定义---关键字参数收集

  • 函数返回值

code:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n29" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">"""
函数可以分为两类:
1.执行过程函数:函数体内完成一定的功能即可,没有返回值
2.具有返回值的函数:函数体完成一定的功能,并且返回一个结果到函数调用处
"""

******************************************

函数定义---普通参数:就是必须传递的参数

def love():
print("i love you")

******************************************

函数参数

函数在定义时,可以在参数列表的位置定义形参

如果函数有形参,那么在调用时必须传递参数(实参)

实参传递给形参的过程,本质上就是变量的赋值操作

def lovejasmine(w):
print(f"i love you {w}")

函数定义---默认参数:在定义形参时指定默认值(和C++一样)

def loveyou(x, w='Jasmine'):
print(f"{x} love {w}")

函数定义---收集参数:定义一个形参专门收集多余的实参 或者理解为---不确定需要传递多少个实参,直接用一个形参来接收

在定义函数时如果需要收集参数,那么这个形参前面需要加一个号 例如args(args可以是别的名字)

接收的多余的参数会存储在args中,形成一个元组

def func(x='+', *args):
print(type(args))
if x == '+':
print('加法运算', sum(args))
else:
print('减法运算', sum(args))

函数定义---命名关键字参数 在调用时必须给形参的名字传递参数

定义在收集参数之后的参数就是命名关键字参数

def func2(a, b, c=10, *args, name):
print(a, b, c, *args, name)

函数定义---关键字参数收集---kw==keyword---会把多余的关键字参数收集为字典

def func3(a, b, c=3, *args, name, **kwargs):
print(a, b, c)
print(name, type(name))
print(args, type(args))
print(kwargs, type(kwargs))

******************************************

函数返回值---函数完成功能后按需返回数据

使用return关键字来指定返回数据,可以返回一些任意类型的数据

函数的返回值,会把数据返回到调用处,可以使用变量接收或直接作为函数的参数等

没有返回值的函数---这句之前定义的函数都是没有返回值的函数

return意味着函数的结束,return后面的语句不再执行

没有返回值的函数会返回一个None,None是一个特殊的数据,就表示没有的意思

def func4(a, b):
if a > b:
return a
else:
return b

函数调用---函数定义后,不调用不执行---

在函数定义之后才能调用函数---可以无限次调用已定义函数

函数名要遵循命名规范---函数名冲突的话会被覆盖

函数定义了几个参数,那么在调用时就必须按指定顺序进行参数的传递

print("#普通参数**********************************************")
love()
lovejasmine('Jasmine')
print("#默认参数**********************************************")
loveyou('Boooooo~')
loveyou('Boooooo~', 'Jasmine')
print("#收集参数**********************************************")
func('+', 123, 456, 789)
print("#命名关键字参数**********************************************")
func2(1, 2, 3, 4, 5, 6, 7, 8, name=9)
print("普通函数也可以使用关键字传参方式-----------------")
lovejasmine(w="Booooooo") # 但是呢最好不要用,因为在函数参数类型较多时,运行可能会报错
print("#关键字参数收集**********************************************")
func3(1, 2, 3, 4, 5, 6, name=7, sex='girl', age=24)

注意形参声明的顺序--普通参数、默认参数、收集参数、关键字参数、关键字收集参数

极少情况下会出现五种类型的形参,一般情况下有普通参数、收集参数、关键字参数

print("#函数返回值**********************************************")
x = func4(10, 11)
print(f'who is bigger? {x}')</pre>

运行结果:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n32" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_13Function.py

普通参数**********************************************

i love you
i love you Jasmine

默认参数**********************************************

Boooooo~ love Jasmine
Boooooo~ love Jasmine

收集参数**********************************************

<class 'tuple'>
加法运算 1368

命名关键字参数**********************************************

1 2 3 4 5 6 7 8 9
普通函数也可以使用关键字传参方式-----------------
i love you Booooooo

关键字参数收集**********************************************

1 2 3
7 <class 'int'>
(4, 5, 6) <class 'tuple'>
{'sex': 'girl', 'age': 24} <class 'dict'>

函数返回值**********************************************

who is bigger? 11

Process finished with exit code 0</pre>

5.2 变量作用域及函数文档

5.2.1 全局变量和局部变量

  • 变量作用域

  • 全局变量

  • 局部变量

  • 变量数据类型分类

  • globals()

  • locals()

  • 嵌套函数

code:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n52" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># **********************************************************
"""
变量作用域:就是变量的有效范围
全局变量:
1.在函数外部定义的变量,可称为全局变量,这种变量在函数内部可以访问但不可以更改变量内容
如果需要在函数内部更改变量内容,则需要在修改内容之前使用global关键字引用改变量
2.在函数内部直接使用global定义的变量,函数内部和外部都可以访问和修改
局部变量:
在函数内定义的变量,只在函数内部有效,函数外部不可获取&更改
变量数据类型分类:
1.可变数据类型:在函数外定义的变量,在函数内可以获取&更改---列表和字典
2.不可变数据类型:在函数外定义的变量,在函数内只能获取,不能更改
globals()---获取全局数据(包含变量和函数)
locals()---获取当前作用域的数据
不光变量有作用域,函数也有相同的作用域
全局函数:就是在脚本中直接定义的函数,不是某函数的嵌套
局部函数:就是函数中的函数
"""
num = 10
name = 'Jasmine'
varlist = [1,2,3,4,5]
vardict = {'a':1,'b':2}
print("# 经过函数之前***********************************")
print(f"Varlist = {varlist},{type(varlist)}")
print(f"vardict = {vardict},{type(vardict)}")

def func():

num += 20---这句会报错---原因是函数内部不允许更改函数外部的变量

print(f"函数外部定义的全局变量name可访问---name = {name}")

global name
name = 'Boooo~'
global daysay
daysay = 'Nice to meet you'
love = "Love Jasmine"
print(f"函数外部定义的全局变量num可访问但不可更改num = {num}", love) # 全局变量num可访问但不可更改
print(f"添加global引用的函数外部定义的全局变量name可修改---name = {name}")
print(f'函数内部使用关键字global定义的全局变量daysay = {daysay}')
varlist[1] = 99 # 可变数据类型
vardict['a'] = 99 # 可变数据类型
print(locals())

def func1():
print("调用func1()函数******************")

def func11():
print("调用func11()函数*******************")

func11()

print("# 经过函数之后***********************************")

love = "Boly"---这句会报错,原因是不可以在函数外部访问&更改局部变量

func()
daysay = 'You,too'
print(f'函数内部使用关键字global定义的全局变量在函数外部可更改daysay = {daysay}')
print(f"Varlist = {varlist},{type(varlist)}")
print(f"vardict = {vardict},{type(vardict)}")
print(globals())
print("# 嵌套函数**********************************************")
func1()</pre>

运行结果:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n55" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_14Variable_Scope.py

经过函数之前***********************************

Varlist = [1, 2, 3, 4, 5],<class 'list'>
vardict = {'a': 1, 'b': 2},<class 'dict'>

经过函数之后***********************************

函数外部定义的全局变量num可访问但不可更改num = 10 Love Jasmine
添加global引用的函数外部定义的全局变量name可修改---name = Boooo~
函数内部使用关键字global定义的全局变量daysay = Nice to meet you
{'love': 'Love Jasmine'}
函数内部使用关键字global定义的全局变量在函数外部可更改daysay = You,too
Varlist = [1, 99, 3, 4, 5],<class 'list'>
vardict = {'a': 99, 'b': 2},<class 'dict'>
{'name': 'main', 'doc': '\n变量作用域:就是变量的有效范围\n全局变量:\n 1.在函数外部定义的变量,可称为全局变量,这种变量在函数内部可以访问但不可以更改变量内容\n 如果需要在函数内部更改变量内容,则需要在修改内容之前使用global关键字引用改变量\n 2.在函数内部直接使用global定义的变量,函数内部和外部都可以访问和修改\n局部变量:\n 在函数内定义的变量,只在函数内部有效,函数外部不可获取&更改\n变量数据类型分类:\n 1.可变数据类型:在函数外定义的变量,在函数内可以获取&更改---列表和字典\n 2.不可变数据类型:在函数外定义的变量,在函数内只能获取,不能更改\nglobals()---获取全局数据(包含变量和函数)\nlocals()---获取当前作用域的数据\n不光变量有作用域,函数也有相同的作用域\n全局函数:就是在脚本中直接定义的函数,不是某函数的嵌套\n局部函数:就是函数中的函数\n', 'package': None, 'loader': <_frozen_importlib_external.SourceFileLoader object at 0x000001D3E40E6D00>, 'spec': None, 'annotations': {}, 'builtins': <module 'builtins' (built-in)>, 'file': 'D:\Prj\Python\Study_Basic_Grammar\_14Variable_Scope.py', 'cached': None, 'num': 10, 'name': 'Boooo~', 'varlist': [1, 99, 3, 4, 5], 'vardict': {'a': 99, 'b': 2}, 'func': <function func at 0x000001D3E412F040>, 'func1': <function func1 at 0x000001D3E4868310>, 'daysay': 'You,too'}

嵌套函数**********************************************

调用func1()函数******************
调用func11()函数*******************

Process finished with exit code 0</pre>

5.2.2 nolocal关键字

code:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n59" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># **************************************

在内函数中如何使用上一层函数中的局部变量?

在内函数中能够访问外函数中定义的局部变量,但是不可更改;如果需要更改的话,可以使用nolocal关键字

nolocal关键字是在内函数中使用,目的是为了使得内函数能够修改外函数定义的变量

注意事项:使用nolocal引用的变量依然是局部变量,在函数外部不能访问和修改

定义一个外层函数

def func1():

外函数的局部变量

num = 10
print(f"调用func1()函数-------------num = {num}")

内函数,局部函数:在函数内部定义的函数

def func11():

print(num) # 可以获取但是不能更改,不能使用global

nonlocal num
num += 1
print(f"调用func11()函数-----------num = {num}")

func11()

print("nolocal关键字**********************************************")
func1()</pre>

运行结果:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n62" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_15Nonlocal_Keyword.py
nolocal关键字**********************************************
调用func1()函数-------------num = 10
调用func11()函数-----------num = 11

Process finished with exit code 0</pre>

5.3 关于脚本文档

code:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n66" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">def func():
"""
这里写的函数说明
:return:
"""
print("函数说明!")

name = 10
x = 20
print(globals())
print(name) # 获取当前脚本的名字
print(doc) # 获取当前脚本的说明文档

如何获取函数的说明(doc)文档

print(func.doc)
"""

脚本文档

var叫作魔术变量
name==>当前脚本作为主程序,那么值是main;如果是当作一个模块,在另外一个脚本中引用去使用,那么值就是当前文件的名字
doc==>当前脚本的1文档说明--在当前脚本当中的第一个 三引号 注释 就是当前脚本的说明文档
{
'name': 'main',
'doc': None,
'package': None,
'loader': <_frozen_importlib_external.SourceFileLoader object at 0x00000254884C6D00>,
'spec': None,
'annotations': {},
'builtins': <module 'builtins' (built-in)>,
'file': 'D:\Prj\Python\Study_Basic_Grammar\_16Function_doc.py',
'cached': None, 'name': 10, 'x': 20
}
"""</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n69" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_16Function_doc.py
{'name': 'main', 'doc': None, 'package': None, 'loader': <_frozen_importlib_external.SourceFileLoader object at 0x000001DD1FBB6D00>, 'spec': None, 'annotations': {}, 'builtins': <module 'builtins' (built-in)>, 'file': 'D:\Prj\Python\Study_Basic_Grammar\_16Function_doc.py', 'cached': None, 'func': <function func at 0x000001DD1FBFF040>, 'name': 10, 'x': 20}
main
None

这里写的函数说明
:return:

Process finished with exit code 0
</pre>

5.4 递归

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n73" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># **********************************************

递归函数

"""
递归函数:定义了一个函数,然后在函数内,自己调用自己
要求:递归函数内必须要有结束,不然就会一直调用下去,直到调用的层数越多,最终栈溢出
注意事项:递归函数的效率很低,尽量不用递归函数
"""

def factorial(n):
if n == 1:
print("1 = ",end="")
return 1
else:
print(f"{n}*", end="")
return n * factorial(n - 1)

print(factorial(7))
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n76" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_17Function_Recursion.py
8765432*1 = 40320

Process finished with exit code 0
</pre>

5.5 回调函数

  • 自定义回调函数

  • 将函数库里面的函数作为回调函数

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n85" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># **************************************************

回调函数:被作为形参并被调用的函数

将回调函数作为形参的函数

自定义回调函数

def func(f):
print(f"我是带有回调函数参数的函数,刚刚调用了{f}函数!")
print(f"其类型为{type(f)}")
f()

def callbackfun():
print("我是回调函数,刚刚有函数调用我了!")

*****************************************************

将函数库里面的函数作为回调函数

def callfunc(a, b, f):
# 这个函数是将a和b作为参数传递给f函数,调用f函数,输出返回值
print(f"{f}函数的输出结果为:{f([a, b])}")

print("# 自定义回调函数*********************************")
func(callbackfun)
print("# 将函数库里面的函数作为回调函数*********************************")
callfunc(1, 2, sum)
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n88" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_18Callback_Function.py

自定义回调函数*********************************

我是带有回调函数参数的函数,刚刚调用了<function callbackfun at 0x000001CA33DC8040>函数!
其类型为<class 'function'>
我是回调函数,刚刚有函数调用我了!

将函数库里面的函数作为回调函数*********************************

<built-in function sum>函数的输出结果为:3

Process finished with exit code 0
</pre>

5.6 闭包函数

  • 全局变量弊端

  • 解决全局变量弊端--闭包函数

  • 闭包函数特点

  • 如何检查某函数是否为闭包函数?

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n101" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># *********************************************
"""

闭包函数:外函数返回的内函数,并且该内函数还使用了外函数的局部变量,称为闭包函数

返回的内函数叫做 闭包函数,整个函数叫做 闭包

全局变量弊端:全局变量有风险,因为所有函数都能用

闭包函数的特点:

1.在外函数中定义了局部变量,并且在内部函数中使用了这个局部变量
2.在外函数中返回了内函数,返回的内函数就是闭包函数
3.主要是保护了外函数中的局部变量不受外部的影响,但是又不影响使用

如何检测一个函数是否为闭包函数:函数名.closure 如果是闭包函数,返回一个cell;否则,返回None

"""
money = 0

def work():
global money
money += 100

def overtime():
global money
money += 200

def shopping():
global money
money -= 50
money = 0 # 就突然清零了,然后钱就没了

闭包函数*******************************************************************

def func():
money1 = 0

def work1():  # 在外函数中定义了内函数
    nonlocal money1  # 在内函数中调用了外函数的临时变量
    money1 += 100
    print(f"money = {money1}")

def overtime1():
    nonlocal money1
    money1 += 200
    print(f"money = {money1}")

def shopping1():
    nonlocal money1
    money1 -= 50
    print(f"money = {money1}")
return work1  # 闭包函数

print("# 全局变量有风险***************************************")
work()
work()
overtime()
shopping()
print(money)
print("# 因此需要改进****************************************")
print("# 闭包函数****************************************")
res = func()

此时就不能够在全局中对money1这个局部变量进行操作了

res()
res()
print("# 检测是否是闭包函数****************************************")
print(f"非闭包函数:{work.closure}") # 非闭包函数
print(f"闭包函数:{res.closure}") # 闭包函数
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n104" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_19Closure_Function.py

全局变量有风险***************************************

0

因此需要改进****************************************

闭包函数****************************************

money = 100
money = 200

检测是否是闭包函数****************************************

非闭包函数:None
闭包函数:(<cell at 0x000002364C56CFD0: int object at 0x000002364BCD6290>,)

Process finished with exit code 0
</pre>

5.7 迭代器

  • 什么叫迭代器?

  • iter()函数

  • 迭代器取值的方案

  • 检测迭代器和可迭代对象的方法

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n117" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from collections.abc import Iterator
"""
迭代器前言简介:是Python中最具特色的功能之一,也是Python中访问集合元素的一种方式(字符串、列表、元组、字典、集合)
是一个可以记住访问遍历的位置的对象
从集合的第一个元素开始访问,直到集合中的所有元素被访问完毕
迭代器只能从前往后一个一个地遍历,不能后退
什么叫迭代器?
迭代器(iterator)是一个能被next()函数调用并不断返回下一个值的对象

对于数据量超大的数据(恒河沙),一次性显示就看不完,而且会非常长,所以就没必要一次性给超多数据

iter()函数

迭代器取值的方案:
1.next()函数 调用一次获取一次,直到数据被取完
2.list()函数 直接取出迭代器中的所有数据
3.使用for循环遍历迭代器的数据
迭代器取值的特点:
取出一个少一个,直到都取完,最后再获取就会报错

检测迭代器和可迭代对象的方法:
from collections.abc import Iterator,Iterable
type()函数返回当前数据的类型
isinstance()函数检测一个数据是不是一个指定的类型
"""
range(10, 1, -1) # 10--2(左闭右开) 返回一个可迭代的对象
for i in range(10, 1, -1):
print(i,end=' ')
print('\n',end='')

定义一个列表,列表是一个可迭代对象,可以使用for循环来遍历数据,可以把可迭代对象转换为迭代器使用

print("iter()函数*****************************************")
arr = ['赵四', '刘能', '小沈阳', '海参炒面']
"""
iter()函数:
功能:把可迭代的对象转为迭代器对象
参数:可迭代的对象(str,list,tuple,dict,set,range)
返回值:迭代器对象
注意:迭代器对象一定是一个可以迭代的对象,但是可迭代对象不一定是迭代器
"""
res = iter(arr)
print(res, type(res))
arr1 = "123456789"
res1 = iter(arr1)
print(res1, type(res1))
arr2 = {'name':'Jasmine','sex':'woman','year':'23'}
res2 = iter(arr2)
print(res2, type(res2))

使用next()函数去调用迭代器对象

print("迭代器取值的方案*****************************************")
print("使用next()函数去遍历迭代器对象*****************************************")
"""
next()函数:
功能:一个一个按顺序取迭代器中的值,直到取完为之,从已取完迭代器中取数据会报错
参数:迭代器对象
返回值:迭代器对象中的一个元素
"""
print(next(res))
print(next(res))
print("使用list()函数去遍历迭代器对象*****************************************")
"""
list()函数:
功能:一次性取完迭代器中未取的数据,从已取完迭代器中取数据会返回[]
参数:迭代器对象
返回值:迭代器对象中所有未取的元素
"""
print(list(res)) # 之前取过的就不再取了
print(list(res))

print(next(res)) 如果访问到末尾了就不能继续再访问了,会报错

print(list(res1))
print("使用for循环去遍历迭代器对象*****************************************")
for i in res2:
print(i,end=' ')
print('\n',end='')
print("检测迭代器和可迭代对象的方法*****************************************")
varstr = "Boly"
print(f"varstr是不是一个string?{isinstance(varstr, str)}")
res3 = iter(varstr)
print(f"res3是不是一个Iterator?{isinstance(res3, Iterator)}")
print(f"varstr是不是一个Iterator?{isinstance(varstr, Iterator)}")
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n120" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_21The_iterator.py
10 9 8 7 6 5 4 3 2
iter()函数*****************************************
<list_iterator object at 0x000002BE02B0FE80> <class 'list_iterator'>
<str_iterator object at 0x000002BE02B0FE50> <class 'str_iterator'>
<dict_keyiterator object at 0x000002BE0241FB30> <class 'dict_keyiterator'>
迭代器取值的方案*****************************************
使用next()函数去遍历迭代器对象*****************************************
赵四
刘能
使用list()函数去遍历迭代器对象*****************************************
['小沈阳', '海参炒面']
[]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
使用for循环去遍历迭代器对象*****************************************
name sex year
检测迭代器和可迭代对象的方法*****************************************
varstr是不是一个string?True
res3是不是一个Iterator?True
varstr是不是一个Iterator?False

Process finished with exit code 0
</pre>

5.8 The range() Function

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n124" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 内置函数--就是在系统安装完Python解释器时就可以使用的函数

官网:https://www.python.org/

"""
功能:range()函数能够生成一个指定的数字序列(前闭后开)
参数:
start:开始的值默认值为0
stop:结束的值
[, step]:步进值,默认值为1
返回值:可迭代的对象,数字序列,不是迭代器,不属于任何类型

如何遍历range()函数生成的数据:
1.转为list列表数据
2.for循环
3.转为迭代器,使用next()函数
"""
res = range(10)
print(res)
print(list(res))
anwster = iter(res)
print(next(anwster))
res1 = range(1,10)
print(list(res1))
res2 = range(1,10,2)
print(list(res2))
res3 = range(-10,-20,-3)
print(list(res3))
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n127" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_22range_function.py
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[-10, -13, -16, -19]

Process finished with exit code 0
</pre>

5.9 zip()函数

  • 可迭代对象的元素数目一样多时

  • 可迭代对象的元素数目不一样多时

  • *zip()

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n138" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># ***********************************************************************
"""
zip():---主要用于矩阵运算,用于数据分析
功能:zip函数是可以接收多个可迭代的对象,然后把每个可迭代对象中的第i个元素组合在一起,形成一个新的迭代器,新的迭代器包含的元组数目以元素数目最少的可迭代的对象为准
参数:iterables 任意个的 可迭代对象
返回值:返回一个元组的迭代器
zip():
直接
zip()得到的是组合而成的各元组---元组数目以元素数目最少的可迭代对象为准
zip():
还原出各可迭代的对象,但是每个可迭代的对象的元素数目以*zip()之前元素数目最少的可迭代对象为准,多余的被砍掉
"""
print("可迭代对象的元素数目一样多时****************************************")
var1 = [1,2,3,4]
var2 = ['Jasmine','Boooo~','Boly','Lily']
var3 = [6,7,8,9]
res = zip(var1,var2,var3)
print(res,type(res))
print(list(res))
print("可迭代对象的元素数目不一样多时****************************************")

以元素数目最少的可迭代对象为准

var4 = [1,2,3,4]
var5 = ['Jasmine','Boooo~','Boly']
var6 = [6,7]
res1 = zip(var4,var5,var6)
print(res1,type(res1))
print(list(res1))
print("zip()****************************************")
print("直接
zip()****************************************")

直接*zip()得到的是组合而成的各元组---元组数目以元素数目最少的可迭代对象为准

print(*zip(var4,var5,var6)) # 这一句输出的是元组类型

x,y = zip(var4,var5,var6) 这样会报错,因为不允许这样使用表达式

print("解*zip()****************************************")

zip()还原出各元组,但是每个元组的元素数目以zip()之前元素数目最少的可迭代对象为准,多余的被砍掉

var7,var8,var9 = zip(*zip(var4,var5,var6))
print(var7,type(var7),var8,type(var8),var9,type(var9))
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n141" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_23zip_function.py
可迭代对象的元素数目一样多时****************************************
<zip object at 0x000002312E37A600> <class 'zip'>
[(1, 'Jasmine', 6), (2, 'Boooo~', 7), (3, 'Boly', 8), (4, 'Lily', 9)]
可迭代对象的元素数目不一样多时****************************************
<zip object at 0x000002312E37A800> <class 'zip'>
[(1, 'Jasmine', 6), (2, 'Boooo~', 7)]
zip()****************************************
直接
zip()****************************************
(1, 'Jasmine', 6) (2, 'Boooo~', 7)
解*zip()****************************************
(1, 2) <class 'tuple'> ('Jasmine', 'Boooo~') <class 'tuple'> (6, 7) <class 'tuple'>

Process finished with exit code 0
</pre>

5.10 其他内置函数

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n154" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">"""
数据类型转换相关的函数:
int()
float()
bool()
cpmplex()
str()
list()
tuple()
dict()
set()
"""
"""
变量相关函数:
id()---获取当前数据的ID标识(其实就是存储地址)
type()---获取当前数据的数据类型
print()---数据的打印
input()---获取用户输入的数据
isinstance()---检测是否为指定的数据类型
"""
"""
数学相关函数:
abs()---返回一个数的绝对值。实参可以是整数或浮点数。如果参数是一个复数,返回它的模。
sum()---sum(iterable, /, start=0)---Sums start and the items of an iterable from left to right and returns the total.
---The iterable’s items are normally numbers, and the start value is not allowed to be a string.
---第二个参数start是计算前total的初始值(这我是没想到的噗哈哈哈)
max()---获取最大值---如果参数为多个元组,那么返回多个元组中第一个元素最大的元组,如果第一个元素最大的元组存在多个,则对比第二个元素,返回第一个元素最大且第二个元素最大的元组,以此类推
min()---获取最小值---如果参数为多个元组,那么返回多个元组中第一个元素最小的元组,如果第一个元素最小的元组存在多个,则对比第二个元素,返回第一个元素最小且第二个元素最小的元组,以此类推
pow()---求幂运算---有两种用法,提供两个参数x,y,返回x的y次幂;提供三个参数x,y,z,返回x的y次幂并对z求模
round()---round(number[, ndigits])---Return number rounded to ndigits precision after the decimal point.
---If ndigits is omitted or is None, it returns the nearest integer to its input.
---The return value has the same type as number.
---对于.5的数是奇进偶退
"""
print("数学相关函数********************************************")
print("abs()********************************************")
print(f"abs(-99.99) = {abs(-99.99)}")
print(f"abs(-99) = {abs(-99)}")
print(f"abs(1+2j) = {abs(3+4j)}")
print("sum()********************************************")
print(f"sum([1,2,3]) = {sum([1,2,3])}")
print(f"sum([1,2,3],2) = {sum([1,2,3],4)}")
print("max()********************************************")
print(f"max([1,2,3]) = {max([1,2,3])}")
print(f"max([3,1,2,4],[2,1,3,6],[3,2,4,5]) = {max([3,1,2,4],[2,1,3,6],[3,2,4,5])}")
print(f"max(1,2,3) = {max(1,2,3)}")
print("min()********************************************")
print(f"min([1,2,3]) = {min([1,2,3])}")
print(f"min(1,2,3) = {min(1,2,3)}")
print(f"min([3,1,2,4],[2,1,3,6],[2,2,4,5]) = {min([3,1,2,4],[2,1,3,6],[2,2,4,5])}")
print("pow()********************************************")
print(f"pow(2,3) = {pow(2,3)}")
print(f"pow(2,3,3) = {pow(2,3,3)}") # 计算2的3次方为8,8对3取余,结果为2
print("round()********************************************")
print(f"round(3.1415926) = {round(3.1415926)}") # 默认返回整数
print(f"round(3.1415926,2) = {round(3.1415926,2)}") # 返回值保留两位小数
print(f"round(1.5) = {round(1.5)}") # 奇进偶退
print(f"round(2.5) = {round(2.5)}")
"""
进制相关函数:
bin()---将数值转换为二进制
int()---将数值转换为整型(十进制)
oct()---将数值转换为八进制
hex()---将数值转换为十六进制
"""
print("进制相关函数********************************************")
print("bin()********************************************")
print(f"bin(123) = {bin(123)}")
print("int()********************************************")
print(f"int(0b1111) = {int(0b1111)}")
print(f"int(0o173) = {int(0o173)}")
print("oct()********************************************")
print(f"oct(0b1111) = {oct(0b1111)}")
print(f"oct(123) = {oct(123)}")
print("hex()********************************************")
print(f"hex(0b1111) = {hex(0b1111)}")
print(f"hex(123) = {hex(123)}")
"""
ascii字符集:
A-Z:65-90
a-z:97-122
0-9:48-57
Unicode---万国码---UTF-8编码方案最常用
ord()---将字符转换为ascii
chr()---将ascii转换为字符
"""
print("ascii********************************************")
print("ord()********************************************")
print(f"ord('a') = {ord('a')}")
print("chr()********************************************")
print(f"chr(97) = {chr(97)}")
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n157" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_24Other_Built_in_function.py
数学相关函数********************************************
abs()********************************************
abs(-99.99) = 99.99
abs(-99) = 99
abs(1+2j) = 5.0
sum()********************************************
sum([1,2,3]) = 6
sum([1,2,3],2) = 10
max()********************************************
max([1,2,3]) = 3
max([3,1,2,4],[2,1,3,6],[3,2,4,5]) = [3, 2, 4, 5]
max(1,2,3) = 3
min()********************************************
min([1,2,3]) = 1
min(1,2,3) = 1
min([3,1,2,4],[2,1,3,6],[2,2,4,5]) = [2, 1, 3, 6]
pow()********************************************
pow(2,3) = 8
pow(2,3,3) = 2
round()********************************************
round(3.1415926) = 3
round(3.1415926,2) = 3.14
round(1.5) = 2
round(2.5) = 2
进制相关函数********************************************
bin()********************************************
bin(123) = 0b1111011
int()********************************************
int(0b1111) = 15
int(0o173) = 123
oct()********************************************
oct(0b1111) = 0o17
oct(123) = 0o173
hex()********************************************
hex(0b1111) = 0xf
hex(123) = 0x7b
ascii********************************************
ord()********************************************
ord('a') = 97
chr()********************************************
chr(97) = a

Process finished with exit code 0
</pre>

5.11 sorted()函数

  • 从小到大排序

  • 从大到小排序

  • 先对每个数据取绝对值再排序

  • 使用自定义函数

  • 使用lambda表达式

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n172" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># ************************************************************

sorted()---用于排序

"""
运行原理:把可迭代数据里面的元素,一个一个地取出来,放到key函数中处理,并按照函数中return的结果进行排序,返回一个新的列表(还是原来那些数据)
sorted():
功能:排序
参数:iterable---可迭代数据(对象)(容器类型数据,range数据序列,迭代器)
reverse---可选,默认为False,不反转,True反转
key---可选值,是个函数,可以是自定义函数,也可以是内置函数
返回值:排序后的结果
"""

def func(num):
return num % 5

print("从小到大排序********************************************")
array = [1, 2, 6, 5, 4, 3, -10]
print(f"original data array:{array}")
print(f"sorted(array):{sorted(array)}")
print("从大到小排序********************************************")
print(f"original data array:{array}")
print(f"sorted(array,reverse=True):{sorted(array, reverse=True)}")
print("先对每个数据取绝对值再排序********************************************")
print(f"original data array:{array}")
print(f"sorted(array,key=abs):{sorted(array, key=abs)}")
print(f"original data array:{array}")
print(f"sorted(array,reverse=True,key=abs):{sorted(array, key=abs, reverse=True)}")
print("使用自定义函数********************************************")
print(f"original data array:{array}")
print(f"sorted(array,key=func):{sorted(array, key=func)}")
print(f"original data array:{array}")
print(f"sorted(array,key=func,reverse=True):{sorted(array, key=func, reverse=True)}")
print("使用lambda表达式********************************************")
print(f"original data array:{array}")
print(f"sorted(array,key=lambda x:x%4):{sorted(array, key=lambda x:x%5)}")
print(f"original data array:{array}")
print(f"sorted(array,key=lambda x:x%5,reverse=True):{sorted(array, key=lambda x:x%5, reverse=True)}")
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n175" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_25Sorted_Function.py
从小到大排序********************************************
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array):[-10, 1, 2, 3, 4, 5, 6]
从大到小排序********************************************
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,reverse=True):[6, 5, 4, 3, 2, 1, -10]
先对每个数据取绝对值再排序********************************************
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,key=abs):[1, 2, 3, 4, 5, 6, -10]
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,reverse=True,key=abs):[-10, 6, 5, 4, 3, 2, 1]
使用自定义函数********************************************
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,key=func):[5, -10, 1, 6, 2, 3, 4]
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,key=func,reverse=True):[4, 3, 2, 1, 6, 5, -10]
使用lambda表达式********************************************
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,key=lambda x:x%4):[5, -10, 1, 6, 2, 3, 4]
original data array:[1, 2, 6, 5, 4, 3, -10]
sorted(array,key=lambda x:x%5,reverse=True):[4, 3, 2, 1, 6, 5, -10]

Process finished with exit code 0
</pre>

5.12 map()函数

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n179" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># **********************************************
"""
map():map(func, *iterables)
功能:对传入的可迭代数据中的每个元素进行处理,返回一个新的迭代器
参数:
func:是一个函数,自定义or内置函数都可
iterables:可迭代的数据
返回值:迭代器
"""
print("map()***************************************")
varlist = ['1','2','3','4'] # 转换为[1,2,3,4]
newlist = map(int,varlist)
print(f"varlist = {varlist}")
print(f"newlist = {list(newlist)}")
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n182" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_26map_function.py
map()***************************************
varlist = ['1', '2', '3', '4']
newlist = [1, 2, 3, 4]

Process finished with exit code 0
</pre>

5.13 reduce()函数

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n186" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from functools import reduce

*****************************************************

"""
reduce():
功能:每一次从iterable中拿出两个元素,放入到func函数中进行处理,得出一个计算结果
然后把这个计算结果和iterable中的第三个元素,放入到func函数中继续运算,得出
的结果和之后的第四个元素,放入到func函数中进行处理,以此类推,直到所有元素都
参与了运算
参数:
func:内置函数或自定义函数
iterable:可迭代的数据
返回值:最终的运算处理结果
注意:使用reduce()函数时需要导入from functools import reduce
"""

def func(x, y):
return x*10+y

def transform(x):
verdict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
return verdict[x]

举例1********************************************

print("举例1********************************************")
varlist = [5, 2, 1, 1] # 要求输出5211
print(f"original varlist = {varlist}")
print(f"reduce(func,varlist) = {reduce(func,varlist)}")
print("举例2********************************************")
varlist1 = "456" # 要求输出int类型的456,但是不可以使用int()函数
res = map(transform,varlist1)
res_reduce = reduce(lambda x,y:x*10+y,res)
print(res_reduce,type(res_reduce))
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n189" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_27reduce_function.py
举例1********************************************
original varlist = [5, 2, 1, 1]
reduce(func,varlist) = 5211
举例2********************************************
456 <class 'int'>

Process finished with exit code 0
</pre>

5.14 filter()函数

code:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n193" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># **********************************************

filter()过滤器

"""
filter:filter(function or None, iterable)
功能:过滤数据,把iterable中的每一个元素拿到func函数中进行处理,如果函数返回True则保留数据,返回False则丢弃数据
参数:
func:自定义函数 or 内置函数
iterable:可迭代数据
返回值:保留下来的数据组成的迭代器
"""

def func(x):
if x % 2 == 0:
return True
else:
return False

举例:要求保留所有的偶数,丢弃所有的奇数

print("举例****************************************")
varlist = [1,2,3,4,5,6,7,8,9]
print(f"list(filter(func,varlist)) = {list(filter(func,varlist))}")
print(f"list(filter(lambda x:True if x%2==0 else False,varlist)) = {list(filter(lambda x:True if x%2==0 else False,varlist))}")
</pre>

运行结果:

<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="" cid="n196" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(54, 59, 64); font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; position: relative !important; padding: 10px 30px; border: 1px solid; width: inherit; color: rgb(184, 191, 198); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_28filter_function.py
举例1****************************************
list(filter(func,varlist)) = [2, 4, 6, 8]
list(filter(lambda x:True if x%2==0 else False,varlist)) = [2, 4, 6, 8]

Process finished with exit code 0
</pre>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容

  • Python之函数 什么是函数函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段。 为什么要用函数函数...
    免跪姓黄阅读 212评论 0 4
  • 模块化编程 定义:把程序进行封装 函数封装 面向对象 面向文件 函数:封装完不会执行,调用来使用。 函数是什么:一...
    你怎么还在吃阅读 354评论 0 3
  • 函数进阶 楔子 假如有一个函数,实现返回两个数中的较大值: def my_max(x,y): m = x if...
    go以恒阅读 278评论 0 0
  • 一 引入 ​ 随着程序功能的增多,代码量随之增大,如果不加区分地把所有功能的实现代码放到一起,将会使得程序的组织结...
    100斤的瘦子_汤勇阅读 363评论 1 1
  • 1.函数的定义: #定义函数的目的,增加代码的重用性 def multiple_table(): # 定义遍历r...
    冰云数据阅读 413评论 0 0