Python基础3之函数

本文详细介绍了Python中集合(set)的基本概念、创建方法及常用操作,包括添加、删除、交集、并集等,并通过实例演示了如何利用这些操作解决实际问题。

set

set集合,是一个无序且不重复的元素集合

  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5      
  6     Build an unordered collection of unique elements.
  7     """
  8     def add(self, *args, **kwargs): # real signature unknown
  9         """
 10         Add an element to a set,添加元素
 11          
 12         This has no effect if the element is already present.
 13         """
 14         pass
 15  
 16     def clear(self, *args, **kwargs): # real signature unknown
 17         """ Remove all elements from this set. 清除内容"""
 18         pass
 19  
 20     def copy(self, *args, **kwargs): # real signature unknown
 21         """ Return a shallow copy of a set. 浅拷贝  """
 22         pass
 23  
 24     def difference(self, *args, **kwargs): # real signature unknown
 25         """
 26         Return the difference of two or more sets as a new set. A中存在,B中不存在
 27          
 28         (i.e. all elements that are in this set but not the others.)
 29         """
 30         pass
 31  
 32     def difference_update(self, *args, **kwargs): # real signature unknown
 33         """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
 34         pass
 35  
 36     def discard(self, *args, **kwargs): # real signature unknown
 37         """
 38         Remove an element from a set if it is a member.
 39          
 40         If the element is not a member, do nothing. 移除指定元素,不存在不保错
 41         """
 42         pass
 43  
 44     def intersection(self, *args, **kwargs): # real signature unknown
 45         """
 46         Return the intersection of two sets as a new set. 交集
 47          
 48         (i.e. all elements that are in both sets.)
 49         """
 50         pass
 51  
 52     def intersection_update(self, *args, **kwargs): # real signature unknown
 53         """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
 54         pass
 55  
 56     def isdisjoint(self, *args, **kwargs): # real signature unknown
 57         """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
 58         pass
 59  
 60     def issubset(self, *args, **kwargs): # real signature unknown
 61         """ Report whether another set contains this set.  是否是子序列"""
 62         pass
 63  
 64     def issuperset(self, *args, **kwargs): # real signature unknown
 65         """ Report whether this set contains another set. 是否是父序列"""
 66         pass
 67  
 68     def pop(self, *args, **kwargs): # real signature unknown
 69         """
 70         Remove and return an arbitrary set element.
 71         Raises KeyError if the set is empty. 移除元素
 72         """
 73         pass
 74  
 75     def remove(self, *args, **kwargs): # real signature unknown
 76         """
 77         Remove an element from a set; it must be a member.
 78          
 79         If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
 80         """
 81         pass
 82  
 83     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 84         """
 85         Return the symmetric difference of two sets as a new set.  对称差集
 86          
 87         (i.e. all elements that are in exactly one of the sets.)
 88         """
 89         pass
 90  
 91     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
 92         """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
 93         pass
 94  
 95     def union(self, *args, **kwargs): # real signature unknown
 96         """
 97         Return the union of sets as a new set.  并集
 98          
 99         (i.e. all elements that are in either set.)
100         """
101         pass
102  
103     def update(self, *args, **kwargs): # real signature unknown
104         """ Update a set with the union of itself and others. 更新 """
105         pass
#创建
#se  = {"hong","123"}

#增加
#s = set()
#s.add(123)
#print(s)

#去除s1中存在s2中不存在
#s1 = {11,22,33}
#s2 = {22,33,44}
#s3 = s1.difference(s2)
#print(s3)

#移除
#s1 = {11,22,33}
#s1.discard(1111)存在不存在都不会出错
#s1.remove(11)只能移除存在的
#s1.pop()随机移除
#print(s1)

#交集
#s1 = {11,22,33}
#s2 = {44,22,33}
#s3 = s1.intersection(s2)
#print(s3)

#并集
#s1 = {11,22,33}
#s2 = {44,22,33}
#s3 = s1.union(s2)

小练习:模拟CMDB更新

# old_dict = {
#     "#1":8,
#     "#2":4,
#     "#4":2,
#
# }
# new_dict = {
#     "#1":4,
#     "#2":4,
#     "#3":2,
#
# }
# new_set = set(new_dict.keys())#字典转换成set集合
# old_set = set(old_dict.keys())
# remove_set = old_set.difference(new_set)#去除old中存在new中不存在
# add_set = new_set.difference(old_set)#添加new中存在old中不存在
# update_set = old_set.intersection(new_set)#更新old和new的交集
View Code

函数

  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”

定义和使用

def 函数名(参数):
       
    ...
    函数体
    ...
    返回值

函数的定义主要有如下要点:

  • def:表示函数的关键字
  • 函数名:函数的名称,日后根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
  • 参数:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据。

1、返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

def f1():
     print(123)
     #在函数中,一旦执行return,函数执行过程立即终止
     return '111'
     print(456)
a = f1()
print(a)
#输出
123
111
View Code

2、参数

函数的有三中不同的参数:

  • 普通参数
  • 默认参数
  • 动态参数

普通参数

def sendmail(receive,content):
     print("发送邮件成功",em,content)
     return True
 while True:
     em = input("输入邮箱:")
     result = sendmail(em,'sb')
     if result == True:
         print('发送成功')
     else:
         print('发送失败')
View Code

 

默认参数(只能写在参数列表最后)

def sendmail(receive,content,xx = 'ok'):
    print("发送邮件成功",receive,content,xx)
    return True
sendmail('ds','haha')
sendmail('ds','haha','fuck')
#输出
发送邮件成功 ds haha ok
发送邮件成功 ds haha fuck
View Code

 

动态参数

def f1(*args):#动态参数
     print(args)
f1(11,22,'hongpeng')
#输出(11, 22, 'hongpeng')
def f1(*args):
    print(args,type(args))
li = [11,22,'alex','hhhh']
f1(li,'12')
#输出([11, 22, 'alex', 'hhhh'], '12') <class 'tuple'>
f1(*li)#把li里的每一个元素都转换到元组里,其实for循环
#输出(11, 22, 'alex', 'hhhh') <class 'tuple'>
View Code

 

def f1(*args,**kwargs):
    print(args)
    print(kwargs)

f1(11,22,33,44,k1='v1',k2='v2')
#输出
(11, 22, 33, 44)
{'k2': 'v2', 'k1': 'v1'}
View Code

 

格式化输出(format)

s1 = "i am {0},age {1}".format("alex",18)
print(s1)

s2 = "i am {0},age {1}".format(*["alex",18])
print(s2)

dict = {"name":"alex","age":18}
s3 = "i am {name},age {age}".format(**dict)
print(s3)
#输出
i am alex,age 18
i am alex,age 18
i am alex,age 18
def f1(a,b):
    return a + b
def f1(a,b):
    return a * b
c  = f1(8,8)
print(c)
#输出64
#python解释器从上到下

 

函数的参数在传递的时候是引用

列表字典可以修改,不能重新赋值

def f1(a):
    a.append(999)

li=[11,22,33]
f1(li)
print(li)
#输出
[11,22,33,999]

 

全局变量

都是大写,这是潜规则哦!所有作用域都可读,优先读函数内部自己的变量。

NAME = 'hongpeng'
def f1():
    age = 18
    NAME = 'HONGPENG'
print(NAME,age)

def f2():
    age = 19
print(NAME,age)

f1()
f2()
#输出
HONGPENG 18
hongpeng 19

全局变量重新赋值(global)

NAME = 'hongpeng'
def f1():
    age = 18
global NAME
NAME = 'HONGPENG'
print(NAME,age)

def f2():
    age = 19
print(NAME,age)

f1()
f2()
#输出
HONGPENG 18
HONGPENG 19

3.函数完成登录注册(函数式编程中,注释很重要)

__author__ = 'hongpeng'
def login(username,password):
    """
    用户登录
    :param username:用户名
    :param password: 密码
    :return:返回True
    """
    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:返回True注册成功
    """
    f = open('db','a')
    tmp = '\n'+ username + '|'+ password
    f.write(tmp)
    f.close()
    return True

def main():
    choice = int(input('1:登录 2:注册'))
    if choice == 1:
        usr = input("please input your name...")
        pwd = input("please input your password...")
        r = login(usr,pwd)
        if r:
            print('登录成功')
        else:
            print('登录失败')
    elif choice == 2:
        usr = input("please input your name...")
        pwd = input("please input your password...")
        r = register(usr,pwd)
        if r:
            print("注册成功")
        else:
            print("注册失败")

main()
View Code

 

4.三元运算(本质就是if else的简写)

name = 'hongpeng' if 1==1 else 'haha'

 

如果条件成立,name = ‘hongpeng’,否则 name = 'haha'

5.lambda表达式(功能和定义函数一样)

def f1(a1):
    return a1 + 100
f2 = lambda a1:a1 + 100

r1 = f1(10)
r2 = f2(20)
print(r1)
print(r2)
#输出
110
120
View Code

文件操作

一、打开文件

文件句柄 = open('文件路径''模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

tell and seek

f = open('db','r+',encoding='utf-8')
#如果打开模式无b,则read,按照字符读取
data  = f.read(1)
f.seek(f.tell())
#tell当前指针所在的位置(字节) seek调整指针位置
f.write('888')
#d当前指针位置向后覆盖
f.close()

 练习:修改haproxy配置文件

__author__ = 'hongpeng'
def fetch(backend):#find
    res = []
    with open('ha','r',encoding='utf-8') as f:
        flag = False#标志位
        for line in f:
            if line.strip().startswith('backend') and line.strip() == 'backend '+ backend:
            #找到输入的backend那一行,标志位True
                flag = True
                continue#结束本次,寻找下一行
            if flag and line.strip().startswith('backend'):
            #定位到标志位,找到下一个backend,标识为False,结束
                flag = False
                break
            if flag and line.strip():
                #标志位True并且这一行存在
                res.append(line.strip())
    return res

def add(backend,record):
    #1、backend不存在
    #2、backend存在
    #   (1)record存在
    #   (2)record不存在
    record_list = fetch(backend)
    if not record_list: #record_list为空,backend不存在
        with open('ha','r',encoding='utf-8') as old,open('ha1','w',encoding='utf-8') as new:
            for line in old:
                new.write(line)
            new.write("\nbackend " + backend + '\n')
            new.write(" "*8 + record + '\n')
    else:
        #backend 存在,record c存在
        if record in record_list:
            pass
        else:
            #backend存在,record不存在
            record_list.append(record)
            with open('ha','r',encoding='utf-8') as old,open('ha1','w',encoding='utf-8') as new:
                flag = False
                for line in old:
                    if line.strip().startswith("backend") and line.strip()== "backend "+backend:
                        flag = True
                        new.write(line)
                        for new_line in record_list:
                            new.write(" "*8 + new_line + '\n')
                        continue


                    if flag and line.strip().startswith("backend"):
                        flag =  False
                        new.write(line)
                        continue
                    if line.strip() and not flag:
                        new.write(line)
#a = fetch("www.oldboy.org")
#print(a)
bk = 'www.oldboy.org'
re = 'server 10.3.7.9 10.3.7.9 weight 20 maxconn 300'

add(bk,re)
View Code

 haproxy配置文件

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
        server 100.1.7.99 100.1.7.99 weight 20 maxconn 3000

backend buy.oldboy.org
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
View Code

 函数里的一个坑

li = [11,22,33,44]
def f(arg):
    arg.append(55)
li = f(li)
print(li)

 尼玛,乍一看以为输出[11,22,33,44,55]

然而,执行一下输出None

why?

函数中如果不指定return,默认return None。

li = [11,22,33,44]
def f(arg):
    arg.append(55)
f(li)
print(li)

像上面输出就是[11,22,33,44,55]

 

内置函数

chr()

ord()

随机生成6位验证码(包换数字,大写字母,数字位置随机)

import random
number = []
for i in range(6):
    a = random.randrange(0,5)
    if a == 2 or a == 4:
        num = random.randrange(0,9)
        number.append(str(num))
    else:
        li = random.randrange(65,90)
        aln = chr(li)
        number.append(aln)
print("".join(number))
View Code

compile()  将字符串编译成python代码

eval()  执行表达式,获取结果

exec()  执行python代码,接收:代码或字符串

divmod()  商 取余

filter  函数返回True,将元素添加到结果中

li = [11,22,33,44]
res = filter(lambda a : a > 22,li)
print(list(res))
#输出[33, 44]

# def f2(a):
#     if a>22:
#         return True
# li = [11,22,33,44,55]
#filter内部,循环第二个参数
#result = []
#for item in 第二个参数:
#     r = 第一个参数(item)
#     if r:
#         result(item)
# return result

#ret = filter(f2,li)
#filter,循环第二个参数,让每个循环元素执行函数,如果函数返回True,表示函数合法
#print(list(ret))

 

map  将函数返回值添加到结果中

li = [1,22,33,44]
res = map(lambda a :a+100,li)
print(list(res))
#输出[101, 122, 133, 144]

 

转载于:https://www.cnblogs.com/hongpeng/p/5843732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值