Python Functions
Functions
A function is a block of statements. It is a unit of reusable code. Function is defined by using the def keyword and followed by function name.
Function definition
def myFunction(args): set of statements can be indented equally.
Function call
functionname(args);
def findMax (a, b): if a > b: return a else: return b x = findMax (5,6) y = findMax (8,7) print(x) print(y)
Output
6
8
Function with multiple returns values
In python function can return a more than one values also.
def getValues (): radius = 2.0; center = [0.0,0.0,10] return radius, center output = getValues() radius, points = getValues() print(output) print(radius,points)
Output
(2.0, [0.0, 0.0, 10])
2.0 [0.0, 0.0, 10]
Function with Default arguments
Function can have an argument, but it is optional to pass a function.
def getMinElemSize (avgElemSize = 2): return avgElemSize/10 x = getMinElemSize (4) y = getMinElemSize () # if argument is not passed, it considers default is 2 print(x) print(y)
Output
0.4
0.2