[Tutor] cases with single if and an else clause

Leam Hall leamhall at gmail.com
Mon Oct 4 20:37:28 EDT 2021


On 10/4/21 7:28 PM, David wrote:
> 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.

You could also use a ternary statement. They can be easy-ish to read for simple cases.

-- 
Systems Programmer         (reuel.net/resume)
Scribe: The Domici War     (domiciwar.net)
General Ne'er-do-well      (github.com/LeamHall)


More information about the Tutor mailing list