If you don't want to from __future__ import print_function
you can do the following:
a = 100
b = True
print a if b else "", # Note the comma!
print "see no new line"
Which prints:
100 see no new line
If you're not aversed to from __future__ import print_function
or are using python 3 or later:
from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")
Adding the else is the only change you need to make to make your code syntactically correct, you need the else for the conditional expression (the "in line if else blocks")
The reason I didn't use None
or 0
like others in the thread have used, is because using None/0
would cause the program to print None
or print 0
in the cases where b
is False
.
If you want to read about this topic I've included a link to the release notes for the patch that this feature was added to Python.
The 'pattern' above is very similar to the pattern shown in PEP 308:
This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C's c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the 'common case' and one value is an 'exceptional case', used only on rarer occasions when the condition isn't met. The conditional syntax makes this pattern a bit more obvious:
contents = ((doc + '\n') if doc else '')
So I think overall this is a reasonable way of approching it but you can't argue with the simplicity of:
if logging: print data