Frage

Ternary is easy to use when checking for none-y variables.

>>> x = None
>>> y = 2 if x else 3
>>> y
3

If i want to check for none-ity before i return is there a ternary equivalence to:

def foobar(x):
  if x:
    return x*x
  else:
    print 'x is None-y'

Is there something that looks like:

def foobar(x):
  return x*x if x else print 'x is None-y'
War es hilfreich?

Lösung

Use print as a function, import it from __future__ in Python2:

>>> from __future__ import print_function
>>> def foobar(x):
      return x*x if x else print ('x is None-y')
... 
>>> foobar(0)
x is None-y
>>> foobar(2)
4

Another alternative will be to use sys.stdout:

>>> import sys
>>> def foobar(x):
      return x*x if x else sys.stdout.write('x is None-y\n')
... 
>>> foobar(0)
x is None-y
>>> foobar(2)
4

Andere Tipps

In Python 2, print is a statement and cannot be used within a conditional expression.

In Python 3, print is a function and therefore can be used like this (with parentheses). However, I'd argue that this is poor style since print() is called for its side effect rather than return value.

I'd stick with the original if (possibly adding an explicit return to the else for clarity).

Finally, your code claims that 0 is None-y, which is kinda strange in this context.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top