zoukankan      html  css  js  c++  java
  • 自定义函数

    自定义函数的形式如下:
    def 函数名称(参数):
    函数体
    return 值
     
    函数的调用:
    函数名称(参数)
     
    难点在参数:
    1,位置参数,如:
    def  add(x,y):
    return x+y
    add(2,3)
    #两个参数的顺序必须一一对应, 少一个多一个都不行。
     
    2,关键字参数
    使用命名(关键字)来指定函数中的参数。

    def func(a, b=5, c=10):
        print('a is', a, 'and b is', b, 'and c is', c)

    func(3, 7)
    func(25, c=24)
    func(c=50, a=100)
    输出:

    a is 3 and b is 7 and c is 10
    a is 25 and b is 5 and c is 24
    a is 100 and b is 5 and c is 50

     
    3,默认参数,如:
    def add(x,y=10)
    return x+y

    >>> add(3)
    13
    >>> add(3,4)
    7

    注意:必选参数在前,默认参数在后
    默认参数为不可变对象
     
    3,可变参数,如:
    当不确定函数调用的时候会传递多少个参数(不传参也可以),可用包裹(packing)位置参数,或者包裹关键字参数,来进行参数传递,会显得非常方便。

    1、 包裹位置传递
    def fc(*args):
        print(arg)
    >>> fc(1,2,3)
    (1, 2, 3)

    注意:*表示解释器将args当成一个元组来对待,

    2、 包裹关键字传递
    def fd(**kwargs):
        print(kwargs)
    >>> fd(a=1,b=2,c=3)
    {'a': 1, 'b': 2, 'c': 3}

  • 相关阅读:
    matlab基础知识
    reverse number
    C++基础知识(一)
    ES6 let const学习
    [ZZ]一名IT从业者的英语口语能力成长路径
    使用windows Live Writer 以及office word 2013发布文章到博客园总结
    CString.format的用法
    Cstring 与 string 注意点
    卡尔曼滤波应用
    linux 重新挂载分区(教程)
  • 原文地址:https://www.cnblogs.com/blogzyq/p/13900229.html
Copyright © 2011-2022 走看看