Page 147 - CodePilot V5.0 C8
P. 147
User-defined Functions
Functions defined by the user according to the needs of the program are called user-defined
functions. They can perform a specific task. User-defined functions are called and used in the
same way as built-in functions.
CREATING A FUNCTION
The syntax to define a function is as follows:
def function_name(parameter1, parameter2,…,parameterN):
#function body
#return statement
A Python function consists of the following components:
The def keyword: Every function definition must begin with the def keyword.
Function name: It comes after the def keyword, should be meaningful and follow Python
naming rules.
Parameters: After the function’s name, parameters are defined inside parentheses. These are
optional and contain the variables that are passed to a function to perform a specific task.
Function body: It contains one or more indented code statements that execute when the
function is called.
The return keyword: The return keyword is used to exit a function.
Return statement: It is optional and is used if you want your function to return a value. If there
is no return statement, then the function will return None.
For example, to calculate the area of a rectangle, a function is:
def calculate_area(Length, Breadth):
area=Length*Breadth
return area
CALLING A FUNCTION
Once you have defined the function, you can call it from another function, program or even the
Python prompt. You can call a function by typing the function name followed by parentheses. If
the function takes any arguments, they are included within the parentheses.
The syntax to call a function is as follows:
function_name(parameter1,parameter2,…,parameterN)
For example, suppose you have a function named calculate_area() that takes two parameters,
length and breadth. You can execute it as follows:
def calculate_area(Length, Breadth):
area=Length*Breadth
return area
calculate_area(4, 5)
145
Step Ahead with Python

