How to define a function in python?
This article was published as a part of the Data Science Blogathon
A function is a reusable block of code that can perform a basic task. The function definition in python may be a bit different from the syntax used in languages like C, C++, or Java. The objective of this article is to provide the syntax for function definition in python.
The function definition starts with a def keyword followed by the function name and the arguments the function can take. These arguments are within parentheses and there can be any number of arguments including zero. When there is more than one argument, they are separated by a comma. Since python is a loosely typed language, (meaning we don’t assign a data type to a variable when declaration) we shouldn’t include the data types for the arguments. The function definition statement is terminated by a colon. In python, we define a function as follows:
def function_name(arg1,arg2,arg3,...): """ function logic goes here. """ return value1, value2, value3,...
Below is a simple function,
def greet(): print("hello world")
This is a basic function that prints “hello world” to the console.
If we look at the function definition closely, we see that there are no curly brackets around the function body. In python, the function body is identified by the indentation level. Since we don’t use curly brackets to indicate the function body, the indentation is useful for the python interpreter to know which part of the code defines the function logic. If we don’t have an indentation of the function logic relative to the function declaration, an IndentationError will be raised and the function will not be interpreted.
def fun(name): print("hello" + name)
The above function will not compile and will throw an IndentationError.
A function may return a value in which case it is intimated to the interpreter via the return statement. Unlike C, C++ or Java, multiple values can be returned by a python function. If we don’t include a return statement, the control will be transferred automatically to the calling code without returning any value. A default value of None will be returned if no return statement is there. As with other languages, a function can have at most one return statement.
def add(a, b): return a + b def hello(): print("Hello world") res = add(5,7) #res will be having a value of 12. res = hello() #res will be having a value of None.
We can set default values for arguments in the function definition. To do so we use the subsequent syntax. Note that the default arguments must be on the right side of the argument list. That is, a default argument must only come after all the non-default arguments.
def areaOfCircle(radius, pi=3.14): return pi * radius * radius
Here the function takes a default argument pi which is defined on the right side of the argument list. If we define the default argument to the left of a non-default argument we get a SyntaxError.
Now that we have defined functions, we see how we can call them in our code. To call a function we use the function name along with arguments that were used to define the function. The number of arguments should exactly match the number of arguments present in the function definition. Any difference in the number of arguments will raise the TypeError.
def areaOfCircle(radius, pi=3.14): return pi * radius * radius #function call print(areaOfCircle(5)) #note that the default argument is not passed a value. #prints 78.5 on the screen.
Programmers with C++ or Java background would have frequently overloaded functions. Overloading of functions doesn’t work in Python because if we define a function two or more times by varying the number of arguments, the last defined function will override the previous definitions. If the function with the specified number of arguments in the function call doesn’t even exist we get a TypeError. For eg,
def add(a, b): return a + b def add(a, b, c): return a + b + c print(add(1,2)) #throws a TypeError asking for one more argument. print(add(1,2,3)) #prints 6 on the console.
Passing functions as arguments
We can pass a function itself as an argument to a different function. Suppose we want to apply a specific function to an array of numbers. Rather than defining a function and calling it using a for loop, we could just use the map function. The map function is a powerful built-in function that takes a function and a collection of elements as arguments and applies the input function across the collection of elements and returns the processed elements.
def square(i): return i * i res = list(map(square, [1,2,3])) #res now contains [1,4,9]. We have gotten the results without even looping through the list
*args and **kwargs
Speaking about arguments there are some special types of arguments. Experienced programmers may have possibly used in C and C++ this argument. Python offers that capabilities too. If we don’t know how many arguments a function will receive during runtime we can use *args to receive those arguments in the function definition. We can also achieve function overloading using *args also although it is not technically function overloading as we are not defining multiple functions with the same function name.
def add(*args): sum = 0 for arg in args: sum += arg return sum add(1,2,3) #returns 6 add(1,2,3,4) #returns 10
If we want to receive named arguments, we can use the **kwargs.
def fun(**kwargs): for key in kwargs: print(key, kwargs[key]) fun(a=1,b=2,c=3) #prints #a 1 #b 2 #c 3
Any production level code would use a special type of argument. These are command-line arguments used by the main function. In python, those arguments will be passed to the __main__ function. We can easily get them by parsing the sys.argv variable. Since parsing a command-line string is a common task we have libraries to do that for us like argparse.
How to define ‘anonymous’ functions
Anonymous functions are functions without a name. They are also known as lambda functions. But wait! If a function has no name how will you call it? These are called where they are defined. They are not used later in the code most of the time. These functions are special functions that are used when we need to pass a function itself as an argument. This case most frequently occurs when we want to do some sort of data processing with pandas or any other library. The function might be so small that it doesn’t deserve a name of its own. These functions are defined with the keyword lambda.
list(map(lambda x: x*x, [1,2,3])) #prints values [1,4,9]
We have computed the squares of the input list without even defining a function. What we are doing with the statement lambda x: x*x is that we are defining an anonymous function, i.e without a name, and we are immediately calling it. Suppose that we want to use the lambda function at a later point we can store that in a function variable and use it.
square = lambda x: x*x list(map(square, [1,2,3])) #prints values [1,4,9]
The variable square stores the function to square numbers and we are using it at a later time when we want to compute the squares of the numbers in a list. While defining lambda functions we should keep the following points in mind:
- There is no return statement.
- The arguments aren’t written inside parentheses.
- There is no indentation.
- Multiple arguments are separated by a comma
- These functions are defined in a single line.
This concise article mentioned the steps to define a function and explained the components of a function. The function definition in python may seem very different compared to C, C++ or Java without curly brackets, return types etc. But once we grasp the function structure, it becomes easier to write more complicated functions.
About the author
I am a python developer working in an IT MNC for more than three years. I can be contacted via Gmail.