0

Im comparing two strings in an if statement, i expect them both to be False, but one is True.

See code example:

z = 'Test'
x = 'Test1234'

z and x == 'Test'
False

x and z == 'Test'
True

Why? It's not possible that im the first person to see this, but i can't find other threads. I think im using the wrong search words.

Thanks in advance.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Wobbel
  • 13
  • 1
  • Try `bool(x)` and you'll see that its True. `x and z == 'Test'` is the same as `True and True`. – tdelaney Aug 14 '21 at 19:12
  • `z and x == 'Test'` is the same as `z and (x == 'Test')`, not `(z and x) == 'Test'`, which you are mistakenly assuming would be equivalent to `z == 'Test' and x == 'Test'`. – chepner Aug 14 '21 at 19:13
  • Thanks, i get it now. Never knew operator precedence is a thing. https://docs.python.org/3/reference/expressions.html#operator-precedence – Wobbel Aug 14 '21 at 19:17
  • You probably did (`x + y*z` is the same as `x + (y*z)`, not `(x+y)*z`), but didn't realize that `and` and `==` are also binary operators. – chepner Aug 14 '21 at 19:19
  • try asking better questions. "the language is wrong and it is not possible that I made a mistake" is basically what you write. – Alex Aug 14 '21 at 19:37
  • I did not, I never said the language is wrong, I ran into something I had no previous knowledge of, I got helped by some friendly people. Show me where I did wrong and help others improve instead of pulling them down. – Wobbel Aug 15 '21 at 20:13

1 Answers1

0

Testing a non-boolean variable in an expression is evaluated as a boolean which for a string is True if the String is not None and is not an empty string; e.g. bool('test') = True; bool('') = False; bool(None) = False.

By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. See built-in types.

z = 'Test'
x = 'Test1234'

z and x == 'Test' # False
x and z == 'Test' # True

The expression x and z == 'Test' using operator precedence is evaluated as x and (z == 'Test') -- adding ()'s for clarity. The lone 'x' is evaluated as a boolean expression so is the same as bool(x) so the expression then becomes bool(x) and (z == 'Test').

This is evaluated as True and ('Test' == 'Test') or True and True or just True.

CodeMonkey
  • 22,825
  • 4
  • 35
  • 75