Play with Function Arguments in Python
In this article, I will be writing about 4 different function arguments.
- Required Arguments
- Keyword Arguments
- Default Arguments
- Variable-length arguments
- Required Arguments
If the argument is passed when defining the function, then values must be passed when calling the function. Otherwise, It will throw an error. Let’s understand with simple example.
We have passed an argument called ‘name’. However, when we call the function, value for the argument is not passed. so it it shows the error as “required positional argument”.
In the above image, the value has been passed when the function is called. It prints the passed value.
2. Keyword Arguments
The value of the argument will be assigned to the argument when calling the function. Let say, I want to print the name and age of the person. The name and age can be assigned in the function call.
The value for the name and age arguments have been given. But not in order. It is not compulsory to give values in the order of how it is passed. In the above example, Arguments passed as name and age, but While calling the function, it is not given in the order. We must make sure that the name of the arguments are same as that of the passed arguments. otherwise, it will throw an error.
The name of the argument is changed and it throws an error.
3. Default Arguments
The value can be assigned as default when we define the function.
The value of the name argument has already given while defining the function. So the values for the rest of the argument(s) can alone be passed while calling the function. In the above example, value for the age argument is alone passed during the function call.
NOTE: If we are going to pass more than one argument, if one of the arguments is going to be as Default argument, then it must be placed at the last. otherwise it will show an error. Look at the below example.
The default argument “name” has been initialized as 1st argument. It throws an error as “Non-default argument follows default argument”.
4. Variable-Length Argument
The values which are given in the function call must be equal to the arguments passed. In the below example, 2 arguments passed but 4 values have been given while calling the function and it throws an error.
The number of values are equal to the number of arguments passed. Hence, No error. It shows the output in the above snippet.
I hope, You enjoyed reading. Follow me for more interesting contents. Just take a look at my GitHub. Do you want full coding for this article? click here.
If you like this article, then please give a clap.