P0 = [2,1] P1 = [8,1] P2 = [5,5]
v1 = np.array(P1) - np.array(P0) v2 = np.array(P2) - np.array(P0) v1_cross_v2 = [0, 0, v1[0] * v2[1] - v2[0] * v1[1]] A = np.linalg.norm(v1_cross_v2) A_tri = A/2
A_tri
12.0
def area_tri(P0,P1,P2): v1 = np.array(P1) - np.array(P0) v2 = np.array(P2) - np.array(P0) v1_cross_v2 = [0, 0, v1[0] * v2[1] - v2[0] * v1[1]] A = np.linalg.norm(v1_cross_v2) A_tri = A/2 return A_tri
def
and is followed
by the function name, here area_tri
. Then comes some
arguments in parentheses, (
)
, here
P0
, P1
, and P2
. Finally,
the first line of the function declaration ends with :
.
The following code lines will belong to the function as long as they
are indented (by some amount, typically 4 spacings). The function may
contain a statement with a return
keyword followed by
a single or a list of variables.
def
-:
-indentation-return
syntax is called by supplying values (or variables) as arguments. For
the first triangle we have:
area_tri([2,1],[8,1],[5,5])
12.0
A_tri
as this is
what was written after return
in the function declaration.
area_tri([4,1],[2,5],[8,3])
10.0
Choose which booklet to go to: