How to define a function in Python?

Contents

A function is a reusable code block 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 ++ about Java. The goal of this post is to provide the syntax for defining functions in Python.

The definition of the function begins with a def keyword followed by the name of the function and the arguments that the function can take. These arguments are in parentheses and there can be any number of arguments, including zero. When there is more than one argument, are separated by a comma. Since Python is a imprecise type language (which means we don't assign a data type to a variable when it is declared), we should not include the data types for the arguments. The function definition declaration ends with 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.

Bleeding

If we look closely at the definition of the function, we see that there are no braces around the body of the function. In Python, the body of the function is identified by the indentation level. Since we do not use curly braces to indicate the body of the function, the indentation is useful for the Python interpreter to know which part of the code sets the function logic. If we don't have an indentation of the function logic relative to the function declaration, a IndentationError will be generated and the function will not be interpreted.

def fun(name):
print("hello" + name)

The above function will not compile and will return a IndentationError.

Return values

A function can return a value in which case it is hinted to the interpreter by means of the Return statement. Unlike C, C ++ about Java, a python function can return multiple values. If we don't include a return statement, control will be automatically transferred to the calling code without returning any value. A default value of None will be refunded if there is no return statement. In the same way as with other languages, a function can have at most one return declaration.

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.

Default arguments

We can determine default values ​​for the arguments in the function definition. For this we use the following syntax. Note that the default arguments must be on the right side of the argument list. In other words, a default argument should only come after all non-default arguments.

def areaOfCircle(radius, pi=3.14):
    return pi * radius * radius

Here the function takes a default pi argument which is set to the right side of the argument list. If we define the default argument to the left of a non-default argument, we get a Syntax error.

Call functions

Now that we have defined functions, see how we can call them in our code. To call a function we use the name of the function together with the arguments that were used to set the function. The number of arguments must exactly match the number of arguments present in the function definition. Any difference in the number of arguments will raise the Typing error.

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.

Feature overload

Experienced C programmers ++ or Java would have overloaded functions often. Function overloading does not work in Python because if we define a function two or more times by varying the number of arguments, last set function will override previous definitions. If the function with the specified number of arguments in the function call doesn't even exist, we get a Typing error. As an example,

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. Instead of setting 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 items as arguments and applies the input function to the entire collection of items and returns the processed items..

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

* arguments and ** kwargs

Talking about arguments, there are some special types of arguments. Experienced programmers may have used this argument in C and C ++. Python also offers those capabilities. If we do not know how many arguments a function will receive throughout the execution time, we can use * args to receive those arguments in the function definition. Furthermore we can achieve a function overload using * args even though technically not a function overload since 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 ** 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

Command line arguments

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 obtain them by parsing the variable sys.argv. Since parsing a command line string is a common task, we have libraries to do that for us, how to argue.

How to set ‘anonymous functions’

Anonymous functions are unnamed functions. They are also known as lambda functions. But wait! If a function has no name, How will you call it? These are named 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 occurs most frequently when we want to do some kind of data processing with pandas or any other library. The function can be so small that it does not deserve a proper name. These functions are defined with the keyword lambda.

list(map(lambda x: x*x, [1,2,3]))
#prints values [1,4,9]

We have calculated the squares of the input list without even setting a function. What are we doing with the statement lambda x: x * x is that we are defining an anonymous function, In other words, Nameless, and we are calling her immediately. Suppose we want to use the lambda function at a later point, we can store it 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 in square numbers and we will use it at a later time when we want to calculate the squares of the numbers in a list. When establishing lambda functions we must pay attention to the following points:

  1. No return statement.
  2. Arguments are not enclosed in parentheses.
  3. No indentation.
  4. Multiple arguments are separated by a comma
  5. These functions are defined on a single line.

Conclution

This concise post mentioned the steps to set a function and explained the components of a function. Function definition in Python may look very different compared to C, C ++ or Java without keys, return types, etc. But once we understand the structure of the function, it becomes easier to write more complicated functions.

About the Author

I am a Python developer working in an IT multinational for more than three years. You can contact me through Gmail.

The media shown in this post is not the property of Analytics Vidhya and is used at the author's discretion.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.