Today we will learn about functions in python.
What are functions?
A function is a block of organized, reusable code that is used to perform a single, related action. They provide better modularity for your application and a high degree of code reusing. This means that you will have a separate block for doing one task. Python gives you many built-in functions like print(), etc. but you can also create your own functions too.
Let’s dive into it and understand more with the help of example.
first_number = 5
second_number = 6
when we write,
sum = first_number+second_number
We will get 11 as result. Now what if now i want to add different two numbers, i will have to assign new values to first_number and second_number variable and then print sum to get the desired result.
We have a better way to this, we can use functions. How, you say? Let’s get into it.
To declare a function that is to tell machine that certain part of our code is function, we use a keyword called def . Keywords are special words reserved by python, you cannot use them as variable names as it will result in error.
def sum_two_numbers(a, b):
Now, Let’s break it down and understand in detail what is happening in the code snippet above. def is a keyword to define function, sum_two_numbers is name of the function ( you can name it anything you want, but it is best practice to name a function such that it briefly explains what is it for ) , the variables in parenthesis are called parameters or arguments of the function ( you can contain zero or more arguments ), colon ( : ) tells us that function scope is getting started.
After that we left 4 spaces in the next line to tell the machine that code written below is part of the function and it is called definition of the function. In above example, we assigned the added value of variable a and b to a variable name sum.
Now, we used another keyword named as return, it will help output the value of sum variable as result.
This is how we defined a structure of a function.
Next question, how do we use it?
We call it and ask it to assist, just like a friend does.
Here, I wrote a python file named as main.py
You can write your custom python file, just remember to save the file name with .py extension. Then, to run that file you can navigate to the location where your file resides and run,
in command prompt and you will see the result for the code written in that file on command line.
As you can notice, our function only return a value but doesn’t print it. So we use print function to print the output of the function
print() is an in-built function which is used to print anything on the command line.
That’s it for functions basic. Try and write your own functions to perform difference of two numbers, addition of three numbers, multiplication of two numbers, division of two numbers, etc.
Have a great day!!