Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bool and int types in boolean contexts

I have this code in a boolean context:

True and False or 2  

Output: 2

The type check for this expression resulted in int.

Next, I modified the code to:

True and False or True 

Output : True And the type check for this expression resulted in bool

  • Why is the output in the 1st code 2?
  • Shouldn't the expression evaluate to a boolean value ?
    If not so, Why?
like image 852
Kshitij Saraogi Avatar asked Jul 30 '26 20:07

Kshitij Saraogi


1 Answers

All you need to know here is the definition of OR operand.Based on python documentation :

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So since the precedence of or is lower than and your expression evaluated as following :

(True and False) or 2

Which is equal to following :

False or 2

Thus based on preceding documentation the result would be the value of right object which is 2.

like image 110
Mazdak Avatar answered Aug 01 '26 08:08

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!