0

Trying to understand how AND statement works inside abs(numbers) function.

Calling print(abs(21-22 and 9-4 and 11-8))

This would always give me whatever the last expression is. In this case it calculates 11-8, so it prints 3. Why other expressions are not in the output and no error as well?

Remi
  • 42
  • 5

2 Answers2

5

The fact that the expression is inside an abs call doesn't change the way that it's interpreted:

>>> 21-22 and 9-4 and 11-8
3

which is of course the same as:

>>> -1 and 5 and 3
3

An and evaluates the "truthiness" of each operand. If either of them is "falsey", that one is returned; otherwise the last one is returned.

All int values except 0 are "truthy", so the only time you'll get something other than the last value from an and of ints is if one of them is zero:

>>> -1 and 0 and 3
0
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Yup. [The python docs explicitly state that](https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not) `x and y` is equivalent to 'if x is false, then x, else y' – bisen2 Jun 01 '20 at 19:14
2

and is a logical operator, it will return True if both the operands of the operator are true.

I believe the comma does what you expected to do in this case:

print(abs(21-22),abs(9-4),abs(11-8))
Red
  • 26,798
  • 7
  • 36
  • 58