[Tutor] cases with single if and an else clause

Alan Gauld alan.gauld at yahoo.co.uk
Tue Oct 5 03:34:04 EDT 2021


On 05/10/2021 01:12, Manprit Singh wrote:

> def absolutevalue(num):
>     if num < 0:
>         return -num
>     return num
> 
> Here the else clause is not used:

Strict structural programming rules say there should
be a single return statement from a function. So
setting a value in the if/else and returning that
at the end is "better"

In practice there can be valid arguments for returning
as soon as possible, especially in a complex function.
The alternative often requires setting flags and
adding lots of unnecessary if/else tests which
complicate an already complex function further.
In that case it's easier for everyone if you just
exit as soon as possible.

As ever there are no hard and fast rules, use what
makes the code easiest to read, test and debug.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list