How to write inline if statement for print?

974,160

Solution 1

Python does not have a trailing if statement.

There are two kinds of if in Python:

  1. if statement:

    if condition: statement
    if condition:
        block
    
  2. if expression (introduced in Python 2.5)

    expression_if_true if condition else expression_if_false
    

And note, that both print a and b = a are statements. Only the a part is an expression. So if you write

print a if b else 0

it means

print (a if b else 0)

and similarly when you write

x = a if b else 0

it means

x = (a if b else 0)

Now what would it print/assign if there was no else clause? The print/assignment is still there.

And note, that if you don't want it to be there, you can always write the regular if statement on a single line, though it's less readable and there is really no reason to avoid the two-line variant.

Solution 2

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.

Solution 3

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)

Solution 4

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

Solution 5

You can write an inline ternary operator like so:

sure = True

# inline operator
is_true = 'yes' if sure else 'no'

# print the outcome
print(is_true)
Share:
974,160
Ricky Robinson
Author by

Ricky Robinson

Updated on July 21, 2022

Comments

  • Ricky Robinson
    Ricky Robinson almost 2 years

    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?

  • Ricky Robinson
    Ricky Robinson almost 12 years
    Oh. But what if I don't want anything to happen in the else branch? I need something like: print a if b
  • aneroid
    aneroid almost 12 years
    else a would be better then else 0
  • jamylak
    jamylak almost 12 years
    if b: print a Just need a simple if in that case
  • Rostyslav Dzinko
    Rostyslav Dzinko almost 12 years
    @RickyRobinson, if you want nothing to be changed - just assign old 'a' value: a = 1 if b else a
  • Jan Hudec
    Jan Hudec almost 12 years
    -1: Easier. And totally unreadable. And not what the asker wanted anyway.
  • Jan Hudec
    Jan Hudec almost 12 years
    Fixing the answer, because it's almost good if it wasn't for the word 'statement' which made it totally bad. The gist of the question is that it's not a statement.
  • Ricky Robinson
    Ricky Robinson about 11 years
    Thanks. The thing here is that print "" will still print something: a blank line.
  • Ricky Robinson
    Ricky Robinson about 11 years
    Of course that's the easiest option. I think that at the time (august 2012) I wanted to do something like: if DEBUG: print something
  • Ricky Robinson
    Ricky Robinson about 11 years
    Thanks. The end argumnt in print only appears in Python 3.x, right?
  • Noelkd
    Noelkd about 11 years
    aye, I'm more of a 2.7 man hence the from __future__ import print_function
  • glglgl
    glglgl almost 11 years
    ITYM a = int(bool(b)).
  • Val
    Val over 10 years
    I think that if condition: statement does not work in case of multiline statements.
  • sancho.s ReinstateMonicaCellio
    sancho.s ReinstateMonicaCellio over 10 years
    Duplicated answer? See that by SkariaArun, and also a comment.
  • sancho.s ReinstateMonicaCellio
    sancho.s ReinstateMonicaCellio over 10 years
    +1-1: Good for pointing out that the else expression is mandatory, but not ok for not providing the answer for the case in question: print "nothing" (something along the lines of "" or None, see details in other answers).
  • Eduardo
    Eduardo over 10 years
    Yes, but you don't need to use if, simply use boolean logic like I show below in my examples.
  • Eduardo
    Eduardo over 10 years
    Yes, but you don't need to use if, simply use boolean logic like I show below in my examples.
  • mbomb007
    mbomb007 over 8 years
    @JanHudec If Python doesn't have a trailing if, then why does this work: print [i for i in range(10) if i%2]? I wish they'd allow it outside of comprehensions...
  • Jan Hudec
    Jan Hudec over 8 years
    @mbomb007, that is not a trailing if statement either. It is simply part of the list (or generator) comprehension. Note that the thing before the if is not a statement, it is two expressions with for between them.
  • yoniLavi
    yoniLavi over 8 years
    Note that the print '' will still print a newline, which is avoided in the answer by Noelkd.
  • Alexander von Wernherr
    Alexander von Wernherr over 7 years
    Thanks, that helped me a lot. Would print ("a " + (id+ "" if id else "") + " b") be considered a good solution if I want to ad an "id" to a string if id is not none?
  • Jan Hudec
    Jan Hudec over 7 years
    @AlexandervonWernherr, yes, that sounds reasonable.
  • melpomene
    melpomene over 7 years
    This has nothing to do with formatting; you could just do print a if b else "". Which is exactly what Noelkd's answer does.
  • Karan Singh
    Karan Singh about 7 years
    Can anybody help me understand why b=a is a statement and not an expression?
  • Jan Hudec
    Jan Hudec about 7 years
    @KaranSingh, because python grammar defines it that way.
  • m3nda
    m3nda about 7 years
    @melpomene but printing "" ads a new line, that can be avoided using print "", (colon) for Python2, and using print("", end="") for Python3.
  • Apurva Kunkulol
    Apurva Kunkulol almost 7 years
    can the else part be omitted? To write like print a if a
  • Jan Hudec
    Jan Hudec almost 7 years
    @ApurvaKunkulol, would you be so kind and read the question again? It shows precisely that syntax—and the syntax error it produces. Ergo, no, it can't.
  • Gavin Palmer
    Gavin Palmer over 6 years
    I ended up doing something like print("reason why I do nothing") if not_good_reason else do_something()
  • Charles Jaimet
    Charles Jaimet about 6 years
    It's worth noting that 'else' is required. It would be convenient to simply use 'if' in some cases (e.g. c += a if b), but alas.
  • CodeMantle
    CodeMantle over 5 years
    @KaranSingh, the a=b not being an expression is a helpful syntactic device in Python, and learnt from other languages (C) where assignment and testing could be mingled and mixed up.