In this article, we will talk about what we call a reusable piece of code called functions.Functions are central to any programming language. Python makes it very easy to define and use functions.
Python functions are more powerful than their
C++ counterparts in the sense that it allows
keyword arguments and can also be passed as arguments to another function.
Like other articles in Python for Developers series, this article is based on examples with required explanations whenever required.
Minimal Python function
A minimal is defined using a
def keyword followed by a
function-name and a parenthesis
Points to ponder about functions are:
- Defined using
- There is no need to specify return type
- If a function returns nothing it returns
- There is no need to provide types of argument of functions
- Python functions accept default arguments
- Arguments can be passed using
keywordargument as well
Basic Function Calling
A function can be called using name of the function followed by arguments in parenthesis.
There are three ways to call a function:
- All positional arguments
- All keyword arguments (order does not matter)
- Positional arguments followed by keyword arguments (order is important)
Positional argument must be placed before keyword arguments.
Parameters of a function which has some default value (i.e. if no value is passed while they are called, the default value is used) must be placed at the end of list of arguments of function definitions.
If a function returns a value, the same can be catched in a variable. However, if no return statement is explicitly written by the programmer, it is said to return
A function in python can return any object/variable - integer, float, strings, list, list of list, tuple, set, dictionary, list of dictionary, function reference.
Don't worry about what
five() returns, we will talk about it later. For now, it is sufficient to know that a function can be defined inside another function and be returned.
Any number of positional and keyword arguments
In Python, it is possible to write any function that can take any number of positional arguments followed by any number of keyword arguments.
The traditional name that catches all the positional argument in function definition is called
arguments and the variable which catches all keyword argument is named
Without going too much into the details of it, just remember that such a function has
(*args, **kwargs) as arguments in its definition.
In the example shown below, we will just print all the passed arguments to the function.
In this article, we talked about functions which are fundamental to any programming language. We talked about how functions in Python are powerful and take positional and keyword arguments. We also discussed how we can supply default values to arguments in function definitions.