英文:
Why are most values True in Boolean?
问题
我在这篇文章中找到了关于Python布尔值的内容。我想知道为什么空数组、空字符串和数字0被视为假,而其他情况则不然。能有人为我解释一下吗?请注意:这不是另一篇文章的重复。
英文:
I found this article about python boolean at boolean. I was wondering why an empty array, string and the number 0 is false while the other ones are not. Can someone explain this to me? And do note: this is not a duplicate of another article.
答案1
得分: 0
在Python中,值可以是真值(truthy)或假值(falsy)。
""(空字符串),[](空列表),0都是假值。
当存在某种值时,它被视为真值。
它们与true和false不同,但当单独用作条件时,它们会被视为真假值。
许多编程语言都具有这个概念。
这只是一个简单的解释,有关此问题的详细答案,请参考https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false。
英文:
Values in python can be either truthy or falsy.
"", [], 0 are all falsy values.
When there is a value of some kind, it is considered truthy.
They are not the same as true and false but when used as a conditional by themselves they are treated as such.
A lot of programming languages have this concept.
This is just the simple explanation, the answers on this question https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false are far more detailed.
答案2
得分: 0
这是用于检查对象是否具有数据的简便方法。
def some_func(some_string: str):
if some_string: # 空字符串和None都会评估为False
# 对字符串进行一些操作
如果你想知道它为什么起作用,字符串和列表对象具有重载的__bool__
特殊函数。
英文:
This is for easy checking of whether an object has data.
def some_func(some_string: str):
if some_string: # both an empty string and None eval to false
# do something with string
If you are wondering why it works, the string and list object have an overloaded __bool__
special function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论