函数
一、函数定义:
函数的定义和使用:
def 函数名(参数): ... 函数体 ...
函数的定义主要有如下要点:
- def:表示函数的关键字
- 函数名:函数的名称,日后根据函数名调用函数
- 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
- 参数:为函数体提供数据
- 返回值:当函数执行完毕后,可以给调用者返回数据。
一、函数参数:
函数的有三中不同的参数:
- 普通参数
# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参 def func(name): print name # ######### 执行函数 ######### # 'lucy' 叫做函数func的实际参数,简称:实参 func('lucy')
- 默认参数
def func(name, age = 18):#age=18默认参数 print "%s:%s" %(name,age) # 指定参数 func('lucy', 19) # 使用默认参数 func('alex') 注:默认参数需要放在参数列表最后
- 动态参数
def func(*args): print args # 执行方式一 func(11,33,4,4454,5) # 执行方式二 li = [11,2,2,3,3,4,54] func(*li)
def func(**kwargs): print args # 执行方式一 func(name='wupeiqi',age=18) # 执行方式二 li = {'name':'wupeiqi', age:18, 'gender':'male'} func(**li)
def func(*args, **kwargs): print args print kwargs
import smtplib from email.mime.text import MIMEText from email.utils import formataddr def mail(receiver):#receiver形参,普通参数 ret=True try: #构造MIMEText对象时,第一个参数就是邮件正文,subtype传入'plain',utf-8编码保证多语言兼容性 msg=MIMEText("恭喜,您已注册成功",'plain','utf-8') msg['From']=formataddr(["lucy",'XXXXX@163.com']) msg['To']=formataddr(["echo",receiver]) msg['Subject']='注册通知' #SMTP类构造函数,表示与SMTP服务器之间的连接,port表示smtp服务的端口,默认是25 server=smtplib.SMTP('smtp.163.com',25) #smtplib.SMTP提供的方法:登陆到smtp服务器,SMTP.login(user, password) server.login("XXXXXX@163.com",'XXXXXXXpwd') #发送邮件,msg是字符串,表示邮件,SMTP.sendmail(from_addr, to_addrs, msg) server.sendmail('XXXXXXXX@163.com',[receiver],msg.as_string()) server.quit()#断开与smtp服务器的连接 except Exception: ret=False return ret ret=mail('YYYYYY@qq.com')#'YYYYYY@qq.com'实参 if ret: print('发送成功') else: print('发送失败')
def main(*s):#tuple print(s,type(s)) ret=main(6,7,8,9) def main(**s):#dict print(s,type(s)) ret=main(k1=6,k2=7,k3=8,k4=9) def main(*s1,**s2):#*必须在**前面,否则报错 print(s1,type(s1)) print(s2,type(s2)) ret=main(6,7,8,9,k1=6,k2=7,k3=8,k4=9)#同理要求,否则报错 def main(*s1,**s2): print(s1,type(s1)) print(s2,type(s2)) a=[6,7,8,9] b={'k1':6,'k2':7,'k3':8,'k4':9} ret=main(a,b)#都给了*s1,tuple def main(*s1,**s2): print(s1,type(s1)) print(s2,type(s2)) a=[6,7,8,9] b={'k1':6,'k2':7,'k3':8,'k4':9} ret=main(*a,**b)#分别给s1、s2
1. 位置参数 *args, 把参数收集到一个元组中,作为变量args
def show_args(*args): => how_args("hello", "world")
2. 关键字参数 **kwargs, 是一个正常的python字典类型,包含参数名和值
def show_kwargs(**args): = > show_kwargs(foo="bar", spam="eggs")
d='{0} is {1}' ret=d.format('lucy','nice') print(ret) d='{0} is {1}' e=['lucy','nice'] ret=d.format(*e) print(ret) d='{name} is {how}' ret=d.format(name='lucy',how='nice') print(ret) d='{name} is {how}'#key value形式 e={'name':'lucy','how':'nice'}# ret=d.format(**e) print(ret)
test=lambda x:x+2#创建形参x,创建了函数体:x+2并把结果return) ret=test(5) print(ret)
二、python的内置函数:
1.abs():
返回绝对值
参数可以是:负数、正数、浮点数或者长整形
abs(-1.2) #返回 1.2 abs(1.2) #返回 1.2 abs(-11216.5) #返回 11216.5 abs(11216.5) #返回 11216.5
2.all(iterable):
如果iterable(适合迭代的对象,Python里有大量内置的iterable类型,如: list,str,tuple,dict,file,xrange等)的所有元素不为0、''、False、或iterable不为空,all(iterable)返回True,否则返回False
空元组、空列表、空字典返回值为True,这里要特别注意
>>> all(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0 True >>> all(['a', 'b', '', 'd']) #列表list,存在一个为空的元素 False >>> all([0, 1,2, 3]) #列表list,存在一个为0的元素 False >>> all(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0 True >>> all(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素 False >>> all((0, 1,2, 3)) #元组tuple,存在一个为0的元素 False >>> all([]) # 空列表 True >>> all(()) # 空元组 True
>>> all({}) # 空字典
True
3.any(iterable):
如果iterable的任意元素不为0、''、False,any(iterable)返回True。如果iterable为空,返回False
空元组、空列表、空字典返回值为False
该函数与all()函数的区别,any是任意,而all是全部
>>> any(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0 True >>> any(['a', 'b', '', 'd']) #列表list,存在一个为空的元素 True >>> any([0, '', False]) #列表list,元素全为0,'',false False >>> any(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0 True >>> any(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素 True >>> any((0, '', False)) #元组tuple,元素全为0,'',false False >>> any([]) # 空列表 False >>> any(()) # 空元组 False >>> any({}) # 空字典 False
4.bin(x):
将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer
d=bin(3) print(d)#0b11 a=3.25 b=bin(a.__int__())#必须返回integer print(b)#0b11
5.chr(i):
返回整数i对应的ASCII字符。与ord()作用相反。
参数x:取值范围[0, 255]之间的正数。
>>> chr(97) 'a' >>> chr(98) 'b' >>> ord('a') 97 >>> ord('b') 98
6.enumerate():
enumerate函数用于遍历序列中的元素以及它们的下标
i = 0 seq = ['one', 'two', 'three'] for i in seq: print(i)#one two three
seq = ['one', 'two', 'three'] for i,item in enumerate(seq,4): print(i,item)#4 one 5 two 6 three
7.map():
遍历序列,对序列中每个元素进行操作,最终获取新的序列
li=[11,22,33,44] new_li=map(lambda x:x+100,li) l=list(new_li) print(l)#[111, 122, 133, 144]
8.filter():
对于序列中的元素进行筛选,最终获取符合条件的序列
li=[11,22,33,44] def func(x): if x>22: return True else: return False new_li=filter(func,li) l=list(new_li) print(l)#[33, 44]
9.zip():
把n个序列作为列表的元素返回
x=[11,22,33,44] y=[1,2,3,4] a=zip(x,y) a=list(a) print(a)#[(11, 1), (22, 2), (33, 3), (44, 4)] x2,y2=zip(*zip(x,y)) x2=list(x2) y2=list(y2) print(x2,y2)#[11, 22, 33, 44] [1, 2, 3, 4]
10.dir():
列出当前模块的属性列表
11.divmod():
分别取商和余数
c=12 d=9 print(divmod(c,d))#(1,3)
12.eval():
计算表达式expression的值
a=eval('4*8-9') print(a)#23
13.help():
帮助信息
14.hex():
将整数x转换为16进制字符串
print(hex(8))#0x8
15.id():
返回对象的唯一标识
16.oct():
将一个数字转化为8进制
print(oct(8))#0o10
17.ord():
参数是一个ascii字符,返回值是对应的十进制整数
print(ord('a'))#97
18.range():
for i in range(10): print(i)#0 1 2 3 4 5 6 7 8 9
19.reversed():
反转
l=['a','b','c','d'] m=reversed(l) m=list(m) print(m)#['d', 'c', 'b', 'a']
20.round():
四舍五入
print(round(5.8))#6
21.set():
对象实例化
a=list(set('abc')) print(a)
22.sortde():
排序
a=[1,2,31,4,5,22,33,11] b=sorted(a) print(b)#[1, 2, 4, 5, 11, 22, 31, 33]
23.open():
f=open('test.log','w',encoding='utf-8') f.write('五ksfjwie\n')#一个汉字占三个字节 f.write('wewewedsf\n') f.write('wewxdsdew\n')
f=open('test.log','r+',encoding='utf-8')
#调用read()会一次性读取文件的全部内容;调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回listprint(f.read())#五ksfjwie #wewewedsf #wewxdsdew print(f.readline())#五ksfjwie print(f.readlines())#['五ksfjwie\n', 'wewewedsf\n', 'wewxdsdew\n'] f.close()
f=open('test.log','r',encoding='utf-8') print(f.seek(5))#指定当前指针位置,按字节算 5 一个汉字占三个字节 五按照三个算
print(f.tell())#获取当前指针位置,按字节算 5
print(f.read(5))#指定读取字符,按字符算 前面两行注释掉,结果为:五ksfj,五按一个算;不注释掉前两个结果为:fjwie
f=open('test.log','r+',encoding='utf-8') print(f.seek(5))#指定当前指针位置 print(f.tell())#获取当前指针位置 f.truncate()#截断数据,仅保留指定之前数据 五ks
f.close()

浙公网安备 33010602011771号