Home > Mobile >  If num1 or num2 don‘t equal 0
If num1 or num2 don‘t equal 0

Time:10-25

I am a beginner in Python and I have a question: So if I have 2 different numbers, and if either one of these numbers equals to 0 then I should return the absolute value of the number that isn‘t 0. How can I do that? I knnow how to use abs(a or b) and how to return values but I have difficulty writing the algorithm for the return the value that isn‘t 0.

Hope someone can help me, would be greatful :)

CodePudding user response:

Why not return both if one equals 0?

CodePudding user response:

abs(a or b) already does pretty much exactly what you want. Basically, a or b behaves (for numbers) like a if a != 0 else b. If you want to return None if both are 0, you can add another or None after that, meaning "return None if the absolute value is zero".

>>> f = lambda a, b: abs(a or b) or None
>>> [f(0, -4), f(3, 0), f(4, -3), f(0, 0)]
[4, 3, 4, None]

If both numbers are != 0, this will just return the first value. If you want to return None in this case, too, you can use the slightly more cryptic None if a and b else abs(a or b) or None or not (a and b) and abs(a or b) or None if you want to stick with and and or.

CodePudding user response:

what happens when both numbers are not 0? or both are 0? in this example i just returned 0:

def func1(a,b):
    #if both  number are zero
    if a == b == 0:
        return 0
    elif a == 0:
        return abs(b)
    elif b == 0:
        return abs(a)
    #if both of the numbers are not zero
    else:
        return 0
  • Related