如何在 Python 中使用布尔值?
问题描述
Python 是否真的包含布尔值?我知道你可以这样做:
Does Python actually contain a Boolean value? I know that you can do:
checker = 1
if checker:
#dostuff
但我很迂腐,喜欢在 Java 中看到布尔值.例如:
But I'm quite pedantic and enjoy seeing booleans in Java. For instance:
Boolean checker;
if (someDecision)
{
checker = true;
}
if(checker)
{
//some stuff
}
Python 中是否有布尔值之类的东西?我似乎在文档中找不到类似的东西.
Is there such a thing as a Boolean in Python? I can't seem to find anything like it in the documentation.
解决方案
checker = None
if some_decision:
checker = True
if checker:
# some stuff
更多信息:http://docs.python.org/library/functions.html#bool
您的代码也可以工作,因为必要时 1
会转换为 True
.实际上 Python 很久没有布尔类型了(就像在旧的 C 中一样),一些程序员仍然使用整数而不是布尔值.
Your code works too, since 1
is converted to True
when necessary.
Actually Python didn't have a boolean type for a long time (as in old C), and some programmers still use integers instead of booleans.
相关文章