来源:python中国网 时间:2020-03-15

  python函数传参的时候一定要把默认参数写在最后,无论是定义还是调用,否则就会出错。看下面错误的例子:

  第1个是函数定义传参顺序错误,

# -*- coding: utf-8 -*-


def echo(name='老王',age):
    print(123)

echo()
File "D:/pyscript/py3script/ceshi.py", line 4
    def echo(name='老王',age):
            ^
SyntaxError: non-default argument follows default argument


  第2个是函数调用传参顺序错误,

# -*- coding: utf-8 -*-


def echo(age,name='老王'):
    print(age,name)

echo(name='小王',18)

  File "D:/pyscript/py3script/ceshi.py", line 7
    echo(name='小王',18)
                      ^
SyntaxError: positional argument follows keyword argument



  正确的用法是

# -*- coding: utf-8 -*-


def echo(age,name='老王'):
    print(age,name)

echo(18,name='小王')
18 小王