[Tutor] cases with single if and an else clause

Manprit Singh manpritsinghece at gmail.com
Mon Oct 4 21:52:24 EDT 2021


Dear sir,

Now there is one more problem ,  Kindly loom at below written functions :

def grade(percent):
    if percent < 0 or percent > 100:
        ans = "Invalid Input"
    elif percent >= 90:
        ans = "A"
    elif percent >= 70:
        ans = "B"
    elif percent >= 60:
        ans = "C"
    else:
        ans =  "Fail"
    return ans

ans = grade(71)
print(ans)    # that returns "B" which is the right answer
This is a function that returns the grade of the student according to marks
. In this function i have made a single return statement,  This can be
written with multiple return statements as below:

def grade(percent):
    if percent < 0 or percent > 100:    # By combining with or, expression
will be true if any subexpression is true
        return "Invalid Input"
    elif percent >= 90:
        return  "A"
    elif percent >= 70:
        return "B"
    elif percent >= 60:
        return "C"
    else:
        return "Fail"

ans = grade(71)
print(ans)   # that prints "B" the right answer.

Which way should be preferred ?
kindly guide

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