什么是真和假?它与 True 和 False 有何不同? [英] What is Truthy and Falsy? How is it different from True and False?

查看:79
本文介绍了什么是真和假?它与 True 和 False 有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解到 python 中有 truthyfalsy 值,它们与正常的 TrueFalse 不同>.

I just learned there are truthy and falsy values in python which are different from the normal True and False.

有人可以深入解释一下什么是truefalsy 值吗?我应该在哪里使用它们?truthyTrue 值与 falsyFalse 值之间有什么区别?

Can someone please explain in depth what truthy and falsy values are? Where should I use them? What is the difference between truthy and True values and falsy and False values?

推荐答案

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

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

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

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

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

你可以简单地这样做:

if my_list:
   print("Not empty!")

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

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

类似地,对于整数 0、空字符串 "" 等,对于 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.

truthy"和falsy"等术语的概念仅指在上述情况下被视为真的值,以及在上述情况下被视为假的值.

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.

例如,空列表([])被认为是falsy",非空列表(例如,[1])被认为是真实".

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

另请参阅文档的这一部分.

这篇关于什么是真和假?它与 True 和 False 有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆