布尔查询

时间:2009-12-17 16:14:22

标签: python syntax boolean

如果:

x = 0
b = x==0

我打印它会打印'true'

但如果我这样做了:

  

x = 0
  b = x == 3

我印的是假的。 而不是打印错误我如何采用布尔值'b'来打印我想要的文本?

让我进一步解释:

bool = all(n > 0 for n in list) 

if bool != 'True':
    print 'a value is not greater than zero'

但它什么都不打印?

8 个答案:

答案 0 :(得分:6)

你的意思是这样的吗?

x = 0
if x != 3:
    print "x does not equal 3"

答案 1 :(得分:6)

我想以下可能有助于减轻你的一些困惑......

>>> 0==0
True
>>> 'True'
'True'
>>> (0==0) == 'True'
False
>>> (0==0) == True
True
>>>

答案 2 :(得分:4)

其他答案建议的if语句是可能的(您可以添加else子句来打印每种情况下特定的内容)。更直接的是if/else 运算符

print('equality' if b else 'diversity')

您也可以使用索引,因为False的int值为0,而True值为int值1:

print(['different', 'the same'][b])

但我发现它比if变体的可读性低一点。

答案 3 :(得分:3)

删除True附近的引号:

bool = all(n > 0 for n in list) 

if bool != True:
    print 'a value is not greater than zero'

或者,您也可以检查False:

bool = all(n > 0 for n in list) 

if bool == False:
    print 'a value is not greater than zero'

还有其他几种“快捷方式”的写法,但由于你是初学者,所以不要过分混淆主题。

答案 4 :(得分:2)

>>> x = 0
>>> if not x == 3: print 'x does not equal 3'
x does not equal 3

让我进一步解释:

>>> list = [-1, 1, 2, 3]
>>> if not all(n > 0 for n in list): print 'a value is not greater than zero'
a value is not greater than zero

# => or shorter ...
>>> if min(list) < 0: print 'a value is not greater than zero'
a value is not greater than zero

请注意list是内置函数,不应用作变量名。

>>> list
<type 'list'>
>>> list = [1, 2, "value not greater than 0"]
>>> list
[1, 2, "value not greater than 0"]
>>> del list
>>> list
<type 'list'>
...

答案 5 :(得分:2)

a = lambda b :("not true","true")[b == 3]
print a(3)
如果你想把它放在一个lambda

中,

会为你做

答案 6 :(得分:0)

你需要自己进行打印,正如大家在这里所建议的那样。

值得注意的是,某些语言(例如Scala,Ruby,Groovy)具有可以编写的语言功能:

x should be(3)

这将报告:

0 should be 3 but is not.

在Groovy中,使用Spock testing framework,您可以写:

def "my test":
  when: x = 0
  expect: x == 3

这会输出:

条件不满意:

x == 3
| |  |
0 |  3
 false

我不认为这可能在python中干净利落。

答案 7 :(得分:0)

>>> 'True' is not True
True

'True'是一个字符串

True是布尔值

除了巧合之外,他们彼此无关。字符串值恰好与布尔文字具有相同的字母。但那只是巧合。