0

What is the logic behind below operations?

and operator prints only second operand.

>>> print(4 and 3)
3
>>> print(3 and 4)
4
>>> print(1 and True)
True
>>> print(True and 1)
1
>>> print(True and "hello")
hello

or operator prints only first operand.

>>> print(4 or 3)
4
>>> print(3 or 4)
3
>>> print(1 or True)
1
>>> print(True or 1)
True
>>> print(True or "hello")
True
wjandrea
  • 28,235
  • 9
  • 60
  • 81
abinjacob
  • 31
  • 6
  • 2
    As a counter example, try running `print(False and "hello")` or `print(False or "hello")` – Holloway Nov 07 '22 at 17:46
  • 1
    All of the values you've used in your examples are considered True. – Mark Ransom Nov 07 '22 at 17:48
  • 3
    According to [this answer](https://stackoverflow.com/a/68896273/669576), _"Python's logical operators are specifically designed to return the result of the last object evaluated:"_. `and` evaluates both if first is `True` and `or` only evaluates first if it is `True`. – 001 Nov 07 '22 at 17:50
  • 1
    There are really nice ways to take advantage of this behavior. `or` can be used to provide a "default" alternative to a potentially falsey value, e.g. `name = name or "J. Doe"`. `and` can be used to conditionally traverse a potentially `None`/empty object reference, e.g. `do_thing = config and config.do_thing`. – Samwise Nov 07 '22 at 17:55
  • This line helped me to understand it straight "The Boolean operators {and} and {or} are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined." Thanks to @JohnnyMopp Cheers!! – – abinjacob Nov 07 '22 at 18:16

0 Answers0