1

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'
1
  • 2
    Don't do that in real programs. Python ain't Ruby. :-) Commented Jan 12, 2014 at 18:23

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.