Python 3 question

  • Python
  • Thread starter Bipolarity
  • Start date
  • #1
775
1

Main Question or Discussion Point

print(1!=0==0) seems to print the value 'True'. I'm trying to understand why.

Does it first evaluate (1!=0) ?

Or does it first evaluate (0==0) ?

Or does it separate them into (1!=0)^(0==0) ?

I appreciate all help.

BiP
 

Answers and Replies

  • #2
11,882
5,533
Not sure but I think it would use the left to right rule since != and == would have the same precedence as operators.

It's best to write code without an ambiguity like this by explicitly using parenthesis to order the sequence of operations.
 
  • #3
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
Or does it separate them into (1!=0)^(0==0)
That's what it does. There's some python comparison chaining magic going on here to enable expressions such as 0<x<1 to mean x is between 0 and 1 -- just like one would write in math. That you can use it for 1!=0==0 is a side effect of this magic.
 
  • #4
uart
Science Advisor
2,776
9
Or does it separate them into (1!=0)^(0==0) ?
That's what it does. There's some python comparison chaining magic going on here to enable expressions such as 0<x<1 to mean x is between 0 and 1 -- just like one would write in math. That you can use it for 1!=0==0 is a side effect of this magic.
Thanks for the tip on the 0<x<1 syntax DH. That's useful to know. :)

Though surely it's equivalent to (1!=0) and (0==0), rather than xor.
 
  • #5
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
Though surely it's equivalent to (1!=0) and (0==0), rather than xor.
Correct. I read the ^ as the mathematical shorthand for boolean and, which is not the case.


It's not quite equivalent to (1!=0) and (0==0). There is a subtle difference. Consider
self.inbounds = 0 < self.some_function() < 1

This will call self.some_function() once and only once. Now let's rewrite this expression as
self.inbounds = (0 < self.some_function()) and (self.some_function() < 1)

With this rewrite, self.some_function() will be called once if the result from the first call is non-positive, twice if it is positive. Calling the function sometimes once, sometimes twice, can be deleterious if the function has side effects.
 

Related Threads on Python 3 question

Replies
6
Views
4K
Replies
18
Views
4K
Replies
10
Views
927
Replies
7
Views
568
Replies
4
Views
1K
Replies
27
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
5
Views
6K
  • Last Post
Replies
6
Views
1K
  • Last Post
Replies
2
Views
2K
Top