Named Parameters in Python
If many parameters are passed to a function, the chance of making a mistake increases, since the values for the parameters we need can be mixed up.
To avoid such problems, Python has the ability to specify parameter names when calling a function. Let's see how this is done. Let's assume we have the following function:
def func(num1, num2):
return num1 + num2
You can simply call it:
res = func(5, 10)
print(res) # 15
And you can call parameters with names:
res = func(num1=5, num2=10)
print(res) # 15
Named parameters are very convenient because they can be swapped when calling a function:
res = func(num2=2, num1=5)
print(res) # 3
If several optional parameters are specified when declaring a function, they can also be named. In this case, you do not have to list the parameters in the order that you specified them when declaring them:
def func(num1, num2=1, num3=2):
return num1 + num2 + num3
res = func(num1=2, num3=6)
print(res) # 8
Given a function:
def func1(num1, num2, num3):
return (num1 + num2) * num3
Call it by passing values via named parameters.
Given a function:
def func1(text1, text2):
return text1 + ' ' + text2
Call it by passing the string 'hello' and your name via named parameters.