masti
masti

Reputation: 385

How to use comparison and ' if not' in python?

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

Upvotes: 36

Views: 182599

Answers (5)

remosu
remosu

Reputation: 5119

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

Upvotes: 4

SubniC
SubniC

Reputation: 10317

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

Upvotes: 57

S.Lott
S.Lott

Reputation: 391854

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

Upvotes: 3

log0
log0

Reputation: 10917

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):  

Upvotes: 10

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

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)):

Upvotes: 0

Related Questions