2

我正在使用python2.7。,如果我在打印语句中删除,则以下代码有效。但这会在不同的行中打印值。if-statement如果可能的话,我想用内联打印在同一行。

这是我所拥有的:

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)

它引发以下语法错误:

File "binary.py", line 6
    print 1, if x&i else 0
              ^
SyntaxError: invalid syntax
4

4 回答 4

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

binary(127)
于 2013-10-29T18:50:11.480 回答
2

把逗号放在最后

print 1 if x&i else 0,

您正在使用形式为 的条件表达式,true_expr if condition_expr else false_expr并且( )之前的部分是该表达式的一部分。您正在打印该表达式的结果。iftrue_expr

于 2013-10-29T18:50:21.740 回答
1

正如其他答案所述,将逗号放在行print解决您的问题。

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.

于 2013-10-29T19:05:18.993 回答
0
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]

你甚至可以使用,

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]
于 2013-10-29T19:00:57.937 回答