[python] How to write inline if statement for print?

I need to print some stuff only when a boolean variable is set to True. So, after looking at this, I tried with a simple example:

>>> a = 100
>>> b = True
>>> print a if b
  File "<stdin>", line 1
    print a if b
             ^
SyntaxError: invalid syntax  

Same thing if I write print a if b==True.

What am I missing here?

This question is related to python if-statement inline

The answer is


You're simply overcomplicating.

if b:
   print a

Since 2.5 you can use equivalent of Cā€™s ā€?:ā€ ternary conditional operator and the syntax is:

[on_true] if [expression] else [on_false]

So your example is fine, but you've to simply add else, like:

print a if b else ''

Well why don't you simply write:

if b:
    print a
else:
    print 'b is false'

You can use:

print (1==2 and "only if condition true" or "in case condition is false")

Just as well you can keep going like:

print 1==2 and "aa" or ((2==3) and "bb" or "cc")

Real world example:

>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
1 item found.
>>> count = 2
>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
2 items found.

The 'else' statement is mandatory. You can do stuff like this :

>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>> 

EDIT:

Or, depending of your needs, you may try:

>>> if b: print(a)

Try this . It might help you

a=100
b=True

if b:
   print a

For your case this works:

a = b or 0

Edit: How does this work?

In the question

b = True

So evaluating

b or 0

results in

True

which is assigned to a.

If b == False?, b or 0 would evaluate to the second operand 0 which would be assigned to a.


This can be done with string formatting. It works with the % notation as well as .format() and f-strings (new to 3.6)

print '%s' % (a if b else "")

or

print '{}'.format(a if b else "")

or

print(f'{a if b else ""}')

Inline if-else EXPRESSION must always contain else clause, e.g:

a = 1 if b else 0

If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands):

a = 1 if b else a

This piece of code leaves a unchanged when b turns to be False.


You always need an else in an inline if:

a = 1 if b else 0

But an easier way to do it would be a = int(b).


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

hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:

print([a for i in range(0,1) if b])

or using just those two variables:

print([a for a in range(a,a+1) if b])

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to inline

Java - Check Not Null/Empty else assign default value How can I display two div in one line via css inline property Send inline image in email How to pass event as argument to an inline event handler in JavaScript? Adding a stylesheet to asp.net (using Visual Studio 2010) inline if statement java, why is not working how to create inline style with :before and :after How to write inline if statement for print? Logo image and H1 heading on the same line CSS two div width 50% in one line with line break in file