How to write Functions in Python

Functions in Python allow you to write codes and reuse them over and over again, and in this post, you will learn how to write or call functions.

But first, let’s understand what function really means.

A function is simply a reusable block of code that is written to perform a specific task. This task can be as simple as performing mathematical operations, printing a message, rendering a 3D image or even opening a database connection.

Once a function has been defined, you can call it over and over to perform the tasks for which it was designed.

Functions offer several advantages that can make them quite useful in programs and here are some of the reasons:

  • Functions facilitate code reuse, thereby making program development more efficient and error-prone.
  • Breaking down chunks of code into functions makes your program easy to read, test and debug.
  • Functions minimize duplication of code, encouraging continuous improvements of code.

Types of Functions

There are two types of functions in Python and they include:

  • Built-in functions
  • User-defined functions

Built-in, also known as predefined functions are shipped with the standard Python library. Examples are input(), range(), print().

User-defined functions also known as custom functions are created by programmers and are designed to serve a specific purpose.

Creating a simple function

The keyword def is used to instruct the Python interpreter that you are creating a function. This is followed by the name of the function, and a parenthesis containing parameters (which are optional) and ending with a colon.

These parameters provide the data upon which the function processes to perform a task.

The indented lines that follow thereafter form the body of the function. In the real sense, it is the body of a function that does what the function is created to do.

def function_name(<parameters>):

<function_body>

The example below is a simple function, with the name greet, performing a simple task of printing the message – hello.


def greet():

    print('hello')

Calling a function

Functions do not run or execute on their own until they are called.
A function call is a way of telling the interpreter to execute the code contained in a function.
To call a function, all you have to do is to provide the name of the function followed by a parenthesis.
For instance:
greet()

#output
hello

Parameters and Arguments

While the function can work as a self-contained or standalone unit, there are times when it needs data or information to do its work.
This information is provided in the form of parameters and arguments.
Parameters are variables provided in the parenthesis during the definition of a function. Arguments on the other hand are values provided during a function call.
So, parameters are data or information required by the function to do its job, while arguments are information provided to the function in order to do its job.
The following is an example of a function with parameters and a function call with arguments.

#function definition
def add(a, b, c):
    sum = a + b + c
    print(sum)

#function call
add(1,2,3)
#output
#6

To illustrate further, the following code demonstrates how to create functions with parameters and as well call the functions using arguments.

#create and call functions

def Add(a, b):
    result = a + b
    print (result)

def Subtract(a, b):
    result = a - b
    print (result)

def Multiply(a, b):
    result = a * b
    print (result)

def Divide (a, b):
    result = a / b
    print (result)

#call functions
Add(2, 3)
Subtract(200, 111)
Multiply(12, 3)
Divide (18, 2)

Using a Function to check whether a number is even or odd

In the following example, a function is used alongside if statements to check whether a number is even or odd and print a message indicating what kind of number it is.

def check_odd_even(num):
    if(num%2)==0:
        print(num,'is even')
    else:
        print(num,'is odd')

number = int(input('enter any number: '))
check_odd(number)

return statement

Functions are meant to solve specific programming tasks.
A function doesn’t always display an output. It can also return values after performing some operations, using the return statement.
The return statement takes a value from the function and returns or sends it out when the function is being called.
In other words, the return statement is used to send the outcome or result of a function’s operation to the caller.

#return statement in python functions

def func(a, b):
    result = a + b
    return result

sum = func(4, 6)

print (sum)

Recursive functions

A function that calls itself over and over again is said to be recursive. An example of the recursive function is calculating factorials or creating Fibonacci series.

The example below uses recursion to calculate the sum of natural numbers.


#recursive sum of natural numbers
def sum(num):
    if num <= 1:
        return num
    else:
        return num+sum(num-1)

number = 7
print(sum(7))

#output
#28

Factorial of numbers using recursion

Now, let’s use the recursive method to find the factorial of a number.

#finding factorial using recursive function
def factorial(num):
    if num==1:
        return num
    else:
        return num*factorial(num-1)

number = 7
result = factorial(number)
print('The factorial of', number, 'is', result)
#output
#5040

Anonymous/Lambda functions

A lambda function also known as an anonymous function is a function without a name. Just like regular functions, it can take any number of arguments but can only contain a single expression. It’s a way of creating a function on the fly without the need for defining and calling on a function.

Keep in mind that lambda functions can only be expressed in a single line.

Lambda functions are declared using the lambda keyword.


square = lambda x : x*2

print(square(3))

#output
#6

In the above example, the keyword lambda is used to tell Python that you are creating a lambda function. The variable x after the keyword – lambda, represents the argument that you want to pass to the function. x*2 is the expression that you want to evaluate through the function.

The example below is another lambda function, but this time with multiple arguments.


square =  lambda x, y : x*y

print(square(3, 5))

#output
#15

Leave a Reply

Your email address will not be published. Required fields are marked *