I’m assuming that you know basics of python. If not, I would recommend you to read python diaries 1, python diaries 2, and python diaries 3 because some concepts used here are already discussed there.
What is a function?
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.
return whatever_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.
c = a + b
Generally, a function consists of three parts, namely:
Now, we will discuss each of them one by one.
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 -:
- Global variables
- Memory location
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.
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
index,previous_index_value=searching() #assigned to two variables as we are returning two values
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.
See the example for more clarity?
#Array to be sorted
#sorting by sorted() function
#printing both array and new_arr
print "array ->",array
print "new_arr ->", new_arr
#Now sorting using sort() method
print "array_2 ->",array_2
array -> [3, 4, 1, 2, 5]
new_arr -> [1, 2, 3, 4, 5]
array_2 -> [1, 2, 3, 4, 5]
Now, continuing with the above mentioned question.
Also, we returned multiple values using return statement namely index and arr[index-1].
To store them in separated variables, we used 2 variables index and previous_index_value .
If we had used only a single variable then the values would have got stored in form of a tuple in the order in which they are returned.
That’s it for now. We will continue our discussion on function in upcoming articles.