Function arguments in Python
In Python, Custom functions can take four different types of arguments. The argument types and their meanings, however, are pre-defined and can’t be changed. But a developer can, instead, follow these pre-defined rules to make their own custom functions. The following are the four types of arguments and their rules.
1. Default arguments:
Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Below is a typical syntax for default argument. Here, msg parameter has a default value Hello!.
Function definition
def defaultArg( name, msg = "Hello!"):
Function call
defaultArg( name)
2. Required arguments:
Required arguments are the mandatory arguments of a function. These argument values must be passed in correct number and order during function call. Below is a typical syntax for a required argument function.
Function definition
def requiredArg (str,num):
Function call
requiredArg ("Hello",12)
3. Keyword arguments:
Keyword arguments are relevant for Python function calls. The keywords are mentioned during the function call along with their corresponding values. These keywords are mapped with the function arguments so the function can easily identify the corresponding values even if the order is not maintained during the function call. The following is the syntax for keyword arguments.
Function definition
def keywordArg( name, role ):
Function call
keywordArg( name = "Tom", role = "Manager")
or
keywordArg( role = "Manager", name = "Tom")
4. Variable number of arguments:
This is very useful when we do not know the exact number of arguments that will be passed to a function. Or we can have a design where any number of arguments can be passed based on the requirement. Below is the syntax for this type of function call.
Function definition
def varlengthArgs(*varargs):
Function call
varlengthArgs(30,40,50,60)
Now that we have an idea about the different argument types in Python. Let’s check the steps to write a Custom function.
Writing Custom functions in Python:
These are the basic steps in writing Custom functions in Python. For additional functionalities, we need to incorporate more steps as needed.
Step 1: Declare the function with the keyword def followed by the function name.
Step 2: Write the arguments inside the opening and closing parentheses of the function, and end the declaration with a colon.
Step 3: Add the program statements to be executed.
Step 4: End the function with/without return statement.
The example below is a typical syntax for defining functions:
def userDefFunction (arg1, arg2, arg3 ...):
program statement1
program statement3
program statement3
....
return;