How to declare a function in Python
A function is a collection of statements that are executed only when the function is called.
Declaration
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.
Return value
To return a value from a function, use the return keyword, as shown below:
return x
x: The return value of the function.
Note: When a function returns, the statements in the function after the return statement are not executed.
Calling a function
A function is called by writing its name, followed by its parameters enclosed in brackets.
_funcName_ ( _parameters(s) )
Examples
Example 1
Consider a simple example of a function that returns the sum of two numbers:
def sum(a, b):tempSum = a + breturn tempSuma = 2b = 10res = sum(a, b)print "a + b =", res
Explanation
- Lines 1-3: The
sumfunction is declared and takes two input parameters,aandb. The sum function calculates the mathematical sum ofaandbin line 2 and stores the sum in a local variable,tempSum. ThetempSumvariable is returned using thereturnkeyword. - Line 18: The
sumfunction is called in line 8 and is passed withaandbas input parameters. The return value of thesumfunction is then stored in theresvariable.
Example 2
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 = 2b = 10noParam()
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved