CodesCompiler
🔍
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact 🚀 Get Started Free

PYTHON - Positional Arguments

Python - Positional Arguments

Positional Arguments

Thelistofvariablesdeclared in the parentheses at the time of defining afunctionare theformal arguments. And, these arguments are also known aspositional arguments. A function may be defined with any number of formal arguments.

While calling a function −

  • All the arguments are required.
  • The number of actual arguments must be equal to the number of formal arguments.
  • They Pick up values in the order of definition.
  • The type of arguments must match.
  • 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.

PYTHON CODE
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 −

PYTHON CODE
x=10 y=20 x+y=30

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

Example 2

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.

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

The error generated will be as shown below −

PYTHON CODE
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 −

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

Following is the output −

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

Example 4

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

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

It will produce the following error −

PYTHON CODE
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 −

Positional ArgumentKeyword Argument
Only the names of arguments are used to pass data to the given function.Keyword arguments are passed to a function in name=value form.
Arguments are passed in the order defined in function declaration.While passing arguments, their order can be changed.
Syntax:function(param1, param2,…)Syntax:function(param1 = value1,…)