• Python函数


    1、函数定义与调用

    # 定义函数与调用
    def hello():
        print('hello world')
    
    hello()
    
    def area(width, height):
        return width * height
    
    print('area is:', area(4, 5))

    2、变量传递

    # 变量传递
    def test_int(a):
        a += 1
        print('a + 1 =', a)
    
    tmp = 1
    test_int(tmp)
    print('tmp =', tmp)
    
    lst = [1, 2, 3, 4, 5]
    def test_list(l):
        l[0] += 1
        print('l[0] + 1 =', l[0])
    
    test_list(lst)
    print(lst)

    3、参数的使用

    # 参数的使用:必须参数、关键字参数、默认参数、不定长参数
    # 1、必须参数
    # 必需参数须以正确的顺序传入函数,调用时的数量必须和声明时的一样。
    def test_args01(name, age, height):
        print('姓名:', name, end='    ')
        print('年龄:', age, end='    ')
        print('身高:', height)
    
    test_args01('Tom', 18, 180)
    test_args01(18, 'Tom', 180)
    
    # 2、关键字参数
    # 关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。
    # 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
    # 多个参数时,不能只有部分参数使用关键字参数。
    test_args01(age=18, name='Tom', height=180)
    
    
    # 3、默认参数
    # 定义函数时,指定的参数的默认值,在使用函数时,如果不给该参数传值,则使用默认值。
    # 多个参数时,从第一个使用默认参数的参数开始,之后的参数必须都要使用默认参数。
    def test_args02(name, age=18, height=180):
        print('姓名:', name, end='    ')
        print('年龄:', age, end='    ')
        print('身高:', height)
    
    test_args02('Tom')
    
    # 4、不定长参数
    # 使用*号,参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。
    def test_args03(arg1, *var_tuple):
        print(arg1, end=' ')
        print(var_tuple)
    
    test_args03(1)
    test_args03(1, 2, 3, 4, 5)
    
    # 使用**号,参数会以字典(dictionary)的形式导入,存放所有未命名的变量参数。
    def test_args04(arg1, **var_dict):
        print(arg1, end=' ')
        print(var_dict)
    
    test_args04(1, a=2, b=3, c=4)
    
    # *号的特殊使用方式,使用*号作为参数时,*号之后的参数必须使用关键字传入,*号并不占用参数数量。
    def test_args05(a, b, *, c, d):
        print(a, b, c, d)
    test_args05(5, 6, c = 7, d = 8)

    4、创建匿名函数

    # 使用lambda创建匿名函数
    
    summation = lambda a, b: a + b
    
    print(summation(1, 2))
  • 相关阅读:
    使用javaDate类代数据仓库维度表
    Hermes和开源Solr、ElasticSearch 不同
    MapReduce 异常 LongWritable cannot be cast to Text
    吐槽CSDN编辑
    Codeforces 452A Eevee
    看不清楚未来,请做好如今
    JDBC数据库连接
    mixpanel实验教程(2)
    使用jquery+一般处理程序异步载入信息
    Eclipse中的Maven项目报Unbound classpath variable错误
  • 原文地址:https://www.cnblogs.com/wbz-blogs/p/12089086.html
Copyright © 2020-2023  润新知