def manyReturn():
return 1, "hello", True
x,y,z = manyReturn()
print(f"{x}\t{y}\t{z}")
位置参数
def userInfo(name,age,gender):
print(f"姓名是:{name},年龄是:{age},性别是:{gender}")
# 位置参数 -默认使用方式
userInfo("马浩楠",22,"男")
传递的参数和定义的参数的顺序及个数必须一致
关键字参数
# 关键字参数
userInfo(name="马浩楠",age=22,gender="男")
userInfo(age=22,name="马浩楠",gender="男")
userInfo("马浩楠",age=22,gender="男")
函数调用时,如果有位置参数时,位置参数必须在关键字参数的前面,但关键字参数之间不存在先后顺序
缺省参数
# 缺省参数
def userInfo(name,age,gender = "男"):
print(f"姓名是:{name},年龄是:{age},性别是:{gender}")
userInfo("马浩楠",22)
不定长参数
# 不定长 -位置不定长 *号
def userInfo(*args):
print(args)
userInfo(1,"Hello",True)
传递的所有参数都会被args变量收集,根据传进参数的位置合并为一个元组类型
# 不定长 -关键字不定长 **号
def userInfo(**kwargs):
print(kwargs)
userInfo(name="马浩楠",age=22,gender="男")
参数是”键 = 值“形式的情况下,所有的键值对都会被kwargs接收,组成字典类型容器
# 定义函数,接收另一个函数作为形参
def test(calculate):
result = calculate(1,3)
print(f"参数的函数类型是:{type(calculate)}")
print(f"计算结果:{result}")
# 定义函数,作为参数传入另一个函数
def calculate(x,y):
return x+y
# 调用,并传入函数
test(calculate)
函数calculate,作为参数,传入test函数中使用
有名称的函数,可以基于名称重复使用,无名称的匿名函数,只能临时使用一次
语法
lambda 传入参数: 函数体(一行代码)
示例
# 定义一个函数,接收其它函数输入
def test(calculate):
result = calculate(4,5)
print(f"结果是:{result}")
# 通过lambda匿名函数的形式,将匿名函数作为参数传入
test(lambda x, y: x * y)
open() 打开函数
open(name,mode,encoding)
示例
# 打开文件
f = open("./data.txt","r",encoding="utf-8")
此时的 f 是 open函数的文件对象
read()方法:文件对象.read(num)
num表示要从文件中读取的数据长度(字节),如果没有传入um,则表示读取文件中所有数据
# 打开文件
f = open("./data.txt","r",encoding="utf-8")
# 读取文件 - read()
print(f.read(2))
print(f.read())
readlines()方法
按照行的方式吧整个文件的内容进行一次性读取,并返回列表,每一行的数据为一个元素
# 多次使用read方法,会影响内容,已经读取过的内容不会继续读取
# 读取文件 - readLines()
lines = f.readlines()
print(lines)
readline()方法:一次读取一行内容
# 读取文件 - readLine()
line1 = f.readline()
line2 = f.readline()
line3 = f.readline()
print(f"读取第一行数据:{line1}")
print(f"读取第二行数据:{line2}")
print(f"读取第三行数据:{line3}")
for 循环读取文件行
# for循环读取文件行
for i in f:
print(f"每一行的数据是:{i}")
close() 与Java一致
with open 语法
通过在with open的语句块中对文件继续操作,在操作完成后自动close文件,避免遗忘掉close方法
with open("./data.txt","r",encoding="utf-8") as f:
for i in f:
print(f"每一行:{f}")
操作总览
with open("./wordsCount","r",encoding="utf-8") as f:
count = 0
for i in f:
count += i.count("itheima")
print(f"itheima出现的次数是:{count}")
# 方式二:
print(f.read().count("itheima"))
# 打开文件(不存在的)
f = open("./write.txt","w",encoding="UTF-8")
# write 写入
f.write("Hello World")
# flush 刷新
#f.flush() # 将内存中积攒的内容,写入到硬盘的文件当中
# close 关闭
f.close() # 内置 flush()
# 打开一个存在的文件
f = open("./data.txt","w",encoding="utf-8")
# write写入、flush刷新
f.write("婚姻:否")
# close 关闭
f.close()
将模式改为 a 即可
w = open("./bill.txt","w",encoding="UTF-8")
with open("./comsumerData.txt","r",encoding="UTF-8") as f:
for i in f:
if i.count("测试") != 1:
w.write(i)
w.close()
f.close()
7-