Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 674
masti Avatar asked Nov 11 '10 10:11

masti


People also ask

What is == and != In Python?

== Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal.

Can you use != In Python?

You can use "!= " and "is not" for not equal operation in Python. The python != ( not equal operator ) return True, if the values of the two Python operands given on each side of the operator are not equal, otherwise false .

Is not VS != In Python?

The != operator compares the value or equality of two objects, whereas the Python is not operator checks whether two variables point to the same object in memory.

How do you compare an if statement in Python?

If equals test in Python: if with == The equals ( == ) operator tests for equality. It returns True when both tested values are the same. When their values differ, the operator returns False . This way our if statements can test for specific situations, such as a variable having a certain value.


2 Answers

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 
like image 162
SubniC Avatar answered Oct 02 '22 14:10

SubniC


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):   
like image 39
log0 Avatar answered Oct 02 '22 14:10

log0