-1

I know that 'AND' is to give out a boolean value. eg:

x = 4 

x > 3 and x < 5

It will output TRUE

But when the code is:

18 and 4

it will output 4. What does it mean?

buran
  • 13,682
  • 10
  • 36
  • 61
vonnov
  • 1
  • 1
  • No idea, but `4 and 18` wil output `18` – Rafael-WO Oct 06 '21 at 06:22
  • 1
    Take a look at https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false and keep in mind that the result of `and` or `or` is the last term that was evaluated before succeeding or failing (this is the case for python as well as JavaScript, PHP and C if I recall correctly) – apokryfos Oct 06 '21 at 06:23
  • The definition of "A and B" in Python is this: if A is true, it returns B, otherwise it returns A. Similarly "A or B" means "if A is false, return B, otherwise it returns A." This gives it the usual Boolean meaning but also allows many more uses. – Tim Roberts Oct 06 '21 at 06:23
  • Does this answer your question? [How does the logical \`and\` operator work with integers?](https://stackoverflow.com/questions/49658308/how-does-the-logical-and-operator-work-with-integers) – Rafael-WO Oct 06 '21 at 06:24
  • `and` (lower case) will return one of the operants. So, it will only return `True` (title case) if one of the operants was `True`. `p and q` is implemented as `q if p else p`. – Klaus D. Oct 06 '21 at 06:25
  • In the olden days, Python didn't have boolean values. `a and b` is `b` if `a` is "truth-y", otherwise `a` (i.e. logically equivalent to `b if a else a`, but doesn't evaluate any operand more than once). `a or b` is `a` if it is "truth-y", otherwise `b` (`a if a else b`). The first language to use this convention was Lisp, in the late 1950s. – molbdnilo Oct 06 '21 at 06:31
  • 1
    @apokryfos that explains why I can do something like `self.logger = logger or getLogger("dummy")`. My horizons have expanded. – MSH Oct 06 '21 at 06:38

1 Answers1

0

If the operands of and/or were not boolean values (True/False)

  • And - > will return the operand at left (unless any operand is False/0, it will return False/0)
  • Or -> will return the operand at right (unless it was False/0 and the other non False/0)
>>> 5 and 6
6
>>> 6 and 5
5
>>> 0 and 2 
0
>>> 0 or 2
2
>>> True and 2
2
>>> 2 and True
True
Mahmoud Aly
  • 578
  • 3
  • 10