6.函数

定义及使用

def 函数名(……):
    逻辑代码
# 函数只有被调用时才会执行
# 定义函数必须在调用函数之前

参数

  • 参数种类

    • 形参:定义函数时括号内的参数;
    • 实参:调用函数时传入的参数。
  • 传参方式

    • 位置传参

      def jiafa(a,b,c):
          print(a+b+c)
      jiafa(10,10,10)
      
    • 关键字传参

      def jiafa(a, b, c):
          print(a + b + c)
      jiafa(a=10, b=10, c=10)
      
    • 混合传参

      def jiafa(a, b, c):
          print(a + b + c)
      jiafa(10, b=10, c=10)
      

    应用场景:邮件发送

    def send_email(msg_to, send_info):
        import smtplib
        from email.mime.text import MIMEText
        from email.header import Header
        msg_from = '562979247@qq.com' # 发送方邮箱
        passwd = 'ajhrofcmbyjfbejc' # 授权码
        subject = "寄语" # 邮件主题
        msg = MIMEText(send_info) # 生成一个MIMEText对象(还有一些其它参数)
        msg['Subject'] = subject  # 放入邮件主题
        msg['From'] = msg_from  # 放入发件人
        s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 通过ssl方式发送,服务器地址,端口
        s.login(msg_from, passwd) # 登录到邮箱
        s.sendmail(msg_from, msg_to, msg.as_string())  # 发送邮件:发送方,收件方,要发送的消息
        print('成功')
    
    p = input("请输入要接收邮件的qq邮箱地址:")
    info = input("请输入要发送的内容:")
    send_email(p, info)
    
    • 默认值传参

      需求:调用一个函数,传入一个大字符串和一个小字符串,查找小字符串在大字符串中出现的次数,调用函数的时候,可以不传小字串,默认查找字符'a'在大字符串中的出现次数。

      def count_num(str_big, str_small="a"):
          l1 = list(str_big)
          num = l1.count(str_small)
          return num
      
      
      str1 = input("请输入一长串字符:")
      print(f"您输入的字符中b出现的次数是{count_num(str1, 'b')}")
      print(f"您输入的字符中a出现的次数是{count_num(str1)}")
      
    • 动态传参

      • *:将传入的参数封装为元组
      # 对传入的若干个参数进行求和
      def sum1(*args): # 默认取名为*args
            num = 0
            for i in args:
                num += i
            return num
      
        print(f"{sum1(1, 2, 3)}")
      
      • **:将传入的参数封装为字典
       def fun1(**kwargs):
          print(kwargs, type(kwargs))
      
      
      fun1(name='wy', height="185cm") # {'name': 'wy', 'height': '185cm'} <class 'dict'>
      

返回值

  • 特点

    • 函数内未写return时,默认结尾有一句return None;
    • 函数内运行到return则函数结束,后续代码并不会执行;
    • return与print的区别:return是直接返回一个值,而print是直接输出;
    • return返回的类型可以为任意类型。
  • 练习

    • 定义两个函数,第一个函数用户循环输入要累加的数值,函数内部将用户输入的值封装成一个列表返回;第二个函数将第一个函数返回的列表当作参数传入,返回列表中所有数据之和的结果。
# 函数1
def fun1():
    l1 = []
    while True:
        n = int(input("请输入数值:"))
        if n == -1:
            break
        l1.append(n)
    return l1


l2 = fun1()
print(l2)

# 函数2
def fun2(l):
    num = 0
    for i in l:
        num += i
    return num


print(fun2(l2))     
  • 进阶用法

    • 返回多个值:多个值用逗号分隔开,返回的结果为一个元组

      def fun1():
          return 11, 22, 33
      
      
      t1 = fun1()
      print(t1, type(t1))
      
    • 多个变量分别接收返回值

      def fun1():
          return 11, 22, 33
      
      
      a, b, c = fun1()
      print(a, b, c)
      

嵌套

  • 函数可以嵌套调用

    def fun1():
        print("hello world")
    
    
    def fun2():
        return 100
    
    
    def fun3(a1, b1):
        fun1()  # 调用fun1函数
        res1 = fun2()  # 调用fun2函数
        return a1 + b1 + res1
    
    
    res2 = fun3(11, 22)
    print(res2)
    
  • 函数内部定义的函数无法调用

练习:定义一个函数,传入一个文本路径,和一个关键词,将文本中包含关键词的那一句话拿出来放在一个列表中返回该列表

import os


def fun1(file_os, words):
    l1 = []
    if os.path.exists(file_os):
        f = open(file_os, mode='r', encoding='UTF-8')
        l2 = f.readlines()
        for i in l2:
            if words in i:
                l1.append(i.strip())
    else:
        print('该路径不存在')
    return l1


os1 = input("请输入文件路径:")
words1 = input("请输入文本:")
print(fun1(os1, words1))

# 优化写法
import os


def fun1(file_os, words):
    l1 = []
    if not os.path.exists(file_os):
        print('该路径不存在')
        return l1
    f = open(file_os, mode='r', encoding='UTF-8')
    l2 = f.readlines()
    for i in l2:
        if words in i:
            l1.append(i.strip())
    return l1


os1 = input("请输入文件路径:")
words1 = input("请输入文本:")
print(fun1(os1, words1))

作用域及变量

  • 函数内外分别形成一个作用域;
  • 全局变量为函数外定义的变量,局部变量为函数内定义的变量:函数内作用域可以使用全局变量,函数外作用域不能使用局部变量;
  • 局部变量前加global可以将自身转化为全局变量,但要注意必须先调用函数才能使用该变量。

函数名可作为变量

# 赋值操作
def fun1():
    print("好好学习,天天向上!")


fun2 = fun1
fun2()

# 存储到容器中,如列表
def fun1():
    print("鹅鹅鹅")


def fun2():
    print("曲项向天歌")


def fun3():
    print("白毛浮绿水")


def fun4():
    print("红掌拨清波")


fun_list = [fun1, fun2, fun3, fun4]
flag = input("请输入开始:")
for i in fun_list:
    i()
    
# 作为返回值
def fun1():
    print("鹅鹅鹅")


def fun2():
    print("曲项向天歌")


def fun3():
    print("白毛浮绿水")


def fun4():
    print("红掌拨清波")


fun_list = [fun1, fun2, fun3, fun4]


def show1():
    for i in fun_list:
        i()


def function1():
    return show1


res1 = function1()
res1()

# 作为参数
def fun1():
    print("鹅鹅鹅")


def fun2():
    print("曲项向天歌")


def fun3():
    print("白毛浮绿水")


def fun4():
    print("红掌拨清波")


fun_list = [fun1, fun2, fun3, fun4]


def show1():
    for i in fun_list:
        i()


def function1(s):
    s()


function1(show1)
posted @   WangYao_BigData  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示