zoukankan      html  css  js  c++  java
  • python---函数定义、调用、参数

    1、函数定义和调用

      下面def test部分的代码块是函数定义;test(2,3)则是函数调用

    def test(a,b):
        print(a)
        print(b)
    
    test(2,3)

    2、必填参数,即函数调用的时候,必须填入的参数。

    def test(a,b):
        print(a)
        print(b)
    
    test(2)
    报错信息:TypeError: test() missing 1 required positional argument: 'b'

    3、默认值参数,如下,调用的时候不填写则使用默认值,填写则使用填写的变量值;值得注意的是,定义函数的时候,默认参数要在必填参数的后面

    def test(a,b='111'):
        print(a)
        print(b)
    
    test(2)  //打印结果是2和111
    test(2,3)  //打印结果是2和3

    4、不定长参数

    def test(a,b='111',*args): //此处的args也可以用别的变量名代替
        print(a)
        print(b)
        print(args)
    
    test(2,3,4,5,6) //调用的时候按位置匹配,不定长参数的位置是可以不填的,不填的打印结果为()
    打印结果为:
        2
        3
        (4, 5, 6)  //此处是一个tuple,如果想取出里面的值,可以for arg in args:来取出里面的数值

    5、关键字参数

    def test(a,b='111',*c,**d):
        print(a)
        print(b)
        print(c)
        print(d)
    
    test(2,3,4,5,6,song='star',name='ta')  //调用的时候,可以不传,打印结果为{},如果想使用其值得话,可以for key,value in d.items():的方式
    打印结果为:
        2
        3
        (4, 5, 6)
        {'song': 'star', 'name': 'ta'} //为字典类型
  • 相关阅读:
    基于jQuery弹性展开收缩菜单插件gooey.js
    动态插入和移除
    匹配0-59 0-23 的正则表达式
    换行问题
    iOSBug -- The file “Info.plist” couldn’t be opened
    MarkDown语法
    Mac -- 右键添加pages文件
    iOS -- 使用蒲公英进行内测
    Mac使用技巧--如何给safari安装翻译插件
    iOS--优化
  • 原文地址:https://www.cnblogs.com/hzgq/p/11736850.html
Copyright © 2011-2022 走看看