[Tutor] cases with single if and an else clause

David bouncingcats at gmail.com
Mon Oct 4 20:28:54 EDT 2021


On Tue, 5 Oct 2021 at 11:14, Manprit Singh <manpritsinghece at gmail.com> wrote:

> So when i am going to write a function that returns the absolute value, i
> feel writing the function in the below given way is perfectly fine:
>
> def absolutevalue(num):
>     if num < 0:
>         return -num
>     return num
>
> Need your suggestions

I used to use this style because it feels like it does simplify and
perhaps makes the code more elegant.

However I have recently stopped doing this.

Functions and methods with more than one return statement
are harder to debug when used. They are more likely to need
external testing.

If there is just one return statement, then the return value can be
easily checked inside the function just before it returns.

If the function has more than one return statement then that
approach to debugging is not so easy.

In that situation, the return value would need to  be checked outside
the function in every place that the function is called, or checked
at more than one place inside the function.


More information about the Tutor mailing list