-3

My code:

a = 7
b = 5
print((a and b))

Output: 5

Why is the output 5? Doesn't logical operator gives True or False output? Why isnt it raising any errors ?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
A Ki Nir
  • 3
  • 1
  • 1
    Why are you assuming that's a logical operator? It's printing a bitwise operation result... According to what documentation should an error be raised? – OneCricketeer Apr 26 '23 at 13:09
  • and is used and isn't it a logical operator. Also why is the output 5 – A Ki Nir Apr 26 '23 at 13:13
  • The rule for Python's `and` is: If `a` is "truthy" (seen as true) `b` is returned, `a` otherwise. – Michael Butscher Apr 26 '23 at 13:13
  • 1
    I think that's a good question. One might expect `a and b` to do something like `bool(a) and (bool)b`, returning either True or False. That's not how the `and` operator works in python though. – Sembei Norimaki Apr 26 '23 at 13:13
  • 3
    @AndyPreston `7 & 5` would be the bitwise operation (and also results in `5`). – jonrsharpe Apr 26 '23 at 13:15
  • 2
    It has nothing to do with binaries, check `2 and 4` vs `2 & 4` and also `666 and 'YUP'`, for example. – Nikolaj Š. Apr 26 '23 at 13:15
  • 7 and 5 was a bad example, FWIW, since the bitwise and logical operator are the same result... If you did `5 and 7`, then that would be a better representation of what you're trying to ask – OneCricketeer Apr 26 '23 at 13:15

2 Answers2

2

In Python, the logical operator and returns the first operand if it evaluates to False, otherwise it returns the second operand.

In this case, both a and b are considered True because they are not equal to zero, so the expression (a and b) evaluates to the second operand, which is b with a value of 5.

So the output of print((a and b)) is 5.

Alex
  • 21
  • 2
2

It returns the last "truthy" value, see Boolean operations

Nikolaj Š.
  • 1,457
  • 1
  • 10
  • 17