Functions in Python
By Y Dayanand Kumar
Function:
● In programming, the use of function is one of the means to achieve modularity
and reusability.
● The process of dividing a computer program into separate independent blocks
of code or separate sub-problems with different names and specific
functionalities is known as modular programming.
● It can be defined as a named group of instructions that accomplish a specific
task when it is invoked.
● It can be called repeatedly without writing all the codes of that function, by
simply writing the name of the function and passing the required parameters.
Syntax:
def <function_name>([para1, para2, para3,...]):
#code block (body of the function)
return <value> #optional
Example:
def greet(name):
print(“Hello,” + name + “!”)
greet(“Kumar”)
Types of function:
The two main types:
1. Built-In Functions: These are pre-defined functions provided by Python.
Examples: print(), type(), max(), min(), range(), etc.
2. User Defined Functions: These are functions created by the programmer
using the def keyword.
Example:
def add(a,b):
return a+b
Flow of execution:
● Order in which the statements in a program are executed.
● Execution starts from the first statement in order of appearance from top to
bottom.
● Interpreter does not execute the statements inside the function until the
function is called.
● When the function call is found, instead of next statement it will execute the
function’s statements.
● Then, control comes back to the point of function call and remaining
statements will be executed.