Reputation: 383
I came across a very nasty example of the if
- else
operator in Python where the code looked good but the result was completely different than expected. Here is a short version:
1 + 4 if None else 3 # returns 3
Looking at the Operator Precedence table in the documentation, it seems that if
- else
has almost the lowest precedence.
Is there anything special with if
- else
that treats everything on the left side of the if
as one expression?
Upvotes: 2
Views: 3063
Reputation: 1446
This is example of conditional expression in python.
It will execute block between IF and ELSE
1 + 4 if None else 3 In above line NONE menace FALSE will return so it will execute right side of ELSE block which is 3
Please see below code to understand conditional expression in python
a,b=10,1
v="A is less tahn B" if a < b else "A is greater than B"
print(v)
Upvotes: -1
Reputation: 91159
Well, None
is always false, so that you always get 3.
1 + 4
would be the result if you used a true value instead of None
:
1 + 4 if True else 3
gives 5.
That's exactly because of low precedence: it is the same as
(1 + 4) if ... else 3
as - you know - the precedence of if ... else
is lower than that of +
.
Upvotes: 6
Reputation: 4674
The difference is in the order, not the precedence. Both the if
...else
operator in Python and the ?
...:
operator in c have extremely low precedence (lower than +
and -
, anyway).
Python: result_if_true if conditional else result_if_false
c: conditional ? result_if_true : result_if_false
Consider the order of your example:
print 1 + 4 if None else 3
is the same as:
print (1 + 4) if (None) else (3)
which translates to c as:
cout << (0) ? (1 + 4) : (3);
where None
is translated to 0
since None
is a falsey in Python.
To get your c into Python...
#include <iostream>
using namespace std;
int main() {
int x = (1 + 0) ? (4) : (3);
cout << x; // prints 4
return 0;
}
Translates to:
x = 4 if 1 + 0 else 3
print x
Upvotes: 2
Reputation: 5289
Perhaps you are looking for:
print 1 + (4 if None else 3)
Which prints 4
Upvotes: 0