Search code examples
pythonif-statementreturnfunctionternary

Can ternary work with return and print in python?


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'

Solution

  • 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