I was playing around on the command-line for Python 2.7.8, where I encountered this behavior:
>>> "902".isdigit() == True
True
>>> "902".isdigit(), "2".isdigit() == True
(True, True)
>>> "902".isdigit(), "2".isdigit() == True,True
(True, True, True)
>>> ("902".isdigit(), "2".isdigit()) == (True,True)
I found this surprising. I would have expected >>> "902".isdigit(), "2".isdigit() == True,True to simply return True as if I had surrounded both expressions in parentheses to make them into tuples. Why does Python return this tuple of booleans, rather than a single one? What boolean comparisons does this tuple represent?
Because:
"902".isdigit(), "2".isdigit() == True,True
is interpreted as:
("902".isdigit(), ("2".isdigit() == True), True)
Note that you shouldn't test booleans with ==; a more pythonic way to write the test is:
"902".isdigit() and "2".isdigit()
To add to jonrsharpe's answer:
The reason it is interpreted this way is because the Python parser has no way to determine whether:
"902".isdigit(), "2".isdigit() == True, True
was meant to be:
("902".isdigit(), ("2".isdigit() == True), True)
or:
("902".isdigit(), "2".isdigit()) == (True, True)
Basically there is no way to (from a grammar perspective) to determine this without using explicit parentheses.
See: Full Grammar Specification (but you'd need some background in BNF/EBNF grammars).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With