5) Functions Basics

You’ve learnt about loops so far. Loops allow you to repeat the same code over and over again.

But what if you wanted to execute the same code but at different areas? For example, let’s say that you write a python program that first calculates the loan interest for the user. Later it processes a file and calculates the interest once again. This is where functions come in.

Functions are a bunch of code that is defined under a name (you can give it whatever name you want). You need to use the def built-in while defining a function. Later, whenever you need to run that code you just call the function by its name.

Here’s what this would look like:



Here’s an example of how this would work. Try calling the function more times and see what happens:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Hello friend

====================
I'm Pandaman!
====================

I was just a regular guy before.
But I kept training myself.
Then one day I realized that I can fly!
And now..

====================
I'
m Pandaman!
====================




You can call a function as many times as you want.

You can even pass a bunch of variables also called as arguments or parameters to the function so that it can work with them.

The next example illustrates how, instead of always printing the same message, you could print a customized message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Hello friend

====================
My name was Pandomoro
====================

I was just a regular guy.
But I kept training myself.
Then one day I realized that I can fly!
And starting today..

====================
I am Pandaman!
====================



Functions can also return a value back to the location where they were called.

1
2
The area of a cirlce with radius 50cm is
7850.0 cm sq.



It is important to note that whenever your function returns a value, the flow of control passes back to the place where you called it from. This means that you have to be careful where you place the return. Take a look at the following example:

Once the return statement gets executed then function execution is over. Any statements after return don’t get executed. That is why you want to return a value in the end, once your function is done with its execution.