简体   繁体   中英

how to print in single line with an inline if else statement in python 2.7

I am using python2.7. The below code works if I remove , in the print statement. but that prints the values in different lines. I want to print in same line with an inline if-statement if possible.

Here is what I have:

def binary(x):

   for i in [128,64,32,16,8,4,2,1]:
      #if x&i: print 1,
      #else: print 0,
       print 1, if x&i else 0

binary(127)

It throws the following syntax error:

File "binary.py", line 6
    print 1, if x&i else 0
              ^
SyntaxError: invalid syntax
def binary(x):
   for i in [128,64,32,16,8,4,2,1]:
       print 1 if x&i else 0,

binary(127)

Put the comma at the end :

print 1 if x&i else 0,

You are using a conditional expression, of the form true_expr if condition_expr else false_expr , and the part before the if ( true_expr ) is part of that expression. you are printing the outcome of that expression.

As the other answers have stated, putting the comma at the end of the print line will solve your problem.

However, there is a far easier way to achieve what you want if you use format :

>>> def binary(x):
...     return " ".join(format(n, "08b"))
...
>>> print binary(127)
0 1 1 1 1 1 1 1
>>>

This method does the same thing as your function, only it is a lot more concise and efficient.

x = 127

>>> [1 if ele & x else 0 for ele in [128, 64, 32, 16, 8, 4, 2, 1]]
[0, 1, 1, 1, 1, 1, 1, 1]

You can even use,

x = 127

>>> [[0,1][bool(ele & x)] for ele in [128, 64, 32, 16, 8, 4, 2, 1]]
[0, 1, 1, 1, 1, 1, 1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM