python第三课

# 集合
list_1 = [1, 4, 5, 7, 3, 6, 7, 9]
list_1 = set(list_1)

list_2 = set([4, 6, 0, 66, 22, 8])
print(list_1, type(list_1))

print(list_1.intersection(list_2))   # 交集
print(list_1.union(list_2))   # 并集
print(list_1.difference(list_2))   # 差集

list_3 = set([1, 3, 7])
print(list_3.issubset(list_1))   # 子集
print(list_1.issuperset(list_3))   # 父集

print(list_1.symmetric_difference(list_2))   # 对称差集

list_4 = set([5, 6, 8])
print(list_3.isdisjoint(list_4))


print(list_1 & list_2)  # 交集
print(list_1 | list_2)  # 并集
print(list_1 - list_2)  # 差集
print(list_1 ^ list_2)  # 对称差集

list_1.add(999)  # 添加
list_1.update([888, 777, 555])
# remove 删除

list_1.discard("888")

# 文件操作
f = open("yesterday1", 'r', encoding='utf-8')  # 文件句柄
data = f.read()
print(data)
f = open("yesterday1", 'w', encoding='utf-8')  # 文件句柄
f.write("我爱北京天安门,\n")
f.write("天安门上太阳升")
f = open("yesterday1", 'a', encoding='utf-8')  # a = append 追加
f.write("我爱北京天安门。。。。,\n")
f.write("天安门上太阳升。。\n")
f.write("\nWhen i was young i listen to the radio\n")
data = f.read()
print("--read", data)
f.close()
f = open("yesterday1", 'r', encoding='utf-8')
# print(f.readline())
for line in f.readlines():
    print(line.strip())
for i in range(5):
    print(f.readline())
for index, line in enumerate(f.readlines()):
    if index == 9:
        print("---我是分割线---")
        continue
    print(line.strip())
f.close()
f = open("yesterday1", 'r', encoding='utf-8')
count = 0
for line in f:
    if count == 9:
        print("---我是分割线---")
        count += 1
        continue
    print(line)
f.close()
f = open("yesterday1", 'r', encoding='utf-8')
print(f.tell())
print(f.readline())
print(f.read(5))
print(f.tell())
print(f.readline())
print(f.readline())
print(f.tell())
f.seek(0)  # 光标移到某个位置
print(f.readline())
print(f.tell())  # 打印当前的光标位置

print(f.fileno())  # 文件句柄
print(f.name())  # 文件名称
print(f.seekable())  # 判断光标是否可移动
print(f.flush())  # 刷新
f.close()

import sys, time
for i in range(20):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.2)

f = open("yesterday1", 'a', encoding='utf-8')
f.truncate(20)  # 截断
f.close()

f = open("yesterday1", 'r+', encoding='utf-8')    # 读 追加
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.write("-----------D---------")
f.close()

f = open("yesterday1", 'w+', encoding='utf-8')    # 写 读
f.write("-----------D---------1\n")
f.write("-----------D---------1\n")
f.write("-----------D---------1\n")
print(f.tell())
f.seek(10)
print(f.readline())
f.write("should be at the begining of the second line")
f.close()
a+ 追加读
rb 二进制读
wb 二进制写

# 文件修改
f = open("yesterday1", "r", encoding="utf-8")
f_new = open("yesterday2.bak", "w", encoding="utf-8")
for line in f:
    if "肆意的快乐等我享受" in line:
        line = line.replace("肆意的快乐等我享受", "肆意的快乐等Alex享受")
    f_new.write(line)
f.close()
f_new.close()

with open("yesterday2", "r", encoding="utf-8") as f:
    for line in f:

        print(line)

# 编码转换
# -*-coding:gbk-*-
import sys
print(sys.getdefaultencoding())
s = "你好"   # 数据类型是unicode
print(s.encode("gbk"))
print(s.encode("utf-8"))
print(s.encode("utf-8").decode("utf-8").encode("gb2312").decode("gb2312"))

# 函数与函数式编程
1.面向对象:类-->class
2.面向过程:过程-->def
3.函数式编程:函数-->def
函数是逻辑结构化和过程的一种编程方法
def test(x):
    """The function definitions"""
    x += 1
    return x
def: 定义函数的关键字
test: 函数名
():内可定义形参
"":文档描述(非必要,但是强烈建议为你的函数添加描述信息)
x+=1:泛指代码块或程序处理逻辑
return:定义返回值
# 函数
def func1():
    """testing1"""
    print('in the func1')
    return 0
# 过程
def func2():
    """testing2"""
    print('in the func2')

x=func1()
y=func2()
print('from func1 return is %s' %x)
print('from func2 return is %s' %y)
import time
def logger():
    time_format = '%Y-%m-%d %X'
    time_current = time.strftime(time_format)
    with open('a.txt', 'a+') as f:
        f.write('end action\n')
def test1():
    print('test1 starting action...')
    logger()
def test2():
    print('test2 starting action...')
    logger()
def test3():
    print('test3 starting action...')
    logger()

def test1():
    print('in the test1')
def test2():
    print('in the test2')
    return 0
def test3():
    print('in the test3')
    return 1,'hello',['alex','wupeiqi'],{'name': 'alex'}
x = test1()
y = test2()
z = test3()
print(x)
print(y)
print(z)


def test(x, y, z):
    print(x)
    print(y)
    print(z)
test(y=2,x=1) # 与形参顺序无关
test(1, 2)  # 与形参一一对应
test(x=2,3)
test(3,z=2,y=6)


def test(x,y=2):
    print(x)
    print(y)
test(1)
test(1,3)
def test(x,soft1=True,soft2=True):
    print(x)
def conn(host,port=3306):
    pass
conn()
# 默认参数特点:调用函数的时候,默认参数非必须传递
# 用途:默认安装值

def test(x,y,z=2):
    print(x)
    print(y)
test(1,2,3)

# 参数组
def test(*args):
    print(args)
test(1,2,3,4,5)
test(*[1,2,3,4,5])   # args=tuple([1,2,3,4,5])
# *args:接收N个位置参数,转换成元祖形式
def test1(x,*args):
    print(x)
    print(args)
test1(1,2,3,4,5,6,7)
# **kwargs:把N个关键字参数,转换成字典的方式
def test2(**kwargs):
    print(kwargs)
    print(kwargs['name'])
    print(kwargs['age'])
    print(kwargs['sex'])
test2(name='alex',age=8,sex='N')
test2(**{'name':'alex','age':'8'})

def test3(name,**kwargs):
    print(name)
    print(kwargs)
test3('alex',age=18,sex='m')

def test4(name,age=18,**kwargs):  # 参数组一定在后面
    print(name)
    print(age)
    print(kwargs)
test4('alex',sex='m',hobby='tesla',age=3)

def test4(name,age=18,*args,**kwargs):
    print(name)
    print(age)
    print(args)
    print(kwargs)

    logger("TEST4")
def logger(source):
    print("from %s" % source)

test4('alex',age=34,sex='m',hobby='tesla')

# 局部变量
# 函数外定义的变量是全局变量
school ='oldboy edu.'

def change_name(name):
    global school
    school = 'Mage Linux'
    print("before change", name,school)
    name = 'Alex li'  # 这个函数就是这个变量的作用域
    print("after change", name)
name='alex'
change_name(name)
print(name)
print("school:", school)


def change_name():
    golbal name      # 不要这么写程序
    name = 'alex'
change_name()
print(name)

school ='oldboy edu.'
names = ['Alex',"Jack","Rain"]
names_tuple = (1,2,3,4)
def change_name():
    names[0]="金角大王"
    print("inside func", names)
    print(names)
change_name()
print(names)

# 递归:一个函数在内部调用自己,就叫递归
# 1.必须有一个明确的结束条件
# 2.每次进入更深一层时,问题规模相比上一次递归应有所减少
# 3.递归效率不高
def calc(n):
    print(n)
    return calc(n+1)
calc(0)

def calc(n):
    print(n)
    if int(n/2) > 0:
        return calc(int(n/2))
    print("-->", n)
calc(10)


# 高阶函数:一个函数可以接收另一个函数作为参数。
def add(a,b,f):
    return f(a)+f(b)
res = add(3, -6, abs)
print(res)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值