Python开发【第三篇】:Python函数

时间:2023-01-24 07:39:38

set

    无序,不重复,可嵌套。

函数

    创建函数:

    1、def关键字,创建函数

    2、函数名

    3、()

    4、函数体

    5、返回值

发邮件函数

  1. def sendmail():
  2.     import smtplib
  3.     from email.mime.text import MIMEText
  4.     from email.utils import formataddr
  5.     #三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
  6.     msg = MIMEText('邮件内容','plain','utf-8')
  7.     msg['From'] = formataddr(["发件人名称",'发件人邮箱'])
  8.     msg['To'] = formataddr(["哈哈",'收件人邮箱'])
  9.     msg['Subject'] = "邮件主题"
  10.   
  11.     server = smtplib.SMTP("smtp地址",端口)
  12.     #需要在开启SMTP,否则发送失败
  13.     server.login("发件人邮箱","密码")
  14.     server.sendmail('发件人邮箱',['收件人邮箱'],msg.as_string())
  15.     server.quit()
  16. sendmail()

函数中的return

  1. def f1():
  2.     print(123)
  3.     #在函数中,一旦执行return,函数执行过程立即终止
  4.     return "111"
  5.     print(456)
  6.   
  7. r = f1()
  8. print(r)

函数的默认返回值None

  1. def f2():
  2.     print(123)
  3.   
  4. r = f2()
  5. print(r)

普通参数

  1. #形参【形式参数】:xx
  2. def sendmail(xx,content):
  3.     import smtplib
  4.     from email.mime.text import MIMEText
  5.     from email.utils import formataddr
  6.     #捕获异常
  7.     try:
  8.         msg = MIMEText(content,'plain','utf-8')
  9.         msg['From'] = formataddr(["Golden",'发件人地址'])
  10.         msg['To'] = formataddr(["哈哈",'收件人地址'])
  11.         msg['Subject'] = "主题"
  12.   
  13.         server = smtplib.SMTP("smtp.126.com",25)
  14.         server.login('发件人地址','密码')
  15.         server.sendmail('发件人地址',[xx],msg.as_string())
  16.         server.quit()
  17.     except:
  18.         #发送失败
  19.         return False
  20.     else:
  21.         #发送成功
  22.         return True
  23.   
  24. #实际参数:收件人1\收件人2
  25. # ret = sendmail("收件人1")
  26. # ret = sendmail("收件人2")
  27.   
  28. while True:
  29.     em = input("请输入收件人邮箱地址:")
  30.     result = sendmail(em,"你好")
  31.     if result == True:
  32.         print("发送成功")
  33.     else:
  34.         print("发送失败")

默认参数

  1. def send(xx,content,hh="ok"):
  2.     print(xx,content,hh)
  3.     print("发送邮件成功:",xx,content)
  4.     return True
  5.   
  6. send("hahaha",'hello')
  7. send("hahaha",'hello','bbbb')

注意:如果需要给某个参数指定默认值,该参数必须放在参数列表的最后。

指定参数

  1. def send(xx,content):
  2.     print(xx,content)
  3.     return True
  4.   
  5. send("hahaha","hello")
  6. send(content="hahaha",xx="hello")

动态参数:*

  1. def f1(*args):
  2.     print(args,type(args))
  3.   
  4. f1(11,22,33,"haha","hello")
  5.   
  6. li = [12,23,33,"hahaha","hi"]
  7. f1(li)
  8. f1(*li)

注意:*默认将传入的参数全部放置在元组中,f1(*li)。

动态参数:字典(**)

  1. def f1(**args):
  2.     print(args,type(args))
  3.   
  4. f1(n1="alex",kk=18)
  5. dic = {'k1':'v1','k2':'v2'}
  6. f1(**dic)

注意:**默认将传入的参数全部放置在字典中,f1(**dic)。

万能参数

  1. def f1(*args,**kwargs):
  2.     print(args)
  3.     print(kwargs)
  4.   
  5. f1(11,22,33,44,k1='v1',k2='v2')

注意:*args,**kwargs顺序不能改变。

动态参数实现format功能

  1. s = "i am {0},age {1}".format("alex",18)
  2. print(s)
  3.   
  4. s1 = "i am {0},age {1}".format(*["alex",19])
  5. print(s1)
  6.   
  7. s2 = "i am {name},age {age}".format(age=20,name='alex')
  8. print(s2)
  9.   
  10. dic ={'name':'alex','age':21}
  11. s3 = "i am {name},age {age}".format(**dic)
  12. print(s3)

猜一猜输出

  1. def f1(a1,a2):
  2.     print('+')
  3.     return a1 + a2
  4.   
  5. def f1(a1,a2):
  6.     print('*')
  7.     return a1 * a2
  8.   
  9. ret = f1(8,8)
  10. print(ret)

  

  1. def f1(a1):
  2.     a1.append(999)
  3.   
  4. li = [11,22,33,44]
  5. f1(li)
  6.   
  7. print(li)

注意:函数参数传递的是引用。

全局变量

  1. NAME = "alex"
  2. AGE = 22
  3.   
  4. def f1():
  5.     num = 18
  6.     NAME = "haha"
  7.     #修改全局变量:age
  8.     global AGE
  9.     AGE = 25
  10.     print(num,AGE,NAME)
  11.   
  12. def f2():
  13.     num = 19
  14.     print(num,AGE,NAME)
  15.   
  16. f1()
  17. f2()

注意:全局变量重新赋值需要用global,对于列表或字典,可修改,不可重新赋值。定义全局变量全部大写。

函数实现登录与注册

  1. def login(username,password):
  2.     """
  3.     用于用户登录
  4.     :param username: 用户输入的用户名
  5.     :param password: 用户输入的密码
  6.     :return:True,登录成功;False,登录失败
  7.     """
  8.     f = open("db",'r')
  9.     #逐行读取
  10.     for line in f:
  11.         #用"|"进行分割
  12.         line_list = line.strip().split("|")
  13.         #匹配是否正确
  14.         if line_list[0] == username and line_list[1] == password:
  15.             return True
  16.     return False
  17.   
  18.   
  19. def register(username,password):
  20.     """
  21.     用户注册
  22.     :param username:用户名
  23.     :param password:密码
  24.     :return:默认返回None
  25.     """
  26.   
  27.     f = open("db",'a')
  28.     temp = "\n"+username + "|" + password
  29.     f.write(temp)
  30.     f.close()
  31.   
  32.   
  33. def main():
  34.     t = input("1:登录;2:注册")
  35.     if t == "1":
  36.         user = input("请输入用户名:")
  37.         pwd = input("请输入密码:")
  38.         r = login(user,pwd)
  39.         if r:
  40.             print("登录成功")
  41.         else:
  42.             print("登录失败")
  43.     elif t == "2":
  44.         user = input("请输入用户名:")
  45.         pwd = input("请输入密码:")
  46.         register(user,pwd)
  47.   
  48. main()

三元运算(三目运算)

  1. if 1 == 1:
  2.     name = "alex"
  3. else:
  4.     name = "golden"
  5.   
  6. #上面代码等价于
  7. name = "alex" if 1 == 1 else "golden"

lambda表达式

  1. def f1(a1):
  2.     return a1 + 100
  3.   
  4. #等价上面的代码
  5. f2 = lambda a1:a1 + 100
  6.   
  7. ret = f1(10)
  8. print(ret)
  9.   
  10. r2 = f2(9)
  11. print(r2)

内置函数

  1. #abs():取绝对值
  2. n = abs(-1)
  3. print (n)
  4.   
  5. #all():所有为真,才为真
  6. #any():任何一个为真,就是真
  7. n = all([1,2,3,4,[]])
  8. print(n)
  9.   
  10. n2 = any([1,[],0,"",None])
  11. print(n2)
  12.   
  13. #ascii():自动执行对象的 _repr_方法
  14. class Foo:
  15.     def _repr_(self):
  16.         return "111"
  17. n = ascii(Foo())
  18. print(n)
  19.   
  20. #bin():转二进制
  21. #oct():转八进制
  22. #hex():转十六进制
  23. print(bin(5))
  24. print(oct(9))
  25. print(hex(15))
  26.   
  27. #utf-8 一个汉字:三个字节
  28. #gbk 一个汉字:二个字节
  29.   
  30. #utf-8,一个字节八位,一个汉字三个字节
  31. s = "李杰"
  32. #字符串转换字节类型
  33. #bytes(需要转换的字符串,按照什么编码)
  34. n = bytes(s,encoding="utf-8")
  35. print(n)
  36. n = bytes(s,encoding="gbk")
  37. print(n)
  38.   
  39. #字节转化成字符串
  40. new_str = str(bytes("李杰",encoding="utf-8"),encoding="utf-8")
  41.   
  42. #1、打开文件
  43. #只读
  44. f = open('db','r')
  45. #只写,先清空源文件
  46. f = open('db','w')
  47. #文件存在,报错;不存在,创建并写内容
  48. f = open('db','x')
  49. #追加
  50. f = open('db','a')
  51. #2、操作文件
  52. #通过源码查看功能
  53. f.read()
  54. f.write()
  55.   
  56. #3、关闭文件
  57. f.close()
  58. with open('db') as f:
  59.     pass
  60.   
  61. f = open('db','r',encoding="GBK")
  62. #f = open('db','r',encoding="utf-8")
  63. data = f.read()
  64. print(data,type(data))
  65. f.close()
  66.   
  67. f = open("db","r+",encoding="utf-8")
  68. #如果打开模式无b,则read,按照字符读取
  69. data = f.read()
  70. #获取当前指针的位置(字节)
  71. print(f.tell())
  72. print(data)
  73. #移动当前指针到固定位置(字节)
  74. f.seek(1)
  75. #当前指针位置开始向后覆盖
  76. f.write("777")
  77. f.close()
  78.   
  79. f = open('db','rb')
  80. data = f.read()
  81. print(data,type(data))
  82.   
  83. f = open('db','ab')
  84. f.write(bytes("李杰",encoding="utf-8"))
  85. f.close()

flush()强刷:

  1. f = open("db",'a')
  2. f.write("123")
  3. #强制写入
  4. f.flush()
  5. input("adsdds")

readable()查看文件是否可读,返回True或False。

  1. f = open("db",'w')
  2. print(f.readable())

readline()仅读取一行数据,当文件特别大的时候不至于导致内存撑爆。

  1. f = open("db",'r')
  2. f.readline()
  3. f.readline()

truncate()截断,指针后面的数据清空

  1. f = open("db",'r+',encoding="utf-8")
  2. f.seek(3)
  3. f.truncate()
  4. f.close()

for循环打开的文件对象:

  1. f = open("db",'r')
  2. for line in f:
  3.     print(line)
  4. f.close()

将文件1的前十行写入文件2:

  1. with open('db1','r',encoding="utf-8") as f1,open('db2','w',encoding="utf-8") as f2:
  2.     times = 0
  3.     for line in f1:
  4.         times += 1
  5.         if times <= 10:
  6.             f2.write(line)
  7.         else:
  8.             break

将文件的某个字符串进行替换:

  1. with open('db1','r',encoding="utf-8") as f1,open("db2",'w',encoding="utf-8") as f2:
  2.     for line in f1:
  3.         new_str = line.replace("alex","st")
  4.         f2.write(new_str)

callable()查看函数是否可以被调用,返回True或False

  1. def f1():
  2.     pass
  3. f1()
  4.   
  5. f2 = 123
  6.   
  7. print(callable(f1))
  8. print(callable(f2))

chr()与ord()

  1. r = chr(65)
  2. n = ord("B")
  3. print(r,n)

产生1个随机大写字母:

  1. import random
  2. i = random.randrange(65,91)
  3. print(chr(i))

产生6个随机大写字母:

  1. import random
  2. li = []
  3. for i in range(6):
  4.     temp = random.randrange(65,91)
  5.     c = chr(temp)
  6.     li.append(c)
  7. result = "".join(li)
  8. print(result)

随机产生字母加数字:

  1. import random
  2. li = []
  3. for i in range(6):
  4.     r = random.randrange(0,6)
  5.     if r == 2 or r == 4:
  6.         num = random.randrange(0,10)
  7.         li.append(str(num))
  8.     else:
  9.         temp = random.randrange(65,91)
  10.         c = chr(temp)
  11.         li.append(c)
  12. result = "".join(li)
  13. print(result)

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

exec():执行python代码或字符串,无返回值

eval():执行表达式,有返回值

  1. s = "print(123)"
  2. #先编译,single、eval、exec
  3. #将字符串编译成python代码
  4. r = compile(s,"<string>","exec")
  5. print(r)
  6. #然后执行
  7. exec(r)
  8.   
  9. s = "8*8"
  10. ret = eval(s)
  11. print(ret)

dir()快速查看对象提供了哪些功能

  1. print(dir(dict))

divmod()计算商和余数

  1. r = divmod(97,10)
  2. print(r)

isinstance()判断对象是否是某个类的实例

  1. s = [11,22,33]
  2. r = isinstance(s,list)
  3. print(r)

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

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

将列表中大于22的数输出

  1. def f1(args):
  2.     result = []
  3.     for item in args:
  4.         if item > 22:
  5.             result.append(item)
  6.     return result
  7.   
  8. li = [11,22,33,44,55,66,78]
  9. ret = f1(li)
  10. print(ret)

filter()实现

  1. #filter(函数,可迭代的对象)
  2. def f2(a):
  3.     if a > 22:
  4.         return True
  5.   
  6. li = [11,22,33,44,55,66,78]
  7. #filter内部会循环第二个参数,将每个循环元素执行第一个函数,如果函数返回值是True,就添加到ret中
  8. ret = filter(f2,li)
  9. print(list(ret))

filter()+lambda实现

  1. li = [11,22,33,44,55,66,78]
  2. ret = filter(lambda a : a > 22,li)
  3. print(list(ret))

将列表中每个元素加100

  1. def f1(args):
  2.     result = []
  3.     for i in args:
  4.         result.append(i+100)
  5.     return result
  6.   
  7. li = [11,22,33,44,55,66,78]
  8. r = f1(li)
  9. print(list(r))

map()实现

  1. #map(函数,可迭代的对象)
  2. def f2(a):
  3.     return a + 100
  4.   
  5. li = [11,22,33,44,55,66,78]
  6. result = map(f2,li)
  7. print(list(result))

map()+lambda实现

  1. li = [11,22,33,44,55,66,78]
  2. result = map(lambda a : a + 100,li)
  3. print(list(result))

hash():生成hash值

  1. s = "hhhh"
  2. print(hash(s))

max():返回最大值

min():返回最小值

sum():返回和

pow():指数计算

  1. r = pow(2,10)
  2. print(r)

reverse():反转

round():四舍五入

sorted():排序

zip()

  1. #获取字符串 s = "alex_is_good_guy"
  2. l1 = ["alex",22,33,44,55]
  3. l2 = ["is",22,33,44,55]
  4. l3 = ["good",22,33,44,55]
  5. l4 = ["guy",22,33,44,55]
  6.   
  7. r = zip(l1,l2,l3,l4)
  8. temp = list(r)[0]
  9. ret = '_'.join(temp)
  10. print(ret)

装饰器

s1:

  1. def outer():
  2.     print("log")
  3.   
  4. def f1():
  5.     outer()
  6.     print("F1")
  7. def f2():
  8.     outer()
  9.     print("F2")
  10.   
  11. def f100():
  12.     outer()
  13.     print("F100")

b1:

  1. import s1
  2.   
  3. s2.f1()
  4. s2.f2()
  5. s2.f100()

装饰器实现

s1:

  1. def outer(func):
  2.     def inner():
  3.         print("log")
  4.         return func()
  5.     return inner
  6.   
  7. @outer
  8. def f1():
  9.     print("f1")
  10.   
  11. @outer
  12. def f2():
  13.     print("f2")
  14.   
  15. @outer
  16. def f100():
  17.     print("f100")

b1:

  1. import s1
  2.   
  3. s2.f1()
  4. s2.f2()
  5. s2.f100()

在调用函数前后输出内容

  1. def outer(func):
  2.     def inner():
  3.         print("log")
  4.         ret = func()
  5.         print("after")
  6.         return ret
  7.     return inner

求输出内容:

一:

  1. def f1():
  2.     print("123")
  3.   
  4. def f2(xxx):
  5.     xxx()
  6.   
  7. f2(f1)

二:

  1. def f1():
  2.     print("123")
  3.   
  4. def f1():
  5.     print("234")
  6.   
  7. f1()

传参一:

s1:

  1. def outer(func):
  2.     def inner(a):
  3.         print("log")
  4.         ret = func(a)
  5.         print("after")
  6.         return ret
  7.     return inner
  8.   
  9. @outer
  10. def f1(arg):
  11.     print(arg)
  12.     return "砍你"

b1:

  1. import s:1
  2.   
  3. s2.f1("hahahaha")

参数二:

s1:

  1. def outer(func):
  2.     def inner(*args,**kwargs):
  3.         print("log")
  4.         ret = func(*args,**kwargs)
  5.         print("after")
  6.         return ret
  7.     return inner
  8.   
  9. @outer
  10. def f1(arg):
  11.     print(arg)
  12.     return "砍你"
  13.   
  14. @outer
  15. def f2(arg1,arg2):
  16.     print(arg1,arg2)
  17.     print("f2")

b1:

  1. import s1
  2.   
  3. s2.f1("hahahaha")
  4.   
  5. s2.f2("111","222")

查询字符串是否包含子字符串:

  1. #in方法
  2. str = "hsaoiuo kkaoioweioew"
  3. if "iowe" in str:
  4.     print("存在")
  5. else:
  6.     print("不存在")
  7.   
  8. #fand方法
  9. str = "hsaoiuo kkaoioweioew"
  10. if str.find("iowe") == -1:
  11.     print("不存在")
  12. else:
  13.     print("存在")