第六章 函数进阶
6.1 函数多返回值
def test_return():
return 1,2,3
x,y,z=test_return()
print(x,y,z)
6.2 函数的多种参数使用形式
1、位置参数
根据函数定义的参数位置来传递参数(和之前类似)
2、关键字参数
通过使用“键=值”的形式来传递参数
def user_info(name,age,gender):
print(name,age,gender)
user_info(age=10,name="彦祖",gender="男")
3、缺省参数
def user_info(name,age,gender='男'):
print(name,age,gender)
user_info(age=10,name="彦祖")
如果不传参数则gender为默认:“男”,默认参数可以被覆盖,并且必须在最后
4、不定长参数
位置传递:
def user_info(*args):
print(args)
user_info(10,"彦祖")
user_info(10)
可以看出上面所述的args是个元组,可以接受无数个参数
关键字传递:
def user_info(**kwargs):
print(kwargs)
user_info(age=10,name="彦祖")
user_info(age=10)
kwargs是一个字典,该方法需要通过“键=值”的形式传递参数
6.3 函数作为参数传递
def func(compute):
result=compute(1,2)
print(result)
def compute(x,y):
return x+y
func(compute)
6.4 lambda匿名函数
def func(compute):
result=compute(1,2)
print(result)
func(lambda x,y:x+y)
lambda函数里面只能有一行代码
第七章 Python文件操作
7.1 文件的编码
计算机有许多编码,例如:UTF-8 GBK BIG5
7.2 文件的读取
1、打开文件
三个参数,分别是文件名(路径),打开方式(只读r,只写w,追加a),编码方式
f = open("D:/Desktop/test.txt","r",encoding="UTF-8")
2、读写文件
print(f.read()) #读取指定长度字节
print(f.readlines()) #读取全部行,得到列表
print(f.readline()) #读取一行
3、关闭文件
f.close()
扩展:
用for循环循环读取文件
for line in f:
print(line)
使用with open 就不用担心忘记关闭文件:
with open("D:/Desktop/test.txt","r",encoding="UTF-8")as f:
for line in f:
print(line)
#wordcount
count=0
with open("D:/Desktop/test.txt","r",encoding="UTF-8")as f:
for i in f:
i=i.strip()
for j in i.split(" "):
print(j)
if(j=="itheima"):
count+=1
print(count)
7.3 文件的写入
1、写入要使用open函数的“w”模式
2、写入方法:write(),写入内容 flush(),刷新内容到硬盘中
3、注意:w模式:文件不存在,会创新新文件 存在则覆盖
close()方法,带有flush()方法的功能
7.4 文件的追加
1、写入要使用open函数的“a”模式
其他和文件写入差不多
可以使用'\n'来换行
第八章 异常、模块与包
8.1 异常的捕获
try:
... #可能出现问题的语句
except:
... #怎么处理
捕获指定、多个异常
try:
print(name)
1/0
except (NameError,ZeroDivisionError):
print("出现了变量未定义和除零的异常")
捕获全部异常:
try:
... #可能出现问题的语句
except Exception as e:
... #怎么处理
else语句:表明要是没有异常则执行else语句内容
try:
print(1)
except Exception as e:
print(e)
else:
print("没有异常芜湖")
finally语句:无论是否有异常都执行finally的语句
8.2 模块
8.2.1 基础语法:
#1、
import time
time.sleep(5)
#2、
from time import sleep
sleep(1)
#3、
from time import * #导入time模块中的全部功能
sleep(1)
8.2.2 自定义模块
使用 if __name__ == '__main__': 可以方便在模块内部测试,而模块调用的时候不会显示
8.3 Python包
有很多模块的文件夹,方便管理