In one piece of my program I doubt if i use the comparison correctly. i want to make sure that ( u0 <= u < u0+step ) before do something.
if not (u0 <= u) and (u < u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do something. # condition is satisfied
-
12Python magic: u0 <= u < (u0 + step)ba__friend– ba__friend2010年11月11日 10:10:49 +00:00Commented Nov 11, 2010 at 10:10
5 Answers 5
You can do:
if not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do sth. # condition is satisfied
Using a loop:
while not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
Operator precedence in python
You can see that not X
has higher precedence than and
. Which means that the not
only apply to the first part (u0 <= u)
.
Write:
if not (u0 <= u and u < u0+step):
or even
if not (u0 <= u < u0+step):
In this particular case the clearest solution is the S.Lott answer
But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.
Using De Morgan's law ¬(A^B) = ¬Av¬B
not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step
then
if u0 > u or u >= u0+step:
pass
... in this case the «clear» solution is not more clear :P
-
Interesting advice generally, but as You said, it does not help clarity in this situation.Rauni Lillemets– Rauni Lillemets2015年09月11日 07:14:03 +00:00Commented Sep 11, 2015 at 7:14
Why think? If not
confuses you, switch your if and else clauses around to avoid the negation.
i want to make sure that ( u0 <= u < u0+step ) before do sth.
Just write that.
if u0 <= u < u0+step:
"do sth" # What language is "sth"? No vowels. An odd-looking word.
else:
u0 = u0+ step
Why overthink it?
If you need an empty if
-- and can't work out the logic -- use pass
.
if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here
-
"sth" is "some thing?" In what language?S.Lott– S.Lott2010年11月11日 15:44:22 +00:00Commented Nov 11, 2010 at 15:44
-
3I think I saw this abbreviation in some dictionaries. Anyhow I'm not native English speaker, excuse my English mistakes!masti– masti2010年11月11日 16:51:24 +00:00Commented Nov 11, 2010 at 16:51
-
maybe the inversion of "some-condition-that's-too-complex-for-me-to-invert" is equal to; "not (some-condition-that's-too-complex-for-me-to-invert)" works?GlassGhost– GlassGhost2014年05月30日 16:50:22 +00:00Commented May 30, 2014 at 16:50
-
I totally agree with this answer.Seba Kim– Seba Kim2020年02月28日 10:07:13 +00:00Commented Feb 28, 2020 at 10:07
There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:
if not ((u0 <= u) and (u < u0+step)):