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)
时间: 2024-10-25 07:37:47