Simple recursive sum function | what's the cause of the weird behaviour?
Terry Reedy
tjreedy at udel.edu
Sat Jul 6 14:47:27 EDT 2013
On 7/6/2013 8:37 AM, Russel Walker wrote:
> I know this is simple but I've been starring at it for half an hour and trying all sorts of things in the interpreter but I just can't see where it's wrong.
>
> def supersum(sequence, start=0):
> result = start
> for item in sequence:
> try:
> result += supersum(item, start)
> except:
Bare except statements cover up too many sins. I and others *strongly*
recommend that you only catch what you *know* you actually want to (see
below).
> result += item
> return result
I recommend that you start with at least one test case, and with an edge
case at that. If you cannot bring yourself to do it before writing a
draft of the function code, do it immediately after and run. If you do
not want to use a framework, use assert.
assert supersum([]) == 0
assert supersum([], []) == []
Do the asserts match your intention? The tests amount to a specification
by example. Any 'kind' of input that is not tested is not guaranteed to
work.
Back to the except clause: only add try..except xxx when needed to pass
a test.
--
Terry Jan Reedy
More information about the Python-list
mailing list