[Tutor] cases with single if and an else clause

Manprit Singh manpritsinghece at gmail.com
Mon Oct 4 20:12:44 EDT 2021


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