1

Consider the Python commands:

>>> print 3%2 == 0
False
>>> print 3%2 == 1
True

The output is completely right. But I read somewhere that:

Any nonzero number is interpreted as true.

Why does print 2 and 4 return 4, rather than True?

>>> print 2 and 4 
4
Prune
  • 76,765
  • 14
  • 60
  • 81
Sigur
  • 355
  • 8
  • 19

1 Answers1

2

This is from the logical short-cuts that many languages take. The and operator in this case appears in the low-level code as if it were:

a = 2
b = 4
return b if a else a

... or

if not a:
    return a
else:
    return b

This works as expected with Boolean values. With other data types, the result is non-intuitive (until you get used to it).

Prune
  • 76,765
  • 14
  • 60
  • 81