Argument Passing in Python
Contents
Passing Arguments and using the return keyword:
In this unit, we will be revising the two methods of argument passing. This portion has already been taught in the previous module. The only new addition to this part would be the use of return keyword. Use of return is an essential method of communicating with different functions and thus plays a vital role in the argument passing.
As you already know, argument passing is done in two ways:
- Required argument
- Keyword argument
Required Arguments:
It passes the parameter in their mentioned order of the calling function. It is also known as the conventional form of argument passing.
Consider this example:
def Mario(input, word_ct): print(input) print(word_ct) Mario("I love Mushrooms", 3) Mario("I need more coins!", 4)
Here we give the input string and number of words in it to the function. Note that the order is also kept intact as per the initial function definition.
Keyword Arguments:
Argument passing is done in any order. However, we need to assign the values of parameters during passing.
Consider this example:
def Mario(input, word_ct): print(input) print(word_ct) Mario(input="I love Mushrooms", word_ct=3) Mario(word_ct=4, input="I need more coins!")
Here we mention the parameter variables first. Then we assign the values into it. This nullifies the order in which we send the parameter.
NOTE: As long as the names match, the parameters can be sent in any order you wish. But make sure the parameter names are correct, else it would generate an error.
Default Arguments:
Another method exists which is the default argument passing. Default argument passing tells it is not compulsory to pass all parameters. But it has some pre-assigned values. Hence no error shows up during execution.
Consider this example:
def Mario(input, word_ct=3): print(input) print(word_ct) Mario("I love Mushrooms") Mario("I need more coins!", 4)
Note the first function call. It sends only input but no word count. However, this doesn’t show any error. The default word count will be printed automatically during execution.
The return keyword:
As the name suggests, the return keyword followed by an expression returns the value of that expression to the function from where it has been called. To understand return simply, consider it like a cricket ball. The ball (return) is thrown in the form of expression from a function. To catch the ball, there must be a person on the other side (the calling function) and thus it catches the ball. Hence in return keyword, a variable must be present at the other end, to receive what return returns. Else that would generate an error.
Run this example to understand how return works:
def sum(var1, var2): return var1 + var2 c = sum(10, 20) print("The sum is", c)