36

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
Serenity
  • 35,289
  • 20
  • 120
  • 115
masti
  • 385
  • 1
  • 3
  • 4

5 Answers5

57

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
MERose
  • 4,048
  • 7
  • 53
  • 79
SubniC
  • 9,807
  • 4
  • 26
  • 33
10

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):  
log0
  • 10,489
  • 4
  • 28
  • 62
4

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

Community
  • 1
  • 1
remosu
  • 5,039
  • 1
  • 23
  • 16
3

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
S.Lott
  • 384,516
  • 81
  • 508
  • 779
0

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)):
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283