Python中的“真"和“假"

#39;True#39; and #39;False#39; in Python(Python中的“真和“假)
本文介绍了Python中的“真"和“假"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试运行这段代码:

path = '/bla/bla/bla'如果路径为真:打印真"别的:打印假"

它会打印 False.我认为 Python 将任何有价值的东西都视为 True.为什么会这样?

解决方案

来自 6.11.布尔运算:

<块引用><块引用>

在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值被解释为假:假、无、所有类型的数字零以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集合).所有其他值都被解释为 true.

我认为您误解的关键短语是解释为假"或解释为真".这并不意味着这些值中的任何一个都等于 True 或 False,甚至等于 True 或 False.

表达式 '/bla/bla/bla' 将在需要布尔表达式(如 if 语句中)的情况下被视为 true,但表达式 '/bla/bla/bla' 是 True 并且 '/bla/bla/bla' == True 将评估为 False 原因在 Ignacio 的回答中.

I tried running this piece of code:

path = '/bla/bla/bla'

if path is True:
    print "True"
else:
    print "False"

And it prints False. I thought Python treats anything with value as True. Why is this happening?

解决方案

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

这篇关于Python中的“真"和“假"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)