Creating and Calling Functions

--Originally published at Programming

Introduction to functions

In simple words, a function  is a block of reusable code to perform a single action that can be called whenever the program requires it. Python already has many built-in functions ready for you to use, such as print() input() etc… But you can also create your own functions. When you know your program is going to use certain lines of code several times the best thing to do is to create a function and then call it when needed.

Declaring a function

To declare a function you need to begin with the keyword def followed by the function name of your election and parentheses (). Should your function need parameters, they should be placed between these parentheses. A colon (:) is required at the end of the parentheses. Every line of code inside the if statement must be indented.If you want your function to return a value, you must add the return statement followed by the return value at the end of your function. Now let’s take a look at a simple example.

1.png

Calling a function

Once your function is declared, you can execute your function by calling it from another function or from the Python prompt. Here is what you need to do in order to call it. 3.png

The result of running the program will print to the console the number 3

Example

Now that we know the basics of declaring a function and calling it, it is time to make a simple program that can show you when it may be necessary to implement functions in your programs.

Let’s say we want to make a program that calculates the area of a circle. Considering that the formula for Area is A =  πr2  let’s make a program first without using functions. The program

2.png
4.png
5.png
look like this.

2.png

4.png

It works! But what if later in our program we want to get the area of the circle several times? It’s going to be more efficient if we create a function to get the area. The final program will look like this.

5.png

And the output will be the same as the other one!