1、set
无序,不重复序列、可嵌套
2、函数
==》 定义函数,函数体不执行,只有调用函数时,函数体才执行
1、def
2、名字
3、函数体
4、返回值
5、参数
普通参数
指定参数
默认参数
动态参数
*args
**kwargs
万能参数
*args,**kwargs
6、补充:
a.
def f1
def f2
函数重新赋值
b. 引用
c.全局变量
读,均可读
赋值,先global
字典,列表,可修改
==》全局变量用大写
3、三元运算
4、lamba表达式
函数:
编程分为两种:
面向过程、面向对象
断点:可以查看函数的执行过程
def f1():
asdf
asdfasd
asdfas
# 1、def 关键字,创建函数
# 2、函数名
# 3、()
# 4、函数体
# 5、返回值
发送邮件实例
def sendmail():
try:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["银子", 'xxx@126.com'])
msg['To'] = formataddr(["金子", 'yyy@qq.com'])
msg['Subject'] = "主题"
server = smtplib.SMTP("smtp.126.com", 25)
server.login("xxx@126.com", "123")
server.sendmail('xxx@126.com', ['yyy@qq.com', ], msg.as_string())
server.quit()
except:
# 发送失败
return "失败"
else:
# 发送成功
return "cc"
ret = sendmail()
print(ret)
if ret == "cc":
print('发送成功')
else:
print("发送失败")
"""
# print(123)
# def f1():
# print(123)
# # 在函数中,一旦执行return,函数执行过程立即终止
# return "111"
# print(456)
#
# r = f1()
# print(r)
# def f2():
# print(123)
#
# r = f2()
# print(r)
如果函数没有返回值,python自动默认return None
# 形式参数
如果没有return,python会默认返回None
# 1、普通参数(严格按照顺序,将实际参数赋值给形式参数)
# 2、默认参数(必须放置在参数列表的最后)
# 3、指定参数(将实际参数赋值给制定的形式参数)
# 4、动态参数:
# * 默认将传入的参数,全部放置在元组中, f1(*[1`1,22,33,44])
# ** 默认将传入的参数,全部放置在字典中 f1(**{"kl":"v1", "k2":"v2"})
# 5、万能参数, *args,**kwargs ,一个* 只能在前面,两个* 只能在后面
默认参数
def send(xxoo, content, xx="OK"):
print(xxoo, content, xx)
# print("发送邮件成功:", xxoo, content)
return True
send('alex', "sb")
send('alex', "sb", "BB")
普通参数
def send(xxoo,content):
print(xxoo,content)
return True
send('alex',"sb")
指定参数
def send(xxoo,content):
print(xxoo,content)
return True
send('alex',"sb")
def f1(*args):
print(args,type(args))
li=[11,22,33,"alex"]
f1(li)
f1(*li)
如果列表前面也有*,将把所有值传到元组中,可以接收动态参数。
def f1(**args):
print(args,type(args))
# f1(n1="alex",n2=18)
dic = {'k1':"v1","k2":"v2"}
# f1(kk=dic)
f1(**dic)
万能参数,一个* 只能在前面,两个* 只能在后面
def f1(*args,**kwargs):
print(args)
print(kwargs)
f1(11,22,33,44,k1="v1",k2="v2")
利用动态参数实现format功能
s = "i am {0}, age {1}".format("alex",18)
print(s)
s = "i am {0}, age {1}".format(*["alex",18])
print(s)
s1 = "i am {name}, age {age}".format(name="alex",age=18)
print(s1)
dic = {'name':'alex',"age":18}
s1 = "i am {name}, age {age}".format(**dic)
print(s1)
补充1:
python 内部有一套自己的垃圾回收机制,自动回收垃圾。
def f1(a1,a2):
return a1 +a2
def f1(a1,a2):
return a1*a2
ret = f1(8,8)
print(ret)
补充2:
函数参数传递是引用:
def f1(a1):
a1.append(999)
li=[11,22,33,44]
f1(li)
print(li)
补充3:
# 全局变量,所有作用域都可读
# 对全局变量进行【重新赋值】,需要global
# 特殊:列表字典,可修改,不可重新赋值
# 所有的全局变量必须全部是大写。
NAME="alex"
def f1():
age =18
# global name # 表示,name是全局变量
# print(name)
# name.append(999)
print(age,NAME)
def f2():
age = 19
print(age,NAME)
f1()
f2()
实例:函数式编程实现登陆和注册
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Alex Li
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 else简写
"""
if 1 == 1:
name = "alex"
else:
name = "SB"
# 如果 1==1 成立,
# name = "alex"
# 否则
# name = "SB"
name = "alex" if 1 == 1 else "SB"
"""
lambda表达式
def f1(a1):
return a1 + 100
f2 = lambda a1, a2=9: a1 + a2 + 100
ret = f1(10)
print(ret)
r2 = f2(9)
print(r2)
内置函数
abs()
all()
any()
bool()
ascii()
bin()
oct()
hex()
bytes()
# abs绝对值
# n = abs(-1)
# print(n)
# 所有为真,才为真
# n = all([1,2,3,None])
# print(n)
# 只要有真,就为真
# n = any([[],0,"",None])
# print(n)
# 0,None,"", [], () 都为False
# 注意" "中间有空格,此为True。
# print(bool(()))
# ascii() # 自动执行对象的 __repr__
# class Foo:
# def __repr__(self):
# return "444"
#
# n = ascii(Foo())
# print(n)
# bin() 八进制
# oct() 十进制
# hex() 十六进制
# print(bin(5))
# print(oct(9))
# print(hex(15))
"""
# utf-8 一个汉字:三个字节
# gbk 一个汉字:二个字节
# utf-8
s = "李杰"
# 一个字节8位,一个汉字三个字节
# 0101010 10101010 101010101 0101010 10101010 101010101
# 23 23 23 23 23 23 15
# 2f 2a 2c 2c 2e 2f f
# 字符串转换字节类型
# bytes(只要转换的字符串, 按照什么编码)
n = bytes("李杰", encoding="utf-8")
print(n)
n = bytes("李杰", encoding="gbk")
print(n)
# 字节转化成字符串
new_str = str(bytes("李杰", encoding="utf-8"), encoding="utf-8")
"""
文件操作之打开模式
open函数,该函数用于文件处理
文件操作分为三个步骤:打开文件、操作文件、关闭文件
# 1、打开文件
#文件句柄 = open('文件路径', '模式')
打开文件的模式有:
# f = open('db', 'r') # 【默认】
# f = open('db', 'w') # 【不可读;不存在则创建;存在则清空内容;】
# f = open('db', 'x') # 【不可读;不存在则创建,存在则报错】
# f = open('db', 'a') # 【可读; 不存在则创建;存在则只追加内容;】
“+” 表示可以同时读写某个文件:
# f = open('db', 'r+')读写【可读,可写】使用得最多得是r+
# f = open('db', 'w+')写读【可读,可写】w+每次写文件,首先会清空文件内容
# f = open('db', 'x+')写读【可读,可写】x+当前文件存在,就报错
# f = open('db', 'a+')写读【可读,可写】a+每次写文件,都会写到最后
“b”表示以字节的方式操作:
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
# f = open('db','r', encoding="utf-8")
# data = f.read()
# print(data, type(data))
# f.close()
# f = open('db','r')
# data = f.read()
# print(data,type(data))
# f = open('db','rb')
# data = f.read()
# print(data,type(data))
# f = open("db", 'a')
# f.write("李杰")
# f.close()
#
# f = open("db", 'ab')
# f.write(bytes("李杰", encoding="utf-8"))
# f.close()
# f = open("db", 'r+', encoding="utf-8")
# # f.fileno()
# # 如果打开模式无 b,则read,按照字符读取
# data = f.read(1)
# # tell当前指针所在的位置(字节)
# print(f.tell())
# # 调整当前指着你的位置(字节)
# f.seek(f.tell())
# # 当前指针位置开始向覆盖
# f.write("888")
# f.close()
# 2、操作文件
# read() # 无参数,读全部;有参数,
# b,按字节
# 无b,按字符
# tell() 获取当前指针位置(字节)
# seek(1) 指针跳转到指定位置(字节)
# write() 写数据,b,字节;无b,字符
# close
# fileno
# flush 强刷
# readline 仅读取一行
# truncate 截断,指针为后的清空
# for循环文件对象 f = open(xxx)
# for line in f:
# print(line)
# f = open("db", 'r+', encoding="utf-8")
# f.seek(3)
# f.truncate()
# f.close()
# f = open("db", 'r+', encoding="utf-8")
# for line in f:
# print(line)
# 通过源码查看功能
# 3、关闭文件
# f.close()
# with open('xb') as f:
# pass
with open('xb') as f:
pass
with可以同时打开多个文件,从2.7开始添加的新功能。
with open('db','r',encoding="utf-8") as f1,open("db1",'w',encoding="utf-8") as f2:
times = 0
for line in f1:
times += 1
if times <= 10:
f2.write(line)
else:
break
替换文件:
with open('db','r',encoding="utf-8") as f1,open("db1",'w',encoding="utf-8") as f2:
for line in f1:
new_str = line.replace("alex","luchuan")
f2.write(new_str)
with open('db1', 'r', encoding="utf-8") as f1, open("db2", 'w',encoding="utf-8") as f2:
for line in f1:
if line == "xx":
f2.write()
f2.write()
# new_str = line.replace("alex", 'st')
# f2.write(new_str)
class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer.
encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False).
errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict".
newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.
If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass
def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass
def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass
def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass
def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass
def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass
def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass
def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass
def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass
def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass
def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass
def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass
def write(self, *args, **kwargs): # real signature unknown
写内容
pass
def __getstate__(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
3.x