上接:
Python 入门学习 详细知识点+典型例题/自学笔记(二)_字母符号数字的博客-CSDN博客
目录
try- except- else 未检测出异常,执行else
trry-except-finally 无论异常是否发生都会执行内容
一.函数
python函数作用: 打包代码(1.减少冗余 2.将不同功能的代码封装,分解)
1.创建和调用函数
def myfunc():
pass 函数体
def myfunc():
for i in range(3):
print("I Love python")
调用myfunc()打印三次I Love python
myfunc()
I Love python
I Love python
I Love python
2.函数的参数
参数 可以替换,可以有多个,并且可以指定打印次数
def myfunc(name,times): for i in range(times): print(f"I Love {name}") myfunc("python",5) 打印5次 I Love python I Love python I Love python I Love python I Love python
形参和实参
函数的返回值 return ()
def div(x,y):
if y==0:
return "除数不能为0!!!"
else:
return x/y
调用div()函数
div(4,2)
2.0
div(4,0)
'除数不能为0!!!'
若语句没有通过return()显示的来返回内容,则自己返回一个none值
2.1位置参数
def myfunc(s,vt,o):
return "".join ((o,vt,s)) 颠倒顺序并连接
myfunc("我","喜欢","你")
'你喜欢我'
myfunc("你","喜欢","我")
'我喜欢你'
/ 左侧只能使用位置参数 * 右侧只能是关键字参数
2.2关键字参数
myfunc(o="我",vt="喜欢",s="你")
'我喜欢你'
混合使用时,位置参数必须在关键字参数之前
2.3默认参数
def myfunc(s,vt,o="猪"):
return "".join ((o,vt,s))
myfunc("人","吃") 只传两个参数
'猪吃人'
myfunc("人","吃","饭") 传三个会自动覆盖默认参数
'饭吃人'
默认参数应该放在后面
2.4收集参数 在形参前加 * 号
打包为字典(加**)
def myfunc(**kwargs):
print(kwargs)
myfunc(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
混合使用
def myfunc(a,*b,**c):
print(a,b,c)
myfunc(1,2,3,4,x=5,y=6) 1给的a,2,3,4打包为元组给b,x=5,y=6打包为字典形式给c
1 (2, 3, 4) {'x': 5, 'y': 6}
2.5解包参数(在实参上使用)
一个*号
rgs=(1,2,3,4) def myfunc(a,b,c,d): print(a,b,c,d) myfunc(*args) 1 2 3 4
两个*号(对应的关键字参数)
kwargs={'a':1,'b':2,'c':3,'d':4} myfunc(**kwargs) 1 2 3 4
3.作用域
局部作用域
全局作用域
global语句 故意声明是一个全局变量,并且修改值
4.嵌套函数
def funA():
x=520
def funB():
x=880
print("In funB,x=",x)
funB()
print("In funA,x=",x)
funA()
In funB,x= 880
In funA,x= 520
nonlocal语句 用于内部修改外部函数
def funA():
x=520
def funB():
nonlocal x
x=880
print("In funB,x=",x)
funB()
print("In funA,x=",x)
funA()
In funB,x= 880
In funA,x= 880
LEGB规则 局部和全局发生冲突时,选择哪个
str="我把python学会了"
str
'我把python学会了'
str(520)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
str(520)
TypeError: 'str' object is not callable
5.闭包
def power(exp):
def exp_of(base):
return base **exp
return exp_of
square=power(2)
cube=power(3)
square(2)
4
square(5)
25
cube(2)
8
cube(5)
125
6.装饰器
import time
def time_master(func):
def call_func():
print("开始运行程序......")
start=time.time()
func()
stop=time.time ()
print("结束程序运行.......")
print(f"一共耗费了{(stop-start):.2f}秒。")
return call_func
@time_master 添加装饰器
def myfunc():
time.sleep (2)
print("hallo baby")
myfunc()
开始运行程序......
hallo baby
结束程序运行.......
一共耗费了2.02秒。
可以同时使用多个装饰器
7.lambda表达式
语法:
lambda arg1,arg2,arg3,.....argN : expression
def squareX(x):
return x*x
squareX(3)
9
等价于:
squareY=lambda y:y*y
squareY(3)
9
y=[lambda x:x*x,2,3]
y[0](y[1]) 第二个参数
4
y[0](y[2]) 第三个参数
9
求出10以内的奇数
list(filter(lambda x:x%2,range(10))) [1, 3, 5, 7, 9]
8.生成器(不走回头路,支持使用next,不支持下标索引)
在函数中使用yield表达式代替return语句
def counter():
i=0
while i<=5:
yield i
i+=1
counter()
<generator object counter at 0x0000020B7FD66570>
for i in counter():
print(i)
0
1
2
3
4
5
斐波那契数列 新的数据等于前两个数据的和
def fib(): back1,back2=0,1 while True: yield back1 back1,back2=back2,back1+back2 f=fib() next(f) 0 next(f) 1 next(f) 1 next(f) 2 next(f) 3
直接使用生成器表达式
t=(i**2 for i in range(10)) 打印0到10每个数的平方
next(t)
0
next(t)
1
next(t)
4
next(t)
9
9.递归(函数调用自身的过程)
def func(i):
if i>0:
print("AWBDYL")
i-=1
func(i)
func(10)
AWBDYL
AWBDYL
AWBDYL
AWBDYL
AWBDYL
AWBDYL
AWBDYL
AWBDYL
AWBDYL
AWBDYL
求一个数的阶乘
迭代方法: def factIter(n): result=n for i in range(1,n): result *=i return result factIter(5) 120
递归方法: def factrecur(n): if n==1: return 1 else : return n * factrecur(n-1) factrecur(5) 120
9.1斐波那契数列:
递归:生兔子
def fibRecur(n):
if n==1 or n==2:
return 1
else:
return fibRecur(n-1)+fibRecur(n-2)
fibRecur(12)
144
迭代:生兔子
def fibIter(n):
a=1
b=1
c=1
while n>2:
c=a+b
a=b
b=c
n-=1
return c
fibIter(12)
144
9.2 汉诺塔
def hanoi (n,x,y,z):
if n==1:
print(x, '--->', z) #如果只有1层,直接将金片从x移动到z
else:
hanoi(n-1, x, z, y) #将x上的n-1个金片移动到y
print(x, '--->', z) #将最底下的金片从x移动z
hanoi(n-1, y, x, z) #将y上的n-1个金片移动到z
n=int(input('请输入汉诺塔的层数:'))
hanoi(n,'A','B','C')
请输入汉诺塔的层数:5
A ---> C
A ---> B
C ---> B
A ---> C
B ---> A
B ---> C
A ---> C
A ---> B
C ---> B
C ---> A
B ---> A
C ---> B
A ---> C
A ---> B
C ---> B
A ---> C
B ---> A
B ---> C
A ---> C
B ---> A
C ---> B
C ---> A
B ---> A
B ---> C
A ---> C
A ---> B
C ---> B
A ---> C
B ---> A
B ---> C
A ---> C
10.函数文档, 类型注释,内省
函数文档(汇率转换)
def exchange(dollar,rate=6.32): """ 功能:汇率转换 ,美元————》人民币 参数: -dollar 美元数量 -rate 汇率,默认值为 6.32 返回值: -人民币数量 """ return dollar *rate exchange(10) 63.2
类型注释
def times(s:str , n:int )->str: s类型为字符串型,n类型为整型 return s*n times("python",5) 'pythonpythonpythonpythonpython'
内省(自我检测机制)
times.__name__ 查看名字 'times' times.__annotations__ 查看类型注释 {'s': <class 'str'>, 'n': <class 'int'>, 'return': <class 'str'>}
doc 查看函数文档
11.高阶函数
reduce函数
def add(x,y):
return x+y
import functools
functools.reduce (add,[1,2,3,4,5])
15
等价于:
add(add(add(add(1,2),3),4),5)
15
偏函数(对指定的函数进行二次包装)
square=functools.partial(pow,exp=2)
square(2)
4
square(3)
9
@wraps装饰器
二.永久存储
1.操作文件
f=open ("python.txt","w") 打开文件,可写 f.write ("I love python.") 14 f.writelines(["I love python.\n","I love my file"]) f.close()
f=open("python.txt","r+") 打开文件 f.readable () 检测是否可读 True f.writable() 检测是否可写 True
f.tell() 指针位置 44 f.seek(0) 移动指针到头 0 f.readline () 读取一行 'I love python.I love python.\n' f.read () 读到末尾 'I love my file' f.write ("我再写点东西") 6 f.flush () 缓存数据写入文件中 f.truncate (29) 截断操作 29 f.close() f=open ("python.txt","w") 打开再关闭直接清空 f.close()
2.路径处理
查询:
cwd( ) 路径导入
/ 拼接
is_dir( ) 判断路径是否为文件夹
is_file() 判断是否为文件
exists() 检测路径是否存在
name 获取路径最后一个部分
stem 获取文件名
suffix 获取文件后缀
parent 获取父级目录
parents 获取逻辑祖先路径构成的序列
parts 将路径各个组件拆分成元组
stat() 查询文件或文件夹
resolve() 将相对路径转换为绝对路径
iterdir() 获取当前路径下子文件和子文件夹
from pathlib import Path Path.cwd () WindowsPath('C:/Users/z/AppData/Local/Programs/Python/Python310') p=Path('') p=Path('C:/Users/z/AppData/Local/Programs/Python/Python310') p WindowsPath('C:/Users/z/AppData/Local/Programs/Python/Python310') q=p/"python.txt" q WindowsPath('C:/Users/z/AppData/Local/Programs/Python/Python310/python.txt') p.is_dir() True q.is_dir () False p.is_file () False q.is_file () True p.exists() True q.exists() True p.name 'Python310' q.name 'python.txt' q.stem 'python' q.suffix '.txt' p.parent WindowsPath('C:/Users/z/AppData/Local/Programs/Python') q.parent WindowsPath('C:/Users/z/AppData/Local/Programs/Python/Python310') p.parents <WindowsPath.parents> ps=p.parents for each in ps: print(each) C:\Users\z\AppData\Local\Programs\Python C:\Users\z\AppData\Local\Programs C:\Users\z\AppData\Local C:\Users\z\AppData C:\Users\z C:\Users C:\ ps[0] WindowsPath('C:/Users/z/AppData/Local/Programs/Python') ps[1] WindowsPath('C:/Users/z/AppData/Local/Programs') ps[2] WindowsPath('C:/Users/z/AppData/Local') p.parts ('C:\\', 'Users', 'z', 'AppData', 'Local', 'Programs', 'Python', 'Python310') p.stat() os.stat_result(st_mode=16895, st_ino=14636698789026712, st_dev=3025546364, st_nlink=1, st_uid=0, st_gid=0, st_size=4096, st_atime=1659369987, st_mtime=1659367376, st_ctime=1657550508) p.stat().st_size 4096 Path("./doc").resolve() WindowsPath('C:/Users/z/AppData/Local/Programs/Python/Python310/Doc') p.iterdir() <generator object Path.iterdir at 0x000002A301E80CF0>
修改:
mkdir( ) 创建文件夹
n=p/"python" n.mkdir()
open () 打开文件
rename( ) 修改文件或文件夹名字
n.rename("newpython.txt") WindowsPath('newpython.txt')
replace( ) 替换指定的文件或文件夹
删除:
rmdir( ) 删除文件夹
unlink( ) 删除文件
查找:
glob( ) 查找功能
p=Path('.') p.glob ("*.txt") <generator object Path.glob at 0x000002A37FCD6570> list(p.glob ("*.txt")) [WindowsPath('LICENSE.txt'), WindowsPath('newpython.txt'), WindowsPath('NEWS.txt'), WindowsPath('python.txt')]
文件管理器 with
with open("python.txt","w")as f:
f.write("文件管理器")
5
等价于
f=open("python.txt","w")
f.write("文件管理器")
5
pickle 永久存储对象
3.异常
try -except 捕获并处理异常
try:
1/0
except:
print("出错了")
出错了
try :
1/0
520+"python"
except(ZeroDivisionError,ValueError,TypeError): 直接忽略
pass
try:
1/0
520+"python"
except ZeroDivisionError:
print("除数不能为0!!")
except ValueError:
print("值不正确")
except TypeError:
print("类型不正确")
除数不能为0!!
try- except- else 未检测出异常,执行else
try:
1/0
except:
print("逮到异常")
else:
print("没有逮到异常,哦豁")
逮到异常
try:
1/1
except:
print("逮到异常")
else:
print("没有逮到异常,哦豁")
1.0
没有逮到异常,哦豁
trry-except-finally 无论异常是否发生都会执行内容
try:
1/0
except:
print("逮到异常")
else:
print("没有逮到异常,哦豁")
finally:
print("逮没逮到都会吱一声")
逮到异常
逮没逮到都会吱一声
异常嵌套
try:
1/0
try:
520+"python"
except:
print("内部异常!!!")
except:
print("外部异常!!!")
finally:
print("收尾工作~")
外部异常!!!
收尾工作~
raise 语句
raise ValueError("值不正确")
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
raise ValueError("值不正确")
ValueError: 值不正确
assert 语句 类似于if语句
s="python"
assert s=="python"
assert s!="python"
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
assert s!="python"
AssertionError
利用异常来实现goto
try:
while True:
while True:
for i in range(10):
if i >3:
raise
print(i)
print("被跳过~")
print("被跳过~")
print("被跳过~")
except:
print("到这来了~")
0
1
2
3
到这来了~