DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 7: Positional-Only, Keyword-Only Arguments and Return Statement

1. Positional-Only Arguments (/)

In Python, / is used as a positional-only argument separator.

It means that the parameters written before / must be passed using their position. We cannot pass them using parameter names (keyword arguments).

Example:

def calculate(a, b, /):
    print(a + b)

calculate(10, 20)  # 30
calculate(a=10, b=20)  # TypeError
Enter fullscreen mode Exit fullscreen mode

TypeError: calculate() got some positional-only arguments passed as keyword arguments

Here, a and b must be passed as positional arguments.

2. Keyword-Only Arguments (*)

In Python, * can be used as a keyword-only argument separator.

It means that the parameters written after * must be passed using their parameter names.

Example:

def calculate(a, *, b):
    print(a + b)

calculate(a=10, b=20)  # 30
calculate(10, b=20)    # 30
calculate(10, 20)      # Error
Enter fullscreen mode Exit fullscreen mode

TypeError: calculate() takes 1 positional argument but 2 were given

Here:

  • a can be passed as either a positional or keyword argument.
  • b must be passed as a keyword argument.

Difference Between / and *

Symbol Meaning
/ Parameters before it are positional-only
* Parameters after it are keyword-only

Remember:

  • / separates positional-only parameters.
  • * separates keyword-only parameters.

Return Statement in Python

The return statement is used to send a value from a function back to the place where the function was called.

Example:

def play():
    teamA = 300
    teamB = 290

    if teamA > teamB:
        return "Winner Trophy"
    else:
        return "Runner Trophy"

hand = play()
print(hand)
Enter fullscreen mode Exit fullscreen mode

Output:

Winner Trophy
Enter fullscreen mode Exit fullscreen mode

Top comments (0)