----------------------------------------------------------------------------------------------------
前期回顾:
前期回顾:
Python简介
Python入门
内容编码
注释
脚本参数传入
.pyc文件
变量的声明
用户输入(input)
流程控制(if...else...,缩进,循环,break,continue)
运算(+,-,*,/)
基本数据类型(数字,字符串,布尔值)
面向对象
str,list,tuple,dict
----------------------------------------------------------------------------------------------------
本期大纲:
一、set集合
—创建集合
—集合功能及操作
—练习
二、函数
— 自定义函数
— 自定义函数小练习
— 内置函数
----------------------------------------------------------------------------------------------------
一、set集合
set集合是一个无序且不重复的序列
1、创建集合
li = ["12","34","56",] #列表
dic = {"k":"v"} #字典
se = {"123","456"} #集合
s1 = {11,22}
s2 = set()
s3 = set([11,22,33,4])
>>> s = set()
>>> li = [11,22,11,22]
>>> s = set(li)
>>> print(s)
{11, 22}
2、集合功能及操作
add #添加元素
add(
self
,
*
args,
*
*
kwargs)
>>> s = set()
>>> print(s)
set()
>>> s.add(123)
>>> print(s)
{123}
clear #清楚所有内容
clear(self, *args, **kwargs)
>>> s = {123}
>>> print(s)
{123}
>>> s.clear()
>>> print(s)
set()
copy #浅拷贝
copy(
self
,
*
args,
*
*
kwargs)
difference A中存在B中不存在
difference(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s3 = s1.difference(s2)
>>> print(s3)
{11}
>>> s3 = s2.difference(s1)
>>> print(s3)
{44}
difference_update #从当前集合中删除和B中相同的元素
difference_update(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.difference_update(s2)
>>> print(s1)
{11}
symmetric_difference #对称差集
symmetric_difference(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s3 = s1.symmetric_difference(s2)
>>> print(s3)
{33, 11, 44, 22}
>>> s4 = s2.symmetric_difference(s1)
>>> print(s4)
{33, 11, 44, 22}
symmetric_difference_update #对称差集,并更新到a中
symmetric_difference_update(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.symmetric_difference_update(s2)
>>> print(s1)
{33, 11, 44, 22}
discard #移除某个元素,不存在不报错
discard(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s1.discard(11)
>>> print(s1)
{33, 22}
remove #移除某个元素,不存在会报错
remove(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s1.remove(11111)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 11111
>>> s1.remove(11)
>>> print(s1)
{33, 22}
pop #随机移除某个元素
pop(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> ret = s1.pop()
>>> print(ret)
33
>>> print(s1)
{11, 22}
#ret为删除的值
intersection #取交集,共同都有的
intersection(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s3 = s1.intersection(s2)
>>> print(s3)
{33, 22}
intersection_update #取交集并更更新到A中
intersection_update(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.intersection_update(s2)
>>> print(s1)
{33, 22}
isdisjoint #如果没有交集,返回True,否则返回False
isdisjoint(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s1.isdisjoint(s2)
False
#有交集返回False
>>> s1 = {11,22,33}
>>> s2 = {44,55,66}
>>> s1.isdisjoint(s2)
True
#没有交集返回True
issubset #是否是子序列
issubset(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {44,55,66}
>>> s1.issubset(s2)
False
issuperset #是否是父序列
issuperset(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {44,55,66}
>>> s1.issuperset(s2)
False
union #并集
union(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> s2 = {22,33,44}
>>> s3 = s1.union(s2)
>>> print(s3)
{33, 22, 11, 44}
update #可以迭代
update(
self
,
*
args,
*
*
kwargs)
>>> s1 = {11,22,33}
>>> li = [11,22,3,11,2]
>>> s1.update(li)
>>> print(s1)
{3, 33, 2, 11, 22}
>>> li = (11,22,3,11,2)
>>> s1.update(li)
>>> print(s1)
{3, 33, 2, 11, 22}
>>> li = "sandler"
>>> s1.update(li)
>>> print(s1)
{'a', 33, 2, 3, 'd', 'l', 'e', 11, 's', 22, 'r', 'n'}
3、练习
#!/usr/bin/env python
# -.- coding: utf-8 -.-
# by sandler
old_dice = {
"#1":8,
"#2":4,
"#4":2,
}
new_dice = {
"#1":4,
"#2":4,
"#3":2,
}
#应该删除那几个槽位
#应该更新那几个槽位
#应该增加那几个槽位
new_set = set(new_dice.keys())
old_set = set(old_dice.keys())
remove_set = old_set.difference(new_set)
add_set = new_set.difference(old_set)
update_set = old_set.intersection(new_set)
----------------------------------------------------------------------------------------------------
二、函数
1、自定义函数
1)使用:
(1)、def关键字,创建函数
(2)、函数名
(3)、():
(4)、函数体
(5)、返回值
def 函数名():
函数体
返回值
函数示例,邮件发送:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# By Sandler
def sendmail():
try:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])
msg['To'] = formataddr(["走人",'424662508@qq.com'])
msg['Subject'] = "主题"
server = smtplib.SMTP("smtp.126.com", 25)
server.login("wptawy@126.com", "邮箱密码")
server.sendmail('wptawy@126.com', ['3628905@qq.com',], msg.as_string())
server.quit()
except:
# 发送失败
return "失败"
else:
# 发送成功
return "cc"
ret = sendmail()
print(ret)
if ret == "cc":
print('发送成功')
else:
print("发送失败")
2)参数:
普通参数(严格按照顺序,将实际参数赋值给形式参数)
>>> def f1(name):
... print(name)
...
>>> f1('sandler')
sandler
>>> def f1(name,age):
... print(name)
... print(age)
...
>>> f1('sandler',18)
sandler
18
默认参数(必须放置在参数列表最后)
>>> def f1(name,age,job='IT'):
... print(name)
... print(age)
... print(job)
...
>>> f1("sandler",18)
sandler
18
IT
>>> f1("sandler",18,"HR")
sandler
18
HR
指定参数(将实际参数赋值给定值的形式参数)
>>> def f1(name,age,job='IT'):
... print(name)
... print(age)
... print(job)
...
>>> f1(age=18,name="sandler",job="HR")
sandler
18
HR
动态参数
'*args'(可以传入多个参数,转换成元祖,如果传入一个列表,则会把整个列表转化成一个元祖的元素,但如果列表前加上*,则会把列表的每一个元素转化成元祖的元素)
>>> def f1(*args):
... print(args,type(args))
...
>>> f1(11)
(11,) <class 'tuple'>
>>> li = [11,22,33,44]
>>> f1(li)
([11, 22, 33, 44],) <class 'tuple'>
>>> f1(*li)
(11, 22, 33, 44) <class 'tuple'>
>>> li = "sandler"
>>> f1(*li)
('s', 'a', 'n', 'd', 'l', 'e', 'r') <class 'tuple'>
'**args'(动态指定参数,指定某个key和value,例:n1="sandler",传入后转化为字典,)
>>> def f1(**args):
... print(args,type(args))
...
>>> f1(k1="v1")
{'k1': 'v1'} <class 'dict'>
>>> dic = { "k1":"v1","k2":"v2"}
>>> f1(kk=dic)
{'kk': {'k2': 'v2', 'k1': 'v1'}} <class 'dict'>
>>> f1(**dic)
{'k2': 'v2', 'k1': 'v1'} <class 'dict'>
万能参数(*args,**kwargs)
>>> def f1(*args,**kwargs):
... print(args,type(args))
... print(kwargs,type(kwargs))
...
>>> f1(11,22,33,44,k1="v1",k2="v2")
(11, 22, 33, 44) <class 'tuple'>
{'k1': 'v1', 'k2': 'v2'} <class 'dict'>
3)补充:
字符串格式化: .format(*args,**kwargs)
>>> s1 = "i am {0}, age {1}.".format("sandler", 18)
>>> print(s1)
i am sandler, age 18.
>>> s2 = "i am {0}, age {1}".format(*["sandler", 18])
>>> print(s2)
i am sandler, age 18
>>> s1 = "i am {name}, age {age}".format(name='sandler', age=18)
>>> print(s1)
i am sandler, age 18
>>> dic = {'name': 'sandler', "age": 18}
>>> s2 = "i am {name}, age {age}".format(**dic)
>>> print(s2)
i am sandler, age 18
全局变量:所有的作用域都可读,优先使用自己作用域的变量,
全局变量的变量名需要全部大写(潜规则)
对全局变量进行重新赋值,需要global
global 变量名 在任意作用域定义全局变量
特殊:列表字典,可修改,不可重新赋值
#!/usr/bin/env python
# -.- coding: utf-8 -.-
# By sandler
'''
def f1():
name = "alex"
print(name)
def f2():
print(name)
name变量定义在f1函数中,所以只有f1函数可以读取,f2函数无法读取name变量
'''
NAME = "sandler"
def f1():
age = 18
print(NAME,age)
def f2():
age = 19
print(NAME,age)
f1()
f2()
def f3():
age = 18
global NAME # 表示,name是全局变量
NAME = "yuli"
print(age, NAME)
def f4():
age = 19
print(age, NAME)
f3()
f4()
4)三元运算:对于简单的 if else 语句,可以使用三元运算来表示,即:
if 1 == 1:
name = "sandler"
else:
name = "yuli"
name = "sandler" if 1 == 1 else "yuli"
5)lambda表达式:简单的函数,只能用一行
def func(arg):
return arg + 1
result = func(123)
my_lambda = lambda arg : arg + 1
result = my_lambda(123)
2、自定义函数小练习
编写一个用户登录程序,程序包含用户登录和用户注册,利用函数编写:
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
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 = " " + 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()
3、内置函数
abs() 绝对值
>>> num = abs(3)
>>> print(num)
3
all() 所有为真,才为真
>>> num = all([1,2,3,None])
>>> print(num)
False
>>> num = all([1,2,3])
>>> print(num)
True
any() 只要有真,就为真
>>> num = any([[],0,"",None])
>>> print(num)
False
>>> num = any([[],1,"",None])
>>> print(num)
True
ascii() 忘掉他吧
# 按大王的至理名言来说”忘掉他吧“
>>> class Foo:
... def __repr__(self):
... return "444"
...
>>> num = ascii(Foo())
>>> print(num)
444
bin() 十进制转二进制
>>> print(bin(8))
0b1000
oct() 十进制转八进制
>>> print(oct(12))
0o14
hex() 十进制转十六进制
>>> print(hex(14))
0xe
bool() 布尔值,真或假
>>> print(bool(1))
True
>>> print(bool(0))
False
>>> print(bool(None))
False
>>> print(bool(()))
False
>>> print(bool([]))
False
>>> print(bool({}))
False
bytes() 把字符串转换成字节类型,需要定义编码格式 例“n = bytes("李杰",encoding="utf-8")”
# utf-8 一个汉字:三个字节
# gbk 一个汉字:二个字节
# 字符串转换字节类型
# bytes(只要转换的字符串, 按照什么编码)
>>> name = "李杰"
>>> print(name)
李杰
>>> bytes_name = bytes(name,encoding="utf-8")
>>> print(bytes_name)
b'xe6x9dx8exe6x9dxb0'
>>> bytes_name = bytes(name,encoding="gbk")
>>> print(bytes_name)
b'xc0xeexbdxdc'
str() 把字节转换成字符串str(bytes("李杰",encoding="utf-8"),encoding="utf-8")
>>> name = "李杰"
>>> print(name)
李杰
>>> bytes_name = bytes(name,encoding="gbk")
>>> print(bytes_name)
b'xc0xeexbdxdc'
>>> str_name = str(bytes_name,encoding="gbk")
>>> print(str_name)
李杰
open() 文件处理操作
操作文件是一般分为:打开文件、操作文件、关闭文件
(1)打开文件:
文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
r ,只读模式【默认】
w,只写模式【不可读;不存在则创建;存在则清空内容;】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
x+ ,写读【可读,可写】
a+, 写读【可读,可写】
"b"表示以字节的方式操作
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
f = open('db', 'r') # 只读
f = open('db', 'w') # 只写,先清空原文件
f = open('db', 'x') # 文件存在,报错;不存在,创建并只写
f = open('db', 'a') # 追加
f = open('db','r', encoding="utf-8")
(2)操作文件:
close(self, *args, **kwargs) #关闭文件
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db","r")
#打开文件f.read()
#读取文件f.close()
#关闭文件
fileno(self, *args, **kwargs) #文件描述符
#! /usr/bin/env python
# -.- coding: utf-8 -.-
# By Sandler
f = open("db", 'r+')
f.fileno()
flush(self, *args, **kwargs) #刷新文件内部缓冲区
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db", 'a')
f.write("123")
f.flush() #强制刷新写入上面的内容
input("请输入: ") #等待用户输入
isatty(self, *args, **kwargs) #判断文件是否是同意tty设备
read(self, *args, **kwargs) #读取指定字节数据
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db","r")
data = f.read()
print(data)
f.close()
readable(self, *args, **kwargs) #是否可读
readline(self, *args, **kwargs) #仅读取一行数据
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db","r")
for line in f:
print(line)
#按行打印文件内容f.close()
seek(self, *args, **kwargs) #指定文件中指针位置
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db","r")
f.seek(3) #指定指针位置为第三个字节
seekable(self, *args, **kwargs) #指针是否可操作
tell(self, *args, **kwargs) #获取指针位置
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db","r")
print(f.tell()) #打印当前指针位置(字节)
truncate(self, *args, **kwargs) #截断数据,仅保留指定之前数据
#!/usr/bin/env python
# -.- coding:utf-8 -.-
# By Sandler
f = open("db", 'r+')
f.seek(3) #指定指针位置
f.truncate() #截断,指针位置后的数据清空
f.close()
writable(self, *args, **kwargs) #是否可写
write(self, *args, **kwargs) #写内容
#! /usr/bin/env python
# -.- coding: utf-8 -.-
# By Sandler
f = open("db", 'w') #打开文件
f.write("yuli") #先清空文件内容,再写入文件
f.close() #关闭文件
f = open("db", 'a') #打开文件
f.write("alice") #追加写入文件到最后一行
f.close() #关闭文件
----------------------------------------------------------------------------------------------------