【问题标题】:Python type conversion int <=> bool [duplicate]Python 类型转换 int <=> bool [重复]
【发布时间】:2021-07-29 08:54:51
【问题描述】:

它在 REPL 中

>>> 1 == True
True
>>> 2 == True
False
>>> 3 == True
False
>>> -1 == False
False

但是

if 3:
  print('yes') #prints yes

if not -1:
  print('yes') #prints nothing
  1. 为什么在使用 == 时正整数不被评估为 True,但在 if 语句中却被评估为 True? 2) 为什么负整数在使用 == 时不会被评估为 False,但在 if 语句中它们也不会被评估为 False? 基本规则是什么,写在哪里?

【问题讨论】:

  • TLDR;除了0 之外的所有整数都是真值,0 是假值
  • @python_user 我认为不会。我看不到为什么整数 2 在 if 语句中被视为 True 的答案,但在使用 == 时却不是。
  • @python_user 如果除 0 之外的所有整数都是真实的,那么为什么 3 == True 评估为 False?你所描述的是我所假设的,来自其他语言,但它似乎并没有在 Python 中得到一致的应用。或者我错过了什么。
  • 我链接的问题的答案中的文档链接解释了这一点,请点击“真值测试”测试链接
  • @erbcode:注意:官方文档中很少使用“Truthy”。但他们确实倾向于使用“True”(大写 T)来表示真实的实际常数,其数值为 1,而“true”(小写 t)表示“任何在布尔上下文,被认为是真实的”。实际上,在 Python 中,you should almost never be comparing anything to True or False, you just use the implicit truth testing on the value(“不要使用 == 将布尔值与 TrueFalse 进行比较”)。

标签: python types type-conversion boolean


【解决方案1】:

除 0 以外的每个整数都计算为 True。你的 REPL 给你的结果与你的 if 语句不同的原因是因为你没有评估相同的表达式。

在您的 REPL 中,您是在询问 is A equal to B。仅适用于 False == 0True == 1。在您的代码中,您没有进行比较。您只是在检查该变量是否可以被视为“空/不存在”(可以这么说)。

简而言之:

if a == True:if a: 不是一回事。

如果有帮助,可以这样看:

if changeForADollar == myChange: 对比 if anyChangeAtAll:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2014-01-07
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多