0

It is in the REPL

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

but

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

if not -1:
  print('yes') #prints nothing
  1. Why are positive integers not evaluated as True when using ==, but they are evaluated as True in if-statements? 2) Why are negative integers not evaluated as False when using ==, but they are also not evaluated as False in if-statements? What is the underlying rule, where is it written down?
erbcode
  • 11
  • @python_user I don't think it does. I don't see the answer to why the integer 2 is treated as True in if-statements, but it isn't when using ==. – erbcode May 07 '21 at 02:46
  • @python_user If all ints except 0 are truthy, then why does 3 == True evaluate to False? What you describe is what I would assume, coming from other languages, but it seems to be not consistently applied in Python. Or I'm missing something. – erbcode May 07 '21 at 02:47
  • If there's a difference between "Truthy" and "True", then this difference might explain my question, why == and if-statements behave differently, as in my examples. For now I don't know what that difference is though. – erbcode May 07 '21 at 02:49
  • 2
    @erbcode: A note: "Truthy" is rarely used in the official docs. But they do tend to use "True" (upper case T) to mean the actual constant that is true and has the numerical value of `1`, and "true" (lower case t) to mean "any value which, evaluated in a boolean context, is considered to be true". In practice, in Python, [you should almost never be comparing anything to `True` or `False`, you just use the implicit truth testing on the value](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) ("Don't compare boolean values to `True` or `False` using `==`"). – ShadowRanger May 07 '21 at 03:01
  • @erbcode there is a difference between evaluating to True in a boolean context, i.e. "truthiness" and being `==` to `True`. A conditional statement is *not* equivalent to `== True`, i.e for a given `condition` doing `if condition:` is not the same as `condition == True` it's the same as `bool(condition)` Furthermore, `bool` is a subclass of `int`, withe exactly two objects, `True` and `False` and `1 == True` and `0 == False` – juanpa.arrivillaga May 07 '21 at 03:20

1 Answers1

0

Every integer except 0 evaluates to True. The reason why your REPL was giving you different results than your if statements is because you aren't evaluating the same expression.

In your REPL you are asking is A equal to B. It's only true for False == 0 or True == 1. In your code you aren't doing a comparison. You are just checking that the variable is not something that could be considered "empty/nonexistent" (so to speak).

in short:

if a == True: and if a: are not the same thing.

If it helps, you can look at it like this:

if changeForADollar == myChange: vs if anyChangeAtAll:

OneMadGypsy
  • 4,640
  • 3
  • 10
  • 26