Python 什么是真和假?它与 True 和 False 有何不同?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39983695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:01:56  来源:igfitidea点击:

What is Truthy and Falsy? How is it different from True and False?

python

提问by Patrick Haugh

I just came to know there are Truthyand Falsyvalues in python which are different from the normal Trueand False?

我刚开始知道python中有TruthyFalsy值,它们与正常值TrueFalse?

Can someone please explain in depth what truthyand falsyvalues are?

是否有人可以深入解释什么truthyfalsy值?

Where should I use them?

我应该在哪里使用它们?

What is the difference between truthyand Truevalues and falsyand Falsevalues ?

是什么区别truthyTrue值和falsyFalse价值观?

采纳答案by B. Eckles

As the comments described, it just refers to values which are evaluated to True or False.

正如评论所描述的,它只是指被评估为 True 或 False 的值。

For instance, to see if a list is not empty, instead of checking like this:

例如,要查看列表是否为空,而不是像这样检查:

if len(my_list) != 0:
   print("Not empty!")

You can simply do this:

你可以简单地这样做:

if my_list:
   print("Not empty!")

This is because some values, such as empty lists, are considered False when evaluated for a boolean value. Non-empty lists are True.

这是因为在评估布尔值时,某些值(例如空列表)被视为 False。非空列表为 True。

Similarly for the integer 0, the empty string "", and so on, for False, and non-zero integers, non-empty strings, and so on, for True.

类似地,对于整数 0、空字符串 "" 等,对于 False,以及非零整数、非空字符串等,对于 True。

The idea of terms like "truthy" and "falsy" simply refer to those values which are considered True in cases like those described above, and those which are considered False.

“truthy”和“falsy”等术语的概念只是指那些在上述情况下被认为是真值的值,以及那些被认为是假值的值。

For example, an empty list ([]) is considered "falsy", and a non-empty list (for example, [1]) is considered "truthy".

例如,空列表 ( []) 被认为是“假的”,而非空列表(例如,[1])被认为是“真实的”。

See also this section of the documentation.

另请参阅文档的这一部分

回答by Patrick Haugh

All values are considered "truthy" except for the following, which are "falsy":

所有值都被认为是“真实的”,除了以下是“虚假的”:

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • []- an empty list
  • {}- an empty dict
  • ()- an empty tuple
  • ''- an empty str
  • b''- an empty bytes
  • set()- an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__()returns False
    • obj.__len__()returns 0
  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • []- 一个空的 list
  • {}- 一个空的 dict
  • ()- 一个空的 tuple
  • ''- 一个空的 str
  • b''- 一个空的 bytes
  • set()- 一个空的 set
  • 一个空的range,比如range(0)
  • 对象
    • obj.__bool__()返回 False
    • obj.__len__()返回 0

A "truthy" value will satisfy the check performed by ifor whilestatements. We use "truthy" and "falsy" to differentiate from the boolvalues Trueand False.

“真实”值将满足由iforwhile语句执行的检查。我们使用“truthy”和“falsy”来区bool分值TrueFalse

Truth Value Testing

真值测试

回答by adi1ya

Truthy values refer to the objects used in a boolean context and not so much the boolean value that returns true or false.Take these as an example:

真值指的是在布尔上下文中使用的对象,而不是返回真或假的布尔值。以这些为例:

>>> bool([])
False
>>> bool([1])
True
>>> bool('')
False
>>> bool('hello')
True

回答by user1767754

Python determines the truthiness by applying bool()to the type, which returns Trueor Falsewhich is used in an expression like ifor while.

Python 通过应用bool()类型来确定真实性,该类型返回TrueFalse用于像ifor 之类的表达式中while

Here is an example for a custom class Vector2dand it's instance returning Falsewhen the magnitude (lenght of a vector) is 0, otherwise True.

这是自定义类的示例Vector2d,它的实例False在大小(向量的长度)为 0 时返回,否则返回True.

import math
class Vector2d(object):
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def __abs__(self):
        return math.hypot(self.x, self.y)

    def __bool__(self):
        return bool(abs(self))

a = Vector2d(0,0)
print(bool(a))        #False
b = Vector2d(10,0)    
print(bool(b))        #True

Note:If we wouldn't have defined __bool__it would always return True, as instances of a user-defined class are considered truthy by default.

注意:如果我们没有定义__bool__它总是会返回 True,因为默认情况下用户定义的类的实例被认为是真实的。

Example from the book: "Fluent in Python, clear, concise and effective programming"

书中的例子:“精通Python,清晰、简洁、有效的编程”

回答by jlaurens

Where should you use Truthy or Falsy values ? These are syntactic sugar, so you can always avoid them, but using them can make your code more readable and make you more efficient. Moreover, you will find them in many code examples, whether in python or not, because it is considered good practice.

你应该在哪里使用Truthy 或Falsy 值?这些是语法糖,所以你总是可以避免它们,但使用它们可以使你的代码更具可读性,让你更有效率。此外,您会在许多代码示例中找到它们,无论是否在 python 中,因为它被认为是很好的做法。

As mentioned in the other answers, you can use them in if tests and while loops. Here are two other examples in python 3 with default values combined with or, sbeing a string variable. You will extend to similar situations as well.

正如其他答案中提到的,您可以在 if 测试和 while 循环中使用它们。这是 python 3 中的另外两个示例,默认值与 结合ors是一个字符串变量。你也会扩展到类似的情况。

Without truthy

不真实

if len(s) > 0:
    print(s)
else:
    print('Default value')

with truthy it is more concise:

使用truthy更简洁:

print(s or 'Default value')

In python 3.8, we can take advantage of the assignment expression :=

在python 3.8中,我们可以利用赋值表达式 :=

without truthy

不真实

if len(s) == 0:
    s = 'Default value'
do_something(s)

with truthy it is shorter too

使用truthy它也更短

s or (s := 'Default value')
do_something(s)

or even shorter,

甚至更短,

do_something(s or (s := 'Default value'))

Without the assignment expression, one can do

没有赋值表达式,你可以做

s = s or 'Default value'
do_something(s)

but not shorter. Some people find the s =...line unsatisfactory because it corresponds to

但不会更短。有些人觉得这s =...条线不令人满意,因为它对应于

if len(s)>0:
    s = s # HERE is an extra useless assignment
else:
    s = "Default value"

nevertheless you can adhere to this coding style if you feel comfortable with it.

不过,如果您对它感到满意,则可以坚持这种编码风格。

回答by MLee

while 0:
    print("Inside the loop.", counter)
    counter -= 1
print("Outside the loop.", counter)

If you ran this loop you would see that while 0: = while false:

如果你运行这个循环,你会看到 while 0: = while false:

0 is considered as a falsy

0 被认为是假的

回答by Venkatesh

Falsy means something empty like empty list,tuple, as any datatype having empty values or None. Truthy means : Except are Truthy

Falsy 表示空列表、元组等空值,因为任何具有空值或 None 的数据类型。真实的意思是:除了真实