As in any other language Python allows for the definition of functions. Functions are a set of sequence of instructions that receive well define inputs and produce some outputs.
To define a function Python uses the word def. The value that the function returns
must be preceded by a return. The syntax would be:
def FUNCTION_NAME(INPUTS):
INSTRUCTIONS
return OUTPUTS
or
def FUNCTION_NAME(INPUTS):
INSTRUCTIONS
The return function is optional. Not every function should return an output.
Some functions simply modify the inputs without producing any output.
Important: The instructions and the return statements belonging to the fuction must be indented by 4 spaces inside the header. Indentation is the only way that Python has to group lines of code.
Let's have some simple examples
In [ ]:
def square(a):
return a*a
print(square(1), square(2), square(5))
In [ ]:
square('a') # This should give an error
In [ ]:
def minimum(a, b):
if a<b:
return a
elif b<a:
return b
else:
return a
In [ ]:
minimum(4,5)
In [ ]:
minimum(4,0)
In [ ]:
def power(a, b=2):
return a**b
In [ ]:
power(2)
In [ ]:
power(2, b=5) # This is the prefered way to change the default parameters
In [ ]:
power(2,5) # This works as well
Define a function distance that takes as arguments two lists a,b and computes
the Euclidean distance between the two:
Check your function with these three values
distance([0,0], [1,1])
1.4142135623730951
distance([1,5], [2,2])
3.1622776601683795
distance([0,1,2], [2,3,4])
3.4641016151377544
In [ ]: