| New Reply |
Python 3 question |
Share Thread | Thread Tools |
| Jul31-12, 04:11 PM | #1 |
|
|
Python 3 question
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 |
| Jul31-12, 04:36 PM | #2 |
|
|
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. |
| Jul31-12, 04:39 PM | #3 |
|
Mentor
|
|
| Aug1-12, 10:54 AM | #4 |
|
Recognitions:
|
Python 3 questionThough surely it's equivalent to (1!=0) and (0==0), rather than xor. |
| Aug1-12, 11:21 AM | #5 |
|
Mentor
|
It's not quite equivalent to (1!=0) and (0==0). There is a subtle difference. Consider self.inbounds = 0 < self.some_function() < 1This 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. |
| New Reply |
| Thread Tools | |
Similar Threads for: Python 3 question
|
||||
| Thread | Forum | Replies | ||
| Compile Python, Matlab and Python | Programming & Comp Sci | 3 | ||
| Python question | Engineering, Comp Sci, & Technology Homework | 1 | ||
| Beginner Python question | Engineering, Comp Sci, & Technology Homework | 7 | ||
| Beginner Python question | Engineering, Comp Sci, & Technology Homework | 10 | ||
| Python question | Engineering, Comp Sci, & Technology Homework | 2 | ||