isar
isar

Reputation: 1791

Shrink double if statement in Python

I cannot use the following statement because x and y may be defined as None:

if x*y > 9:
    pass

unsupported operand type(s) for *: 'NoneType' and 'NoneType'

So I should check first for the existence:

if x and y:
    if x*y > 9:
        pass

It seems a bit redundant. Is there a better way to achieve this?

Upvotes: 0

Views: 101

Answers (3)

ShadowRanger
ShadowRanger

Reputation: 155448

While if x and y and x * y > 9: is the most straightforward way, an alternative I find satisfying in an hard to define way is to use defaults for x and y when they're falsy:

if (x or 0) * (y or 0) > 9:

Since replacing either value with 0 makes the result 0, the test doesn't pass, as expected, when either value is None. This works because Python boolean and and or don't return True or False they return the last value evaluated (which will be truthy or falsy already). So if x is a non-zero number, you use x, otherwise you use 0, and same goes for y.

Upvotes: 2

cs95
cs95

Reputation: 402603

Following the EAFP (Easier to Ask Forgiveness than Permission) protocol, here's an alternative using try and except:

try:
   if x * y > 9:
       pass
except TypeError:
   pass

Upvotes: 3

Johannes
Johannes

Reputation: 3388

You can do:

if x and y and x*y > 9:
    pass

If you get even more checks it might be more comfortable to use all:

if all([
    x,
    y,
    x*y > 9,
    other conditions,...]):
    pass

Upvotes: 3

Related Questions