Developers

PYTHON DIARIES CHAPTER 4 → FUNCTION PART – 1

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.

def name_of_function(arguments_separated_by_comma):
    your code/logic
    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.

Example?

def sum_of_numbers(a,b):
    c = a + b
    return c

print sum_of_numbers(2,3)

Output –> 5

Generally, a function consists of three parts, namely:

  1. Input
  2. Code/Logic
  3. 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 -:

  1. Parameters/arguments
  2. Global variables
  3. 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 -:

  1. Return Statement
  2. Modify data at some Memory Location
  3. 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 ?

array=[5,6,7,12,2,4,3,9,25,29]
k=29
def searching():
    global array
    array.sort()
    global k
    index=0
    while index<len(array):
        if array[index]==k:
            return index,array[index-1]
        index=index+1

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

Output ?
9
25

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?

Program?

#Array to be sorted
array=[3,4,1,2,5]

#sorting by sorted() function
new_arr=sorted(array)

#printing both array and new_arr
print "array ->",array
print "new_arr ->", new_arr

#Now sorting using sort() method
array_2=[2,3,5,4,1]
array_2.sort()

#Printing array_2
print "array_2 ->",array_2

Output?
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.

Stay Tuned……….

Guest 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.

Share
Published by
Guest Author

Recent Posts

The Impact of Talent Assessments on Reducing Employee Turnover

Organizations of all industries struggle with employee turnover. The high turnover rates cause increased hiring…

12 hours ago

Virtual Recruitment Events: A Complete Guide

Virtual hiring events are becoming vital for modern recruitment, and the hiring world is changing…

12 hours ago

The Role of Recruitment KPIs in Optimizing Your Talent Strategy

The competition for talent today is intense, and this makes it very important for organizations…

12 hours ago

Interview as a Service – Optimizing Tech Hiring for Efficient Recruitment

Hiring trends are continuously evolving over the ages to keep pace with the latest technological…

12 hours ago

HR Scorecards: Using Metrics to Improve Hiring and Workforce Management

Hiring practices have changed significantly over the past 30 years. Technological advancements and changing workforce…

13 hours ago

Why Recruiting Analytics is Critical for Hiring Success in 2024

In the current world, where the hiring process is ever-evolving, it has become crucial to…

14 hours ago