Python Function and Recursion
Python Function and Recursion
Python Functions
By default, a function must be called with the correct number of arguments. Meaning that
if your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
If you try to call the function with 1 or 3 arguments, you will get an error:
Number of Arguments
Example
This function expects 2 arguments, but gets only 1:
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access
the items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
Example:
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
• If you do not know how many keyword arguments that will be passed
into your function, add two asterisk: ** before the parameter name in
the function definition.
• This way the function will receive a dictionary of arguments, and can access
the items accordingly:
Example
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Return Value
Function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.
Recursion