Positional Arguments in Python allow arguments to be passed to a function implicitly based on the order in which they appear in the function argument list. When you define a Python function, you expect some values or arguments to be passed to the function. Let's define a function to understand this better.
def print_stats(name,age,type_batsman, avg_runs):
print(f"Name of cricketer is {name}.")
print(f"Age of {name} is {age} years.")
print(f"{name} is {type_batsman} handed bastsman.")
print(f"Career ODI Average for {name} is {avg_runs} runs.")
In this function, name, age , type_batsman , avg_runs are called positional arguments. The function expects the order to be maintained when you pass in parameters to this function. Let's call this function to see this.
print_stats("Sachin Tendulkar", 49, "right", 44.8)
Name of cricketer is Sachin Tendulkar.
Age of Sachin Tendulkar is 49 years.
Sachin Tendulkar is Right handed bastsman.
Career ODI Average for Sachin Tendulkar is 44.8 runs.
What would happen if you mess up the order when passing arguments to this function?
print_stats(49, "Sachin Tendulkar", 44.8, "Right")
Name of cricketer is 49.
Age of 49 is Sachin Tendulkar years.
49 is 44.8 handed bastsman.
Career ODI Average for 49 is Right runs.
Clearly, the results would not make sense. So, if you are passing parameters to a function accepting postional arguments , we must strictly maintain the order. What if we pass less parameters than what is expected by this function. Let's see.
print_stats("Sachin Tendulkar", 49,"Right")
TypeError Traceback (most recent call last)
ipython-input-12-247478ed6eaf in module
----> 1 print_stats("Sachin Tendulkar", 49,"Right")
TypeError: print_stats() missing 1 required positional argument: 'avg_runs'
The function expects avg_runs parameter to be passed but it does not receive it when the function call is made leading to a TypeError . Now let's see what happens if we supply more parameters than is expected.
print_stats("Sachin Tendulkar", 49,"Right" ,44.8, 56)
TypeError Traceback (most recent call last)
ipython-input-14-1900fa90b236 in module
----> 1 print_stats("Sachin Tendulkar", 49,"Right" ,44.8, 56)
TypeError: print_stats() takes 4 positional arguments but 5 were given
The function expected 4 positional arguments , but we supplied 5 parameters. It does not know what to do with the 5th parameter, so it throws a TypeError. Always double check before you pass parameters to a function accepting positional arguments. It can save you a lot of effort.
This concludes the discussion on Positional Arguments in Python . In the next post, we will take up Keyword Arguments in Python.
Comments
Post a Comment