Python开发【第三篇】:Python函数
set
无序,不重复,可嵌套。
函数
创建函数:
1、def关键字,创建函数
2、函数名
3、()
4、函数体
5、返回值
发邮件函数
- def sendmail():
- import smtplib
- from email.mime.text import MIMEText
- from email.utils import formataddr
- #三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
- msg = MIMEText('邮件内容','plain','utf-8')
- msg['From'] = formataddr(["发件人名称",'发件人邮箱'])
- msg['To'] = formataddr(["哈哈",'收件人邮箱'])
- msg['Subject'] = "邮件主题"
- server = smtplib.SMTP("smtp地址",端口)
- #需要在开启SMTP,否则发送失败
- server.login("发件人邮箱","密码")
- server.sendmail('发件人邮箱',['收件人邮箱'],msg.as_string())
- server.quit()
- sendmail()
函数中的return
- def f1():
- print(123)
- #在函数中,一旦执行return,函数执行过程立即终止
- return "111"
- print(456)
- r = f1()
- print(r)
函数的默认返回值None
- def f2():
- print(123)
- r = f2()
- print(r)
普通参数
- #形参【形式参数】:xx
- def sendmail(xx,content):
- import smtplib
- from email.mime.text import MIMEText
- from email.utils import formataddr
- #捕获异常
- try:
- msg = MIMEText(content,'plain','utf-8')
- msg['From'] = formataddr(["Golden",'发件人地址'])
- msg['To'] = formataddr(["哈哈",'收件人地址'])
- msg['Subject'] = "主题"
- server = smtplib.SMTP("smtp.126.com",25)
- server.login('发件人地址','密码')
- server.sendmail('发件人地址',[xx],msg.as_string())
- server.quit()
- except:
- #发送失败
- return False
- else:
- #发送成功
- return True
- #实际参数:收件人1\收件人2
- # ret = sendmail("收件人1")
- # ret = sendmail("收件人2")
- while True:
- em = input("请输入收件人邮箱地址:")
- result = sendmail(em,"你好")
- if result == True:
- print("发送成功")
- else:
- print("发送失败")
默认参数
- def send(xx,content,hh="ok"):
- print(xx,content,hh)
- print("发送邮件成功:",xx,content)
- return True
- send("hahaha",'hello')
- send("hahaha",'hello','bbbb')
注意:如果需要给某个参数指定默认值,该参数必须放在参数列表的最后。
指定参数
- def send(xx,content):
- print(xx,content)
- return True
- send("hahaha","hello")
- send(content="hahaha",xx="hello")
动态参数:*
- def f1(*args):
- print(args,type(args))
- f1(11,22,33,"haha","hello")
- li = [12,23,33,"hahaha","hi"]
- f1(li)
- f1(*li)
注意:*默认将传入的参数全部放置在元组中,f1(*li)。
动态参数:字典(**)
- def f1(**args):
- print(args,type(args))
- f1(n1="alex",kk=18)
- dic = {'k1':'v1','k2':'v2'}
- f1(**dic)
注意:**默认将传入的参数全部放置在字典中,f1(**dic)。
万能参数
- def f1(*args,**kwargs):
- print(args)
- print(kwargs)
- f1(11,22,33,44,k1='v1',k2='v2')
注意:*args,**kwargs顺序不能改变。
动态参数实现format功能
- s = "i am {0},age {1}".format("alex",18)
- print(s)
- s1 = "i am {0},age {1}".format(*["alex",19])
- print(s1)
- s2 = "i am {name},age {age}".format(age=20,name='alex')
- print(s2)
- dic ={'name':'alex','age':21}
- s3 = "i am {name},age {age}".format(**dic)
- print(s3)
猜一猜输出
- def f1(a1,a2):
- print('+')
- return a1 + a2
- def f1(a1,a2):
- print('*')
- return a1 * a2
- ret = f1(8,8)
- print(ret)
- def f1(a1):
- a1.append(999)
- li = [11,22,33,44]
- f1(li)
- print(li)
注意:函数参数传递的是引用。
全局变量
- NAME = "alex"
- AGE = 22
- def f1():
- num = 18
- NAME = "haha"
- #修改全局变量:age
- global AGE
- AGE = 25
- print(num,AGE,NAME)
- def f2():
- num = 19
- print(num,AGE,NAME)
- f1()
- f2()
注意:全局变量重新赋值需要用global,对于列表或字典,可修改,不可重新赋值。定义全局变量全部大写。
函数实现登录与注册
- def login(username,password):
- """
- 用于用户登录
- :param username: 用户输入的用户名
- :param password: 用户输入的密码
- :return:True,登录成功;False,登录失败
- """
- f = open("db",'r')
- #逐行读取
- for line in f:
- #用"|"进行分割
- line_list = line.strip().split("|")
- #匹配是否正确
- if line_list[0] == username and line_list[1] == password:
- return True
- return False
- def register(username,password):
- """
- 用户注册
- :param username:用户名
- :param password:密码
- :return:默认返回None
- """
- f = open("db",'a')
- temp = "\n"+username + "|" + password
- f.write(temp)
- f.close()
- def main():
- t = input("1:登录;2:注册")
- if t == "1":
- user = input("请输入用户名:")
- pwd = input("请输入密码:")
- r = login(user,pwd)
- if r:
- print("登录成功")
- else:
- print("登录失败")
- elif t == "2":
- user = input("请输入用户名:")
- pwd = input("请输入密码:")
- register(user,pwd)
- main()
三元运算(三目运算)
- if 1 == 1:
- name = "alex"
- else:
- name = "golden"
- #上面代码等价于
- name = "alex" if 1 == 1 else "golden"
lambda表达式
- def f1(a1):
- return a1 + 100
- #等价上面的代码
- f2 = lambda a1:a1 + 100
- ret = f1(10)
- print(ret)
- r2 = f2(9)
- print(r2)
内置函数
- #abs():取绝对值
- n = abs(-1)
- print (n)
- #all():所有为真,才为真
- #any():任何一个为真,就是真
- n = all([1,2,3,4,[]])
- print(n)
- n2 = any([1,[],0,"",None])
- print(n2)
- #ascii():自动执行对象的 _repr_方法
- class Foo:
- def _repr_(self):
- return "111"
- n = ascii(Foo())
- print(n)
- #bin():转二进制
- #oct():转八进制
- #hex():转十六进制
- print(bin(5))
- print(oct(9))
- print(hex(15))
- #utf-8 一个汉字:三个字节
- #gbk 一个汉字:二个字节
- #utf-8,一个字节八位,一个汉字三个字节
- s = "李杰"
- #字符串转换字节类型
- #bytes(需要转换的字符串,按照什么编码)
- n = bytes(s,encoding="utf-8")
- print(n)
- n = bytes(s,encoding="gbk")
- print(n)
- #字节转化成字符串
- new_str = str(bytes("李杰",encoding="utf-8"),encoding="utf-8")
- #1、打开文件
- #只读
- f = open('db','r')
- #只写,先清空源文件
- f = open('db','w')
- #文件存在,报错;不存在,创建并写内容
- f = open('db','x')
- #追加
- f = open('db','a')
- #2、操作文件
- #通过源码查看功能
- f.read()
- f.write()
- #3、关闭文件
- f.close()
- with open('db') as f:
- pass
- f = open('db','r',encoding="GBK")
- #f = open('db','r',encoding="utf-8")
- data = f.read()
- print(data,type(data))
- f.close()
- f = open("db","r+",encoding="utf-8")
- #如果打开模式无b,则read,按照字符读取
- data = f.read()
- #获取当前指针的位置(字节)
- print(f.tell())
- print(data)
- #移动当前指针到固定位置(字节)
- f.seek(1)
- #当前指针位置开始向后覆盖
- f.write("777")
- f.close()
- f = open('db','rb')
- data = f.read()
- print(data,type(data))
- f = open('db','ab')
- f.write(bytes("李杰",encoding="utf-8"))
- f.close()
flush()强刷:
- f = open("db",'a')
- f.write("123")
- #强制写入
- f.flush()
- input("adsdds")
readable()查看文件是否可读,返回True或False。
- f = open("db",'w')
- print(f.readable())
readline()仅读取一行数据,当文件特别大的时候不至于导致内存撑爆。
- f = open("db",'r')
- f.readline()
- f.readline()
truncate()截断,指针后面的数据清空
- f = open("db",'r+',encoding="utf-8")
- f.seek(3)
- f.truncate()
- f.close()
for循环打开的文件对象:
- f = open("db",'r')
- for line in f:
- print(line)
- f.close()
将文件1的前十行写入文件2:
- with open('db1','r',encoding="utf-8") as f1,open('db2','w',encoding="utf-8") as f2:
- times = 0
- for line in f1:
- times += 1
- if times <= 10:
- f2.write(line)
- else:
- break
将文件的某个字符串进行替换:
- with open('db1','r',encoding="utf-8") as f1,open("db2",'w',encoding="utf-8") as f2:
- for line in f1:
- new_str = line.replace("alex","st")
- f2.write(new_str)
callable()查看函数是否可以被调用,返回True或False
- def f1():
- pass
- f1()
- f2 = 123
- print(callable(f1))
- print(callable(f2))
chr()与ord()
- r = chr(65)
- n = ord("B")
- print(r,n)
产生1个随机大写字母:
- import random
- i = random.randrange(65,91)
- print(chr(i))
产生6个随机大写字母:
- import random
- li = []
- for i in range(6):
- temp = random.randrange(65,91)
- c = chr(temp)
- li.append(c)
- result = "".join(li)
- print(result)
随机产生字母加数字:
- import random
- li = []
- for i in range(6):
- r = random.randrange(0,6)
- if r == 2 or r == 4:
- num = random.randrange(0,10)
- li.append(str(num))
- else:
- temp = random.randrange(65,91)
- c = chr(temp)
- li.append(c)
- result = "".join(li)
- print(result)
compile():将字符串编译成python代码
exec():执行python代码或字符串,无返回值
eval():执行表达式,有返回值
- s = "print(123)"
- #先编译,single、eval、exec
- #将字符串编译成python代码
- r = compile(s,"<string>","exec")
- print(r)
- #然后执行
- exec(r)
- s = "8*8"
- ret = eval(s)
- print(ret)
dir()快速查看对象提供了哪些功能
- print(dir(dict))
divmod()计算商和余数
- r = divmod(97,10)
- print(r)
isinstance()判断对象是否是某个类的实例
- s = [11,22,33]
- r = isinstance(s,list)
- print(r)
filter():函数返回True,将元素添加到结果中
map():将函数返回值添加到结果中
将列表中大于22的数输出
- def f1(args):
- result = []
- for item in args:
- if item > 22:
- result.append(item)
- return result
- li = [11,22,33,44,55,66,78]
- ret = f1(li)
- print(ret)
filter()实现
- #filter(函数,可迭代的对象)
- def f2(a):
- if a > 22:
- return True
- li = [11,22,33,44,55,66,78]
- #filter内部会循环第二个参数,将每个循环元素执行第一个函数,如果函数返回值是True,就添加到ret中
- ret = filter(f2,li)
- print(list(ret))
filter()+lambda实现
- li = [11,22,33,44,55,66,78]
- ret = filter(lambda a : a > 22,li)
- print(list(ret))
将列表中每个元素加100
- def f1(args):
- result = []
- for i in args:
- result.append(i+100)
- return result
- li = [11,22,33,44,55,66,78]
- r = f1(li)
- print(list(r))
map()实现
- #map(函数,可迭代的对象)
- def f2(a):
- return a + 100
- li = [11,22,33,44,55,66,78]
- result = map(f2,li)
- print(list(result))
map()+lambda实现
- li = [11,22,33,44,55,66,78]
- result = map(lambda a : a + 100,li)
- print(list(result))
hash():生成hash值
- s = "hhhh"
- print(hash(s))
max():返回最大值
min():返回最小值
sum():返回和
pow():指数计算
- r = pow(2,10)
- print(r)
reverse():反转
round():四舍五入
sorted():排序
zip()
- #获取字符串 s = "alex_is_good_guy"
- l1 = ["alex",22,33,44,55]
- l2 = ["is",22,33,44,55]
- l3 = ["good",22,33,44,55]
- l4 = ["guy",22,33,44,55]
- r = zip(l1,l2,l3,l4)
- temp = list(r)[0]
- ret = '_'.join(temp)
- print(ret)
装饰器
s1:
- def outer():
- print("log")
- def f1():
- outer()
- print("F1")
- def f2():
- outer()
- print("F2")
- def f100():
- outer()
- print("F100")
b1:
- import s1
- s2.f1()
- s2.f2()
- s2.f100()
装饰器实现
s1:
- def outer(func):
- def inner():
- print("log")
- return func()
- return inner
- @outer
- def f1():
- print("f1")
- @outer
- def f2():
- print("f2")
- @outer
- def f100():
- print("f100")
b1:
- import s1
- s2.f1()
- s2.f2()
- s2.f100()
在调用函数前后输出内容
- def outer(func):
- def inner():
- print("log")
- ret = func()
- print("after")
- return ret
- return inner
求输出内容:
一:
- def f1():
- print("123")
- def f2(xxx):
- xxx()
- f2(f1)
二:
- def f1():
- print("123")
- def f1():
- print("234")
- f1()
传参一:
s1:
- def outer(func):
- def inner(a):
- print("log")
- ret = func(a)
- print("after")
- return ret
- return inner
- @outer
- def f1(arg):
- print(arg)
- return "砍你"
b1:
- import s:1
- s2.f1("hahahaha")
参数二:
s1:
- def outer(func):
- def inner(*args,**kwargs):
- print("log")
- ret = func(*args,**kwargs)
- print("after")
- return ret
- return inner
- @outer
- def f1(arg):
- print(arg)
- return "砍你"
- @outer
- def f2(arg1,arg2):
- print(arg1,arg2)
- print("f2")
b1:
- import s1
- s2.f1("hahahaha")
- s2.f2("111","222")
查询字符串是否包含子字符串:
- #in方法
- str = "hsaoiuo kkaoioweioew"
- if "iowe" in str:
- print("存在")
- else:
- print("不存在")
- #fand方法
- str = "hsaoiuo kkaoioweioew"
- if str.find("iowe") == -1:
- print("不存在")
- else:
- print("存在")
posted on 2016-11-30 10:49 yinshoucheng 阅读(1489) 评论(2) 编辑 收藏 举报