A function is a collection of statements that are executed only when the function is called.
Functions in Python are declared using the
def keyword, as shown in the code snippet below:
def _funcName_ (_parameter(s)_, ...): //function body
_funcName_: The name of the function.
_parameters(s)_: The input parameters that are passed to the function.
function body: The statements written within a function.
To return a value from a function, use the
return keyword, as shown below:
x: The return value of the function.
Note: When a function returns, the statements in the function after the return statement are not executed.
A function is called by writing its name, followed by its parameters enclosed in brackets.
_funcName_ ( _parameters(s) )
Consider a simple example of a function that returns the sum of two numbers:
def sum(a, b): tempSum = a + b return tempSum a = 2 b = 10 res = sum(a, b) print "a + b =", res
sumfunction is declared and takes two input parameters,
b. The sum function calculates the mathematical sum of
bin line 2 and stores the sum in a local variable,
tempSumvariable is returned using the
sumfunction is called in line 8 and is passed with
bas input parameters. The return value of the
sumfunction is then stored in the
Consider an example of a function with no input parameters and no return value:
def noParam(): print "This is a function with no parameters and no retrun value" a = 2 b = 10 noParam()
View all Courses