python笔记三 函数
函数11/1函数:是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名就可以了。
def sayhi(): 函数名
print("hello , i'mhequan")
sayhi()#调用
函数的返回值
def calc(x,y):
res = x**y
returnres#返回函数执行结果
默认返回 None
11/2
参数
defmail(形式参数):
ret = mail(实际参数)
ifret:
print("发送成功")
def mail(a1,a2=11):默认参数必须放在最后
def mail(a1,a2):
mail(a2=123,a1=321) 指定参数
动态参数
def show(*arg): #*把参数转换成元祖
print(agr,type(arg))
show(11,22,33,44)
def show(**arg):##** 把参数转换成字典
print(arg, type(arg))
show(n1=11, n2=22, n3=33, n4=44)
def show(*kwargs,**arg):
print(arg, type(arg))
print(*kwargs,type(kwargs))
show(11,22,33,44,n1=11, n2=22, n3=33, n4=44)
{'n3': 33, 'n4': 44, 'n1': 11, 'n2': 22} <class 'dict'>
11 22 33 44 <class 'tuple'>
show(*a,**b)
11/3
s1 = "{0} is {1}" {name}{acter}
xx = s1.format('hequan','2b')
print(xx)
hequan is 2b
#lambda表达式 简单函数
he = lambda a: a+1
print(he(1))
内置函数
open函数文件处理
r只读 w 只写a追加
r+可读写w+写读a+ 同a
u自动转换成\n
b表示处理二进制文件
close关闭文件
tell()#查看当前指针位置
seek()# 设置指针位置
read
truncate() 指针位置之前的字节,只保留前面的,并保存到文件里。
write
形式参数
实际参数
默认参数
关键参数 在位置参数后面
非固定参数*args **kwargs 元祖列表
局部变量
全局变量
返回值 --return
函数在执行过程中只要遇到return语句,就会停止执行并返回结果,return标志着函数的结束。
如果没有return,返回值就是None.
嵌套函数
递归
匿名函数
map可以用于对可遍历结构的每个元素执行同样的操作
map(lambda x: x**2, ) #
map(lambda x, y: x + y, , ) #
reduce则是对可遍历结构的元素 按顺序进行两个输入参数的操作,并且每次的结果保存作为下次
操作的第一个输入参数,还没有遍历的元素作为第二个输入参数。
这样的结果就是把一串可遍历的值,减少成一个对象:
reduce(lambda x, y: x + y, ) # ((1+2)+3)+4=10
filter 根据条件对可遍历结构进行筛选
filter(lambda x: x % 2, ) # 筛选奇数,
列表生成
]
zip函数可以把多个列表关联起来。
, )] #
iter_odd = (x for x in if x % 2)
print(type(iter_odd)) # <type 'generator'>
square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
文件操作
open()的第一个参数是文件名,第二个参数是模式。文件的模式一般有四种,读取(r),写入(w),追加(a)和读写(r+)。如果希望按照二进制数据读取,则将文件模式和b一起使用(wb, r+b…)。
with open('xx.txt','r') as f:
lines = f.readlines()
for line in lines:
name, age = line.rstrip().split(',')
print('{}is {}yearsold'.format(name,age))
import pickle
lines = [
"I'm like a dog chasing cars.",
"I wouldn't know what to do if I caught one...",
"I'd just do things."
]
with open('lines.pkl','wb') as f:
pickle.dump(lines,f)
with open('lines.pkl','rb') as f:
lines_back = pickle.load(f)
print(lines_back)
页:
[1]