Python函数参数选项(Function parameter options)

大多函数都会需要提供参数,每种语言都有他自己的方式给函数定义参数。Python函数参数定义更灵活方便,下面我们将讲述Python的函数参数定义。

1. 位置参数(Positional parmeters) 
位置参数必须以在被调用函数中定义的准确顺序来传递。
>>>def power(x, y):
...    return x - y

>>>power(3, 4)
-1
>>>power(4, 3)
1
从运行结果可以看出,调用函数时传递的参数顺序与函数定义时参数顺序是一一对应的。
>>>power(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow() takes exactly 2 arguments (1 given)


>>>power(3, 4, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow() takes exactly 2 arguments (3 given)
参数传少、传多,都会报错:函数需要num个参数(实际给了num1个)。所以参数个数也要匹配。这里会有另外一种情况不会受此限制,就是参数定义默认值,稍后会讲到。
位置参数:
1.以顺序进行匹配;
2.调用时参数个数也要匹配;

2. 关键字参数(Passing arguments by parameter name)

3. 可变的参数个数(Varlable numbers of arguments)

原文地址:https://www.cnblogs.com/hypo106/p/4169483.html