What is Truthy and Falsy? How is it different from True and False?(什么是真假?它与真假有什么不同?)
问题描述
I just learned there are truthy and falsy values in python which are different from the normal True
and False
.
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?
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!")
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.
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.
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.
For example, an empty list ([]
) is considered "falsy", and a non-empty list (for example, [1]
) is considered "truthy".
See also this section of the documentation.
这篇关于什么是真假?它与真假有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是真假?它与真假有什么不同?
- 沿轴计算直方图 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01