There is a boolean variable. I need to check its value and, depending on this, change the arguments passed to print.

amusingsize = True print ("Amusing size: %s") %(if(amusingsize) "GB" else "MB") 

How can you do this? I do not want to fence unnecessary if / else blocks.

  • print ("OK" if True else "NO!") go? - BOPOH
  • You have a terrible code style. Do not write like this, it does not add an understanding of what you want to receive. - prospero78su
  • print "Amusing size: " . (amusingsize ? "GB" : "MB") print "Amusing size: " . (amusingsize ? "GB" : "MB") but you have Python, so suffer without comfortable ternary C-like operators) - wirtwelt

4 answers 4

 amusingsize = True print ("Amusing size: %s" %("GB" if amusingsize else "MB")) 
  • And why didn't my option work? What did I do wrong? - Dmitry Bubnenkov
  • Well, the python syntax is like that - it is impossible to write as horrible) - BOPOH
  • Something I can not understand why if MB I stand as True, then prints GB and vice versa. - Dmitry Bubnenkov
  • one
    "GB" if amusingsize else "MB" Equivalent: if amusingsize: print ("GB") else: print ("MB") - DmitriyM

Here is another "hacker" option

 print "Amusing size: %s" % ("MB", "GB")[amusingsize] 
  • This can be used only if it is well known that the expression (amusingsize in this case) returns False , True 0 , 1 , i.e. "+-"[n < 0] is brief and understandable, but in general, many of the variables that are used with if are not themselves boolean. The closer equivalent for a if x else b is [b, a][bool(x)] . - jfs

In fact, everything is simple:
for one-liners with conditions there are strictly defined rules (it is one) and it looks like a free translation like this:

 "значения для True" IF statement ELSE "значения для False" 

But at the same time, each such one-liner can be a value for True / False in another one-liner. For example, here is an unreadable piece of code:

 ['FizzBuzz' if i%3+i%5==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i for i in xrange(1, 16)] 
     amusingsize = True print ("Amusing size: %s") %("GB" if amusingsize else "MB")