Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating numerical expressions

Tags:

python

boolean

Can someone explain to me why when evaluating numerical expressions Python as a result of evaluation returns the last thing that was evaluated?

For example:

3 and 5

evaluates to

5

Another question I have is why is it even evaluating these expressions, when I try to check:

3 == True

I get False but when I evaluate:

3 and 5

and get 5 as a result it obviously( I think) thinks that 3 evaluates to True since it wouldn't continue evaluating if it thought otherwise( I might be wrong here). In contrast when I evaluate:

0 and 3

I get 0, what I think is happening is that Python checks whether 0 is True, decides it's not and spits it out.

I'm sorry if it all sounds a bit chaotic but I stumbled across this in my book and was curious if there is something I'm missing.

like image 940
Blücher Avatar asked Apr 28 '26 00:04

Blücher


2 Answers

Yes, in python any value is either truthy or falsy. Every integer is truthy except for 0. With the boolean operators or and and, python returns the last expression it evaluates, for example 3 or 5 will return 3 as python first sees that 3 is truthy and does not have to evaluate 5 and returns 3.

In 0 and 5, 0 is falsy and so python does not evaluate the next expression and returns 0.

The reason 5 == True gives False as 5 does not equal true, it just acts truthy in boolean expressions. bool(5) == True gives True as this explicitly converts the integer to a boolean.

like image 136
Andrew Marsh Avatar answered Apr 29 '26 15:04

Andrew Marsh


From the Python Reference:

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.

If you had said

0 and 5

the value of the first thing evaluated (0) would have been returned.

For the second question, 3 obviously evaluates to true when treated as a boolean, but the == operator does not coerce its arguments to boolean prior to comparison.

like image 29
Dave Avatar answered Apr 29 '26 13:04

Dave



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!