Python 简明教程

Python - Positional Arguments

Positional Arguments

在定义 function 时在括号中声明的 list of variables 是形式参数。这些参数也称为位置参数。可以使用任意数量的形式参数定义一个函数。

The list of variables declared in the parentheses at the time of defining a function are the formal arguments. And, these arguments are also known as positional arguments. A function may be defined with any number of formal arguments.

在调用函数时:

While calling a function −

  1. All the arguments are required.

  2. The number of actual arguments must be equal to the number of formal arguments.

  3. They Pick up values in the order of definition.

  4. The type of arguments must match.

  5. Names of formal and actual arguments need not be same.

Positional Arguments Examples

让我们讨论位置参数的一些示例:

Let’s discuss some examples of Positional arguments −

Example 1

以下示例显示了位置参数的用法。

The following example shows the use of positional argument.

def add(x,y):
   z = x+y
   print ("x={} y={} x+y={}".format(x,y,z))
a = 10
b = 20
add(a, b)

它将生成如下输出:

It will produce the following output −

x=10 y=20 x+y=30

这里,add() 函数有两个形式参数,它们都是 numeric 。当将整数 10 和 20 传递给它时。变量“a”获取 10,而“b”获取 20,以声明的顺序。add() 函数显示加法。

Here, the add() function has two formal arguments, both are numeric. When integers 10 and 20 passed to it. The variable "a" takes 10 and "b" takes 20, in the order of declaration. The add() function displays the addition.

Example 2

当参数数量不匹配时,Python 也会引发错误。如果您只提供一个参数并检查结果,您会看到一个错误。

Python also raises error when the number of arguments don’t match. If you give only one argument and check the result you can see an error.

def add(x,y):
   z=x+y
   print (z)
a=10;
add(a)

生成的错误将如下所示:

The error generated will be as shown below −

TypeError: add() missing 1 required positional argument: 'y'

Example 3

类似地,如果您传递多于形式参数的数量,将生成一个指出相同错误的错误:

Similarly, if you pass more than the number of formal arguments an error will be generated stating the same −

def add(x,y):
   z=x+y
   print ("x={} y={} x+y={}".format(x,y,z))
add(10, 20, 30)

输出如下:

Following is the output −

TypeError: add() takes 2 positional arguments but 3 were given

Example 4

相应的实际参数和形式的参数的 Data type 必须匹配。将 a 更改为字符串值并查看结果。

Data type of corresponding actual and formal arguments must match. Change a to a string value and see the result.

def add(x,y):
   z=x+y
   print (z)
a="Hello"
b=20
add(a,b)

它将产生以下错误:

It will produce the following error −

z=x+y
     ~^~
TypeError: can only concatenate str (not "int") to str

Difference between Positional and Keyword argument

下表解释了位置参数和关键字参数之间的区别:

The below table explains the difference between positional and keyword argument −