python学习之路day03

本节内容

1. 函数基本语法及特性

2. 参数与局部变量

3. 返回值

嵌套函数

4.递归

5.匿名函数

6.函数式编程介绍

7.高阶函数

8.内置函数

1. 集合

主要作用: 

  1. 去重
  2. 关系测试, 交集\差集\并集\(对称)差集:&、-、|、^
list_1=set([1,3,5,6,7,9])
list_2=set([0,2,6,88,9,])

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

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

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.pop()
print(list_1)

list_1.update([111,222,333])
print(list_1)
2.文件操作
2.1文件读写
#data=open("yesterday",encoding="utf-8").read()

# f=open("yesterday",encoding="utf-8")
# data=f.read()
# data2=f.read()
# print(data)
# print("-----data2--------",data2)

'''f=open("yesterday","r",encoding="utf-8") #r:读(read);w:写(write);a:追加(append);r+:读写;w+:写读;a+:追加写;rb:e二进制
# f.write("\n我爱北京天安门\n")
# f.write("\n when i was young,i would listen to the redio\n")
# f.close()

# for i in range(5):
# print(f.readline())
print(f.tell())
print(f.readline().strip())
print(f.readline().strip())
print(f.readline().strip())
print(f.tell())
f.seek(10)
print(f.readline().strip())
print(f.encoding)
print(f.fileno())
print(f.flush())
print(f.buffer)
'''

'''f=open("yesterday","a",encoding="utf-8")
f.seek(20)
f.truncate(20)
'''
'''f=open("yesterday","r+",encoding="utf-8") #读写(r+)
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.write("========diao======")
print(f.readline())
'''
'''f=open("yesterday","w+",encoding="utf-8") #写读(w+)
f.write("---diao----1\n")
f.write("---diao----2\n")
f.write("---diao----3\n")
print(f.tell())
f.seek(10)

f.write("should bea at the beging of the secound line ")
print(f.readline())
'''
f=open("yesterday","wb") #文件句柄 二进制文件
# print(f.readline())
# print(f.readline())
# print(f.readline())
f.write("hello binary\n".encode())
f.close()
2.2文件内容修改

f=open("yesterday","r",encoding="utf-8")
f_new=open("yesterday3","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语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:

3.字符编码与转码

需知:

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

编码之间转换

#-*-coding:gbk-*-
import sys
print(sys.getdefaultencoding())

s="你好,世界"

print(s.encode("gbk"))
print(s.encode("utf-8"))
print(s.encode("utf-8").decode("utf-8").encode("gb2312"))
4.函数与函数式编程
4.1编程方法:
1.面向对象:华山派--》类----》class
2.面向过程:少林派--》过程----》def
3.函数式编程:逍遥派--》函数----》def
4.2python中函数定义的方法:
def text(x):
"the function defi
ntions...."
     x+=1
return x
4.3为什么要使用函数
1.代码重复利用
2.保持数据的一致性
3.
使程序变的可扩展
4.使程序变得可维护
import sys,time

def logger():
time_formate="%Y-%m-%d %X"
time_current=time.strftime(time_formate)
with open("a.txt","a+") as f:
f.write("%s end action\n"%time_current)
def test1():
print("in the test1")
logger()
def test2():
print("in the test2")
logger()
def test3():
print("in the test3")
logger()
test1()
test2()
test3()
4.4函数返回值
def test1():
print("in the test1")
def test2():
print("in the test2")
return 0
def test3():
print("in the test3")
return 1,"hello world",["alex","fengjie"],{"name":"alex"}
x=test1()
y=test2()
z=test3()
print(x)
print(y)
print(z)
总结:返回值=0,返回None
返回值=1,返回object
返回值>1,返回tuple
4.5参数:形参和实参
1、形参与实参的定义和二者区别
形参:形式参数,不是时间存在,是虚拟变量,在定义函数的时候用形参,目的咋函数调用的时,接收时间参数的值(类型与实参一一对应)
实参:实际参数,调用函数时,传给形参,不能形参传给实参
区别:形参是虚拟的,不占内存空间,形参变量只要在被调用时才分配内存单元;实参是一个变量,占用内存空间,数据传送单向,实参传给形参,不能形参传给实参
2、位置参数和关键字(标准调用:形参与实参位置一一对应;关键字调用:位置无需固定)
def test(x,y,z):
print(x)
print(y)
print(z)
test(1,2,6)
3、默认参数:调用函数的时候,默认参数非必传递
4、参数组:*args,**kwargs 位置放在最后面
# def test(x,y,z):
# print(x)
# print(y)
# print(z)
# test(1,2,6)
def test1(name,*args):
print(name)
print(args)
test1("alex",(1,2,3,4,5))

def test2(name,age=18,*args):
print(name)
print(age)
print(args)
test2("Jack",23,[1,2,3,4,5,6,7])

def test3(name,age=18,*args,**kwargs):
print(name)
print(age)
print(args)
print(kwargs)
test3("rose",25,(1,3,5,7,9),sex="M",hobby="baskeball and tesla")
5.局部变量和全局变量:只在函数中失效
      在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
     全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
     当全局变量与局部变量同名时:
     在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
5.1局部变量
school="oldboy Edu."
def change_name(name,school):
print("before name",name,school)
school = "Mage linux"
name="Jack"
print("after name", name)
name="alex"
change_name(name,school)

print(name)
5.2全局变量
school="oldboy Edu."
def change_name(name):
global school
school = "Mage linux"
print("before name",name,school)
name="Jack"
print("after name", name,school)
name="alex"
change_name(name)
print(school)
print(name)
6.递归
6.1定义:在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
6.2递归的特性:

     1. 必须有一个明确的结束条件

     2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

     3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

def cal(n):
print(n)
if int(n/2)>0:
return cal(int(n/2))
print("--->",n)
cal(10)
7.函数式编程
定义:函数式编程中的函数这个术语不是指计算机中的函数(实际上是Subroutine),而是指数学中的函数,即自变量的映射。也就是说一个函数的值仅决定于函数参数的值,不依赖其他状态。比如sqrt(x)函数计算x的平方根,只要x不变,不论什么时候调用,调用几次,值都是不变的。
8.高阶函数
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

def add(a,b,f):
return f(a)+f(b)
res=add(3,-9,abs)
print(res)
9.作业
程序1: 实现简单的shell sed替换功能
程序2:修改haproxy配置文件 
需求:
1、查
    输入:www.oldboy.org
    获取当前backend下的所有记录

2、新建
    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

3、删除
    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }
原配置文件:
global       
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend www.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000




 

猜你喜欢

转载自www.cnblogs.com/0818and0119/p/9940930.html