functions are a set of instructions that can be reused any number of times.

Why use a function? In programming, sometimes we need to repeat a code. Instead of writing a code again and again we can just convert that code into a function and then call it again and again whenever needed. Moreover it will become more easy to maintain our code by using functions.

def keyword

def keyword is used to define a function in python. After def write the function name and then opening and closing parenthesis. Inside parenthesis we can pass optional parameters. Parameters contain extra information that can be used inside the function.

After parameters we write colon ':' and our tabbed blocks begins in which we define functions body.

To use our function we need to call it with functions name.

Syntax of declaring a function:

def function-name(parameter1, parameter2,...):
	#code instruction

After function definition we have to call it to execute the statements within it. If function defintion contains parameters then we must have to pass arguments to the function name while calling.

We call above function as follows:

function-name(parameter1, parameter2,...)

Example of function without parameters:

def add():


Example of function with parameters:

def add(a,b):

Check out the line where function is called 'add(10,20)'.

After function call, parameter 'a' gets value as 10 and parameter 'b' gets value as 20.

Returning value from functions

return statement is used to return values from functions.

Syntax for using return statement:

def add():
	return c

result = add()

After function call, the function will add the two values and return the variable 'c' which is then assigned to the variable 'result'.

parameters vs arguments

The word parameters and arguments are often used while dealing with functions. Many times they are used interchangeably but there is a slight difference between them.

A parameter is the variable which is part of the function declaration while an argument is an expression used when calling the function.

<< Loop Control Statements Working with Numbers >>