Functions in Python: Explained Using Examples!

This article is focused on readers who are at the very beginning of their programming journey, aimed at helping them to master the concept of functions!

The very first time I heard about “functions”, I felt so lost and everything sounded like a bunch of gibberish to me. Until the point when I understood the “secret sauce” I found the whole idea to be very daunting indeed!

But fear not, just give me 10 minutes of your undivided attention and I promise you will understand the entire idea as this article has been hand-crafted specifically for beginners!

This article will aim at answering the following questions.

  • What are these “functions”?
  • What is the need for them?
  • Why were they introduced into computer programming the first place?

Understanding the answers to these questions is the key to mastering this concept of “functions”!

Ready? Okay, let’s begin!

Need for functions

Okay, assume you want to teach a robot to make a cup of coffee. You would give it the following instructions

  1. Pour water into a bowl
  2. Keep that bowl on a stove
  3. Turn the stove on
  4. Wait for the water to reach 80 Degree Celsius
  5. Turn off the stove
  6. Pour the water into a cup
  7. Add 1 teaspoon of coffee powder to the water
  8. Stir the contents of the cup
  9. Serve hot

The below Python program will print this set of instructions.

print("INSTRUCTIONS TO MAKE COFFEE")
print("Pour water into a bowl")
print("Keep that bowl on a stove")
print("Turn the stove on")
print("Wait for the water to reach 80 Degree Celsius")
print("Turn off the stove")
print("Pour the water into a cup")
print("Add 1 teaspoon of coffee powder to the water")
print("Stir the contents of the cup")
print("Serve hot")
print()

Running this code will give an output like this

Example#1: Output

Simple isn’t it? Can you think of any improvements to the code above? No?

Yeah, not much can be done to improve this code.

Okay, now let us write another simple program and let us assume that this time we wish to make tea instead of coffee!

The code for making tea is shown below

print("INSTRUCTIONS TO MAKE TEA")
print("Pour water into a bowl")
print("Keep that bowl on a stove")
print("Turn the stove on")
print("Wait for the water to reach 80 Degree Celsius")
print("Turn off the stove")
print("Pour the water into a cup")
print("Add 1 tea bag to the cup ")
print("Let that sit for 2 minutes")
print("Serve hot")
print()

And the output for Example#2 will look like this

Example#2: Output

Okay, both the outputs of Example#1 and Example#2 seem very similar indeed!

Can you think of any improvements that you can make to this Example#2?

Yeah, similar to Example#1, not much can be done to improve this code.

Now say we want to make a program that does the following

  • print the instructions for making coffee and then
  • print the instructions for making tea

Then the code will look something like this

print("INSTRUCTIONS TO MAKE COFFEE")
print("Pour water into a bowl")
print("Keep that bowl on a stove")
print("Turn the stove on")
print("Wait for the water to reach 80 Degree Celsius")
print("Turn off the stove")
print("Pour the water into a cup")
print("Add 1 teaspoon of coffee powder to the water")
print("Stir the contents of the cup")
print("Serve hot")
print()

print("INSTRUCTIONS TO MAKE TEA")
print("Pour water into a bowl")
print("Keep that bowl on a stove")
print("Turn the stove on")
print("Wait for the water to reach 80 Degree Celsius")
print("Turn off the stove")
print("Pour the water into a cup")
print("Add 1 tea bag to the cup ")
print("Let that sit for 2 minutes")
print("Serve hot")
print()

As you can see, I have just copy-pasted both the codes of Examples 1&2 one after another.

And the output will look this

Example#3: Output

which is just as we wanted.

Does the code in Example#3 have any room for improvement?

This time the answer is YES, WE CAN IMPROVE THIS CODE! because

This program has the problem of Code repetition.

Focus on the below 2 sets of lines

  • lines 2 to 7 and
  • lines 14 to 19

They are exactly the same. Basically, we are repeating the same instructions to the computer.

Both these sets of lines are doing the same exact action of “making and pouring boiled water into a cup

So what we want to do is to replace these 6 lines

print("Pour water into a bowl")
print("Keep that bowl on a stove")
print("Turn the stove on")
print("Wait for the water to reach 80 Degree Celsius")
print("Turn off the stove")
print("Pour the water into a cup")

using a single line like

make and pour boiled water into a cup

Just imagine, if we have a way to group these lines into one single line like above, then we can write one line every time we need to do that action instead of writing a whole bunch of lines.

This is where the concept of “functions” came into the picture!

Functions are set of instructions that does a specific action.

The action in our case is “making and pouring boiled water into a cup!

This can be done in Python as shown in the program below.

def make_n_pour_boiled_water_into_cup():
	print("Pour water into a bowl")
	print("Keep that bowl on a stove")
	print("Turn the stove on")
	print("Wait for the water to reach 80 Degree Celsius")
	print("Turn off the stove")
	print("Pour the water into a cup")

print("INSTRUCTIONS TO MAKE COFFEE")
make_n_pour_boiled_water_into_cup()
print("Add 1 teaspoon of coffee powder to the water")
print("Stir the contents of the cup")
print("Serve hot")
print()

print("INSTRUCTIONS TO MAKE TEA")
make_n_pour_boiled_water_into_cup()
print("Add 1 tea bag to the cup ")
print("Let that sit for 2 minutes")
print("Serve hot")
print()

A Challenge for you!

Before seeing the output I want you to look at the code above and first come up with your own prediction on what the code will do. The practice of “Reading code with intent” will get you from being a “noob” to an “expert” in no time!

Are you ready? Okay, time to see the output!

Running this code will give the exact same output as in Example#3 as shown below

Example#4: Output

As you can see we got the exact same output and we did not “repeat ourselves”!

So how did we do that?

We have just made our very first function!

Lines 1 to 7 in Example#4 form a function.

So every time we write the line make_n_pour_boiled_water_into_cup(), we are essentially telling Python to execute all the lines grouped below that line in our code (the lines that start with the spaces).

Hence

Functions are a block of code that does a specific action.

In other words, functions are just the short way of mentioning a long action. For example, if I were to write a report of what I did today morning I can either write

  • I jogged for 20mins

or I can write

  • I put one leg in front of another at a moderate pace and continued to do that in a loop for 1200 seconds

Hence “Functions” are very useful at hiding away these unnecessary details and letting us write code that is short, sweet, and efficient!

In Python, functions take the following syntax.

  • start the line with the keyword “def” (look at the side-note below if you do not know what “keywords” are!)
  • then give the “set of lines” you want grouped together “a name”
  • end the line with a pair of parentheses (“Parentheses” is just a fancy name for brackets “()” )
  • write the set of lines you want to be grouped together
  • indent these lines of code with 4 spaces (start with 4 spaces at the beginning of each line)

Follow the above syntax/rules to group related lines of code together.

And whenever we need to execute this function (these lines of code) we have to use its name with a pair of parentheses like on lines 10 and 17 in Example#4 above.

This action of invoking a function using its name is also called a “function call“.

SideNote#1: Keywords

If you are wondering what kind of magic spell this “def” do, have a look at my other article specifically focusing on it

“def” in Python: Explained Using 10 Examples!

There I have explained

  • what “keywords” are
  • what does “def” do and
  • how to wield its power

in detail. The article in the link above is also crafted keeping a beginner in mind so read that one once you are done with this one!

Why code repetition needs to be avoided?

Assume it is winter and we wish to make both the tea and coffee warmer. Let’s say we wish to heat them up to 90 degrees instead of 80 degrees.

Then our function in Example#4 becomes

def make_n_pour_boiled_water_into_cup():
	print("Pour water into a bowl")
	print("Keep that bowl on a stove")
	print("Turn the stove on")
	print("Wait for the water to reach 90 Degree Celsius")
	print("Turn off the stove")
	print("Pour the water into a cup")

As you can see, we just needed to edit one line of code (line-5). If we went with the format in Example#3 (the one without the functions) then we would have had to edit 2 lines of code instead.

One more extra line must not seem like a lot right now, but trust me when you are working on a huge project, one of the most common mistakes programmers make when making changes is to make the change in one place but forget about that altogether in another place.

Thus avoiding code repetition helps us to

  • make the code shorter and
  • make the code easier to maintain!

Okay, what if we wish to make coffee and tea at different temperatures?

How can we do that? Do we need to write 2 functions?

We can do that using a single function by sending the temperature value to functions to print them out. The next section shows how exactly we can do that!

Passing Values into Functions

If you were wondering what those brackets at the end of function names are for, the answer is to send some values into functions!

Have a look at the example below. Here, our goal is to make the coffee at 85 degrees and tea at 95 degrees, while using the exact same function!

def make_n_pour_boiled_water_into_cup(temperature):
	print("Pour water into a bowl")
	print("Keep that bowl on a stove")
	print("Turn the stove on")
	print("Wait for the water to reach " + str(temperature) + " Degree Celsius")
	print("Turn off the stove")
	print("Pour the water into a cup")

print("INSTRUCTIONS TO MAKE COFFEE")
make_n_pour_boiled_water_into_cup(85)
print("Add 1 teaspoon of coffee powder to the water")
print("Stir the contents of the cup")
print("Serve hot")
print()

print("INSTRUCTIONS TO MAKE TEA")
make_n_pour_boiled_water_into_cup(95)
print("Add 1 tea bag to the cup ")
print("Let that sit for 2 minutes")
print("Serve hot")
print()

Another Code Reading Challenge!

Try to read the code and come up with an explanation by yourself before looking at the explanation!

So how does the whole thing work?

  • we sent in the value 85 when making the coffee on line-10
  • this gets passed to the function, and the variable temperature gets loaded with the value 85
  • on line-5 this value 85 then gets converted to string and gets printed.

Similarly, 95 gets passed in when making Tea and we get the output as shown below.

Example#6: Output

The examples so far focused on introducing the concept of functions.

The one thing that differentiates the “best craftsmen” from the “mediocre ones” is the fact that the best craftsmen take time to focus on the little things too!

In software engineering these “little things” include

  • code readability and
  • code maintainability (“maintainability” is just a fancy way of saying, the code should be understandable even if you read it after a year!)

Now let us learn how to write the best code by seeing how we can improve the readability and maintainability of the code by using functions!

Improving Readability Using Functions

Python is all about readability!

The version in Example#6 is not very bad, but there is still room for improvement. In the below example I have broken down the code into 3 functions so that the code becomes more readable.

def boil_water(temperature):
	print("Pour water into a bowl")
	print("Keep that bowl on a stove")
	print("Turn the stove on")
	print("Wait for the water to reach" + temperature + " Degree Celsius")
	print("Turn off the stove")
	print("Pour the water into a cup")

def make_coffee():
        print("Add 1 teaspoon of coffee powder to the water")
        print("Stir the contents of the cup")
        print("Serve hot")
        print()

def make_tea():
        print("Add 1 tea bag to the cup ")
        print("Let that sit for 2 minutes")
        print("Serve hot")
        print()

print("INSTRUCTIONS TO MAKE COFFEE")
boil_water(90)
make_coffee()

print("INSTRUCTIONS TO MAKE TEA")
boil_water(90)
make_tea()

Sharing your functions

Say you wish to share the function you have just made with your friends, you can do that by making a separate Python file as shown below (e.g. make_beverage.py) and giving that to your friends and colleagues.

def boil_water(temperature):
	print("Pour water into a bowl")
	print("Keep that bowl on a stove")
	print("Turn the stove on")
	print("Wait for the water to reach" + str(temperature) + " Degree Celsius")
	print("Turn off the stove")
	print("Pour the water into a cup")

def make_coffee():
        print("Add 1 teaspoon of coffee powder to the water")
        print("Stir the contents of the cup")
        print("Serve hot")
        print()

def make_tea():
        print("Add 1 tea bag to the cup ")
        print("Let that sit for 2 minutes")
        print("Serve hot")
        print()

Your friends can then import the file into their own code using the “import” keyword as shown below.

import make_beverages

print("INSTRUCTIONS TO MAKE COFFEE")
boil_water(90)
make_coffee()

print("INSTRUCTIONS TO MAKE TEA")
boil_water(90)
make_tea()

There is one more trick you need to learn from functions, which is to learn how to retrieve values from a function.

Retrieving Values From Functions.

We already know how to send values into the functions using the brackets (parentheses) at the end. This section tells you how to retrieve values from the functions.

Say we have a simple program to calculate the price of an apartment based on the area of the apartment and the price per meter square.

We use the 2 functions below to do our calculations.

def calc_area(length, breadth):
      area = length * breadth
      return area

def calc_price(area, price_per_sq_m):
       price = area * price_per_sq_m
       return price

If you look at lines 3 and 7, you can see they both have the special “return” keyword. The variable next to this return keyword is returned back from the function.

Let us try retrieving the values now.

import price_calculator

length = 25
breadth = 35
price_per_sqm = 584

land_area = calc_area(length, breadth)
land_price = calc_price(area, price_per_sqm)

print("Price of the land is ", + str(land_price))

In the above script,

  • on line-6 the land_area variable gets the value “returned” by the function calc_area()
  • on line-7 the variable land_price gets the value “returned” by the function calc_price() and
  • the print statement prints the result.

Pretty straightforward isn’t it! Yet, very useful!

Improving the Maintainability of Code

Say you worked on a program 2 years back and then for some project you want to reuse the code again. But will you remember the exact logic you used? Trust me when I say this, nobody does!

So how can we make sure that we can understand our own code after 2 years?

Also, how can we make sure that other programmers can read and understand our code?

The answer to both these questions is “Documentation” which is just a fancy word for “properly structured notes!”

Let us see how we can document functions in Python with our last and 10th example!

def calc_area(length: float, breadth:float)->float:
    '''calculate the area of a rectangular shape using the length and breadth'''
    area = length * breadth
    return area

def calc_price(area: float, price_per_sq_m: float)->float:
    """calculate the price of a given land 
       using the area of the land and 
       the price per square meter of the land
    """
    price = area * price_per_sq_m
    return price
    

I want you to concentrate on line-1. As you can see we have 2 new syntax elements. Let us see them one by one!

Variable type

length:float, breadth:float

Here we are basically telling the user of our function that the variables length and breadth are floating-point variables (a.k.a decimals) so we must pass floating-point values into these variables.

The variable type must follow the variable name and the colon “:” punctuation.

One point worth noting is that the variables being passed into functions are also affectionately known as “arguments”. Just some jargon used in the programming world.

Return Type

At the end of line-1 between the parentheses “()” and the colon “:” symbol we have some new construct.

>float

So what does that mean?

It means that the type of variable returned by the function is floating-point type.

Documentation String

In line-2 we have a line explaining what the function does. This string is surrounded by 3 single quote symbols (”’). This line is called the Documentation string. You can also use the 3 double quotes (“””) instead as shown in lines 7,8, and 9.

Say you are using code written by someone else and you wish to see all the documentation mentioned above, how can you see all these values?

This can be accomplished using the in-built help() function!

>>> import price_calculator
>>> help(price_calculator.calc_area)
>>> help(price_calculator.calc_price)

Press “Q” on your keyboard to get back to the interpreter

press Q again to get back to the interpreter

Just for fun let us see what “help” has to say about the “print” function that we used so much in this article!

help(print)

There seems to be a lot of documentation. I don’t expect you to understand everything at this stage, as there is some fairly advanced stuff in there! The key point to remember here is that all those stuff actually came from the documentations we saw above!

Conclusion

I hope this article has delivered on the promise of helping you understand the idea behind functions and you are now able to wield its power in your programs!

And with that, I will stop.

Feel free to share this article with your friends and colleagues who are learning to program!

Check out our other beginner-level Python articles in the “Where to go from here?” section below!

Where to go from here?

“def” in Python: Explained Using 10 Examples!

Python Comparison Operators Explained Using 10 Examples!

Python “is” and “is not”: Explained Using 14 Examples!

Python “in” and “not in”: Explained Using 8 Examples!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn