A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

On googleing “what is function in programming”, you will get the above answer. It aptly defines what a function is. Let us look further into it.

A function is just like a black box which takes some input, processes it and gives an output. Now, as we are coders, we will make the black box ourselves.

Python

1

2

3

defname_of_function(arguments_separated_by_comma):

your code/logic

returnwhatever_you_want_to# returning is not necessary

Here is an example of function in Python.Note→ Indent all lines of code you want in the function 4 spaces.

Example→

Python

1

2

3

4

5

defsum_of_numbers(a,b):

c=a+b

returnc

printsum_of_numbers(2,3)

Output --> 5

Generally, a function consists of three parts, namely:

Input

Code/Logic

Output

Now, we will discuss each of them one by one.

Input

Input is nothing but the data on which function will do some processing to get the desired output.

Input can be given to function through parameters/arguments or global variables or memory location. In the above example function sum_of_numbers, we are passing the input through variables a and b. Here a and b are parameters.

We will discuss other methods of input in upcoming examples.

Summary of Input →Three ways to input data -:

Parameters/arguments

Global variables

Memory location

Code/Logic

It is a group of statements written together to perform a particular task defined by the programmer

Whatever Logical statements you write inside your function is your code. It is the algorithm (written by you) which performs some logical operation on the input.

In function sum_of_numbers, our logic part consist of a single statement which performs addition of numbers a and b.

Logic/code depends on requirement of user. It may range to several hundred lines.

Output

It is the data sent out by the function (black box). If we have performed some processing on an input, we must be willing to get some output. Though sometimes output is not directly visible but something may have changed behind the screen (internally).

A function can output data by return statement or by modifying the value stored at a memory location directly or we can directly print the value from inside the function. If we are not getting some output then there is no meaning of a function (exceptions are always there!).

Note→ Writing return statement is required only when you are returning something directly i.e. returning some array or variable etc.

Let us look at all of above properties of function (and some others too) through the following examples. Before that, let’s summarize Output.

Summary of Output →

Three ways to output data -:

Return Statement

Modify data at some Memory Location

Print statement

Scope of variables

Any variables defined inside the function is local variable, it means that if we try to access the variable outside the function, we will get an error message.

Any variable defined outside the function (Globally) is global variable, it means we can use them anywhere in our program (both inside and outside of the function). But wait, if we can use them everywhere, how will we differentiate a global variable from a local variable with same name. Python has a very elegant solution for this. To use any global variable inside the function, declare it as “ global variable_name” inside the function. We have to write the keyword global only once then it can be used as any other local variable.

Note → Global variable has global scope i.e. we can use it anywhere in same module but not in other modules. There is another scope called Built-in scope. Built-in scope includes the variables and literal values deﬁned as part of the language, which can be used anywhere within a program.

Return Multiple Values

We can return multiple values from a function very easily. While writing the return statement, simply write the variable names separated by comma.

Let’s discuss it through an example

Question→ Given an array, find the number ‘K’ in array and print the index of the number K and also the number at previous index. Assume index of K can’t be zero and all numbers are distinct.

Given array is → [5,6,7,12,2,4,3,9,25,29,30,31] and K is 29.

Solution →

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

array=[5,6,7,12,2,4,3,9,25,29]

k=29

defsearching():

globalarray

array.sort()

globalk

index=0

whileindex<len(array):

ifarray[index]==k:

returnindex,array[index-1]

index=index+1

index,previous_index_value=searching()#assigned to two variables as we are returning two values

printindex

printprevious_index_value

Output →925

In above code we are using the global variable k inside our function searching. For that, we declared it as global variable and then used it as any other variable.

Similarly, we declared array as global. The sort() method modifies the original array unlike sorted() function which return another list which needs to be stored in some variable.

Suppose our array is stored at location X. Then sort() will sort it and the location of sorted array will be X, so our original array is lost. On other hand sorted() will create the sorted array at some new location in memory, say Y. So, we need to assign a variable to point to the sorted array.

If we print array after using sort() method, we will get its sorted form as output. But if we sort it using sorted() function and then we print it, we will get the original array same as input unless we assign sorted array the same variable name.

About the Author

Our guest articles are a collection of the best contributions made by members of the developer community on our blog. Discover articles on a wide range of topics, shared by top programmers across the world.