2

I tried to test empty string in Python (empty string should be "Falsy" as they write in: How to check if the string is empty?). However I used a little bit different syntax and get weird result in the following comparison:

not(''); # result: True

not('hello'); # result: False

not('hello') == False; # result: True

not('hello') == True; # result: True - how is this result possible? (False == True: result must be False)

Thank you for the answer!

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 2
    FWIW, the `()` and `;` are very superfluous… – deceze Oct 26 '20 at 10:40
  • 2
    `not` negates a boolean value. Empty strings are Falsy. not Falsy is True. - Non-empty strings are Thruthy, not Truthy is flase. `not` is no function - the ( ) is your doing. `not (hello) == True` is equal to `not ( "hello" == True)` – Patrick Artner Oct 26 '20 at 10:42

2 Answers2

2

The precedence here is not ('hello' == False). 'hello' equals neither True nor False, so both 'hello' == True and 'hello' == False are False, which is then negated by not.

>>> 'hello' == False
False
>>> 'hello' == True
False
>>> not ('hello' == True)
True

Truthiness isn't the same as being equal to True. A string can be truthy (i.e. you can decide whether it's more of a "yes" or a "no"), but at the same time not be equal to a boolean value (because a string is a string and a boolean is a boolean).

deceze
  • 510,633
  • 85
  • 743
  • 889
2

It's important to understand that not is an operator, not a function. The parenthesis do nothing for the expression, here's how it is read:

not('hello') == True
# is the same as
not 'hello' == True
# which is the same as
not ('hello' == True)
# which is equivalent to 
not False
# which is 
True

Which happens to evaluate to the same as the expression above (for the same reason that 'hello' == False is False.

The correct way of enforcing precedence with not would be to do

(not something) == True
cs95
  • 379,657
  • 97
  • 704
  • 746