函数的返回值和参数
# 函数的多返回值
def test_return():
return 1, 2
x, y = test_return()
print(x)
print(y)
# 函数的多种传参方式
# 之前写的函数都是位置参数:传递参数和定义参数的顺序及个数必须一致
# 关键字参数: 根据 键=值 的方式进行传递,更加清晰
def user_info(name,age,gender):
print(f"Name: {name}, Age: {age}, Gender: {gender}")
user_info(name = "John", age = 20, gender = "Man")
# 这种形式可以不固定顺序,可以和位置参数混用,但是位置参数必须在前,且与原参数位置匹配
# 缺省参数:也叫做默认参数,为参数提供默认的值,且默认的参数必须写在最后
def user_info2(name,age,gender="Man"):
print(f"Name: {name}, Age: {age}, Gender: {gender}")
user_info2("John", 20)
# 默认值可不写
user_info2("John", 20, gender="Woman")
# 默认值可修改
# 不定长参数: 传递参数个数未知
# 位置传递的不定长: 传进的所有参数都被args收集,根据传递的位置创建一个元组
def user_info3(*args):
print(f"{args[0]}, {args[1]},{type(args)}")
user_info3(1,2,3,"haha")
# 关键字传递的不定长: 参数是 键=值 的形式,所有键值对都被kwargs接受,形成一个字典
def user_info4(**kwargs):
print(f"kwargs: {kwargs},{type(kwargs)}")
user_info4(name="John", age=20)
# 函数作为参数传递
def compute(x,y):
return x+y
def test_function(compute):
res = compute(1,2)
print(f"{type(compute)},{res}")
test_function(compute)
# Lambda匿名函数
# 之前写的函数都是def,定义带有名称的函数,可以重复使用,匿名函数只能使用一次
# 格式: lambda 参数: 函数体
# 注意匿名函数只能写一行代码作为函数体
test_function(lambda x, y: x+y)
文件操作
# 文件的操作
# 打开文件: r(只读), w(只写), a(追加)
f = open("D:/Study/Code/python/test.txt", "r", encoding="UTF-8")
print(type(f))
# 文件读取
# read()将内容封装成字符串
print(f"读取10个字节:{f.read(10)}")
# 注意第二次调用read函数,会从上一次读取完的地方继续读
print(f"读取全部:{f.read()}")
# readlines()读取文件的全部行,并封装到列表对象
lines = f.readlines()
print(f"{type(lines)},{lines}")
# readline()读取文件的一行内容
line1 = f.readline()
print(f"the first line is {line1}")
# 循环读取
for line in f:
print(line)
# 关闭文件
f.close()
# 执行自动关闭文件操作
with open("D:/Study/Code/python/test.txt", "r", encoding="UTF-8") as f:
for line in f:
print(line)
# 统计文件中“计算机”出现的次数
f1 = open("D:/Study/Code/python/test.txt", "r", encoding="UTF-8")
content = f1.read()
count = content.count("计算机")
print(f"出现了{count}次")
f1.close()
# 文件的写入:w模式会将内容全部清空
f2 = open("D:/Study/Code/python/test.txt", "w", encoding="UTF-8")
# write()写入:将内容写入到内存中
f2.write("11408真简单")
# flush刷新:将内存中积攒的内容写入到硬盘的文件中
f2.flush()
f2.close()
# 追加写入:将模式替换为a即可
# 综合案例:完成文件备份
fr = open("D:/Study/Code/python/test2.txt", "r", encoding="UTF-8")
fw = open("D:/Study/Code/python/11408.txt", "w", encoding="UTF-8")
for line in fr:
line = line.strip() # 处理掉空格和回车
fw.write(line)
fw.write("\n") # 手动写入换行符
fr.close()
fw.close() # 注意:写出文件调用close会自动flush,所有无需手动flush