In python, 13 and 9 = what?

55 views Asked by At

Boolean operator 'and' returns True if both sides are True. Any number other than 0 is True. So python should return True for

13 and 19

But why does it return 19?

2

There are 2 answers

0
Talha Tayyab On

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

https://docs.python.org/3/reference/expressions.html#boolean-operations

in simple words if x is 0 it will return 0 else it will return y

0
tadman On

Boolean operator and returns True if both sides are True

This is the case if both sides are literally True as in True and True is, not surprisingly, True. For other values they are truthful or not, in which case, the last value in the chain is the value propagated.1

This is because you do not always want a boolean. test = x and "works!" or "nope" would be annoying if it returned a boolean and "ate" your string.

If you really want a boolean, you can cast with bool() which will convert from truthful to True and otherwise to False.


1 Many languages follow this tradition where the types have a truthful state, like Ruby (13 and 19 yields 19) and JavaScript (13 && 19 yields 19). If Python's behaviour differed significantly from that it would likely cause uproar as this is the expected behaviour.