[Tutor] cases with single if and an else clause
Manprit Singh
manpritsinghece at gmail.com
Mon Oct 4 21:13:02 EDT 2021
Dear sir,
Yes I too feel a single return instead of multiple return statements should
be preferred :
I will not talk about using conditional expression a if c else b because it
can be used in simple cases only . When I have an if clause with multiple
statements I can't use it .
Regards
Manprit Singh
On Tue, Oct 5, 2021 at 5:42 AM Manprit Singh <manpritsinghece at gmail.com>
wrote:
> Dear Sir,
>
> Take an example of finding absolute value of a number without using
> builtin abs()
> it will be written simply as :
>
> num = int(input("Enter a number"))
> if num < 0:
> print(-num)
> else:
> print(num)
>
> This example involves an if clause and an else clause.
> 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
>
> Here the else clause is not used:
> 1) because when the number is negative then only return -num inside the
> if clause of the function will execute and it will return a positive
> number, after that return num will not execute.
> 2) If the number is a positive number then return -num inside the if
> clause will not execute because num < 0 is False. return num will return
> the same number.
>
> Need your suggestions
> Regards
> Manprit Singh
>
>
More information about the Tutor
mailing list