Positional only arguments in Python

This tutorial will give us a piece of extreme information about positional only arguments in Python.

Positional-only arguments in Python:

Definition: The arguments are specifying by the position only called Positional arguments.

Syntax:

def  fun(arg1,arg2,/,arg3,*,arg4,arg5)

Here, arg1 and arg2 are the positional-only arguments and arg3 is using as both positional and the keyword argument.

And arg4,arg5 are keyword-only arguments in Python.

How to use positional arguments:

We have to add ‘/’ after all arguments specified in the function definition.

Example:

def mul(x,y,/,mod=None):
    r=x*y
    if mod is not None:
        r+= mod
    return r
print(mul(3,2,2))
print(mul(3,2,mod=2))

Output:

8

8

Explanation: From the above example we are defining the positional arguments as x,y here mod is the keyword argument.

For mod, we can pass a direct value positionally or by using the keyword also as mod=2 or just as 2.

And after define the x,y we are putting the ‘/’ marker in the above example for making the x and y as positional arguments.

And the keyword-only arguments are specified by using the marker ‘*’.

Example for keyword-only arguments:

def mul(x,y,/,mod=None,*,a,b):
    r=x*y
    if mod is not None:
        r+= mod    
    return(r,a+b)
print(mul(3,2,2,a=5,b=5))

Output: 

(8,10)

Explanation:

From the above example after ‘*’ marker we are defining the arguments a,b called as keyword-only arguments.

We are passing the values to that a and b with the keyword and it is mandatory.

And remaining code is as usual as the above code.

And finally, get the values as (8,10) by applying some mathematical operations in that code.

Because of using the positional arguments there will be a chance to improve the language consistency.

Leave a Reply

Your email address will not be published. Required fields are marked *