What is a function & how to define it?
In this lesson, we will start learning function in Python. Let's do it.
What is a function ?
- A function is a group of related statements that perform a specific task. You can define a function to perform any task (easy or complex task).
- It avoids repetition and makes code reusable. Whenever you want to perform that particular task you call your function.
- Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Built-in functions and User defined functions
- Functions that are included with Python are called built-in functions. Example - print, input, type, int
Those functions that we define ourselves to accomplish a specific task are called user-defined functions.
Syntax
Here is the syntax to define a function
def function_name(parameter(s)):
function body
- Parameters are just variables that are going to be used in the function's body. We provide its values while calling the function.
- When we write a function its body will not be executed unless we call it.
Calling a function
function_name(argument(s))
- We provide the values of parameters (variables) when calling the function. These values are called arguments.
- The number of arguments depends on the parameters.
- Calling simply means that it will run a function's body with given arguments.
Here is a simple example to help you understand everything.
# Task - addition of 2 numbers
# define
def addition(a,b):
c = a +b
print(c)
How to decide parameters: What does your function do? In this example, our function adds two numbers, so we need 2 parameters.
- When we define a function, its body will not be executed unless it is called.
addition(10,20) ### positional arguments
addition(a=30,b=10) ## keyword arguments
- Calling a function means the body will be executed with parameters.