Why use def instead of lambda? The chapter doesn't show it yet, but functions usually have bodies containing more than one line, which is not possible with a lambda-style definition. Here is a function to calculate the area of a triangle given the lengths of three sides a, b, and c.

1
2
3
4
5
def Heron(a,b,c):
  p = a + b + c
  h = p / 2.0
  sqa = h*(h-a)*(h-b)*(h-c)
  return sqa**0.5

Line 2 calculates p, the perimeter of the triangle, which is the sum of the three side lengths. Line 3 lets h be half the perimeter (careful to use a float). Line 4 is the heart of the calculation, part of the famous Heron's Forumula; the last line returns the square root of this quantity.

The same function could also have been written in one very long line, using a lambda-style definition. It should be clear from the example that by introducing names for certain expression evaluations clarifies the program. It's also more efficient to reuse a calculated value (like h) as is seen on line 4 above --- an inferior approach would be to recalculate this value each time it is used.

Important Warning

For Python to correctly interpret a function definition using the def statement, it is important that all the lines in the function be indented by the same number of spaces. Hence, this would be a syntax error:

1
2
3
def myfunction(x):
  y = 2**x - 1 
   return y

The syntax error is that the return statement is indented too far, in comparison to the line defining y. It is the first line in the function body that sets the standard for how far all the remaining lines need to be indented.

Nasty Surprise

One major annoyance about Python is that not all spacing in function bodies is treated equally. For instance, this example might well be a syntax error:

1
2
3
def myfunction(x):
         y = 2**x - 1 
         return y

Just looking at this, there does not appear to anything wrong. Both lines of the body seem indented by the same amount. However, what cannot be seen, is that one of the two indented lines uses only blanks (spaces), but the other line uses a tab character in addition to spaces. Actually, this would not be a problem if all computer systems treated the tab character to be equivalent to the same number of spaces. Sadly, this is not so.

Therefore, experienced Python programmers tend to be wary of tabs for indentation. Even if you never use tabs to indent, be aware that some text editors automatically make tabs in place of multiple blanks.