1

Is there method by using python if/else (ternary_operator) to achieve this function:

flag = True # or False
if flag:
    print 'abc'
else:
    pass

I tried to using:

print 'abc' if flag else ''

But a blank line will be print if the flag == False. Because:

print 'abc' if flag else '' == print ('abc' if flag else '')

Is there any way can make print nothing if flag == False without using ;?

Thanks in advance.


By the way, I'v tried using lambda, but it wasn't successful, here my code:

a = lambda x: x if False else None
print a(1)

Result:

>> python a.py
None
4

3 回答 3

3

Why not just:

if flag:
    print "abc"
else:
    # do something else

?

于 2013-08-22T09:24:54.477 回答
3

In Python 2.X print is a statement while in 3.X print is a function.

You can do from __future__ import print_function and print will now be a function. You can then do print("abc") if condition else None if you want to print in an expression. Note that the value of the expression is always None, but it may or may not print "abc" depending on the value of condition.

You may want to reconsider your programming style. It can be confusing with side-effects, like printing, happening in expressions. Furthermore, Python isn't ideal for functional programming, in my opinion, for a number of reasons. For example:

  • There are no proper tail calls so you would easily get stack overflows (or max recursion depth errors).
  • You cannot have statements in lambda-expressions. This includes yield statements that otherwise could be used to mitigate the lack of tail calls.
于 2013-08-22T09:34:16.840 回答
0
from __future__ import print_function
print('abc') if flag else None
于 2013-08-22T09:41:02.803 回答