-1

print(45 and 2)

What is the mechanism behind the result of 2?

tadams
  • 1
  • 1
  • @cards It's an operator. Unclear why you brought up that it's also a keyword. – Kelly Bundy Aug 06 '22 at 19:53
  • @cards Neither `bool.__and__` nor `operator.add` represent the `and` operator. Due to its short-circuiting, it's not even representable as a function at all. Still unclear why you bring up keywords (and why you now proved that it's a keyword after I had already agreed that it is one). Do you think operators and keywords ate mutually exclusive? – Kelly Bundy Aug 06 '22 at 20:47
  • @juanpa.arrivillaga it was not my intention to raise such confusion. I will remove it – cards Aug 06 '22 at 21:00

2 Answers2

1

Based on the docs: https://docs.python.org/3/reference/expressions.html#and

"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."

Which basically means that you will always get 2 long as you keep the 45 (45 != 0). If you try print(0 and 2) you will get 0.

-1

The and operator checks the first operand. If it is truthy, the second operand is returned. Else, the first operand is returned. 45 is a non-zero integer, so it is truthy. Therefore, the second operand (2) is returned. The or operator works in a similar way.

https://realpython.com/python-and-operator/#using-pythons-and-operator-with-common-objects

Charlie
  • 54
  • 3