如何在python中使用比较和'如果不是'?

mas*_*sti 33 python

在我的一个程序中,我怀疑我是否正确使用了比较.我想在做某事之前确保(u0 <= u <u0 +步骤).

if not (u0 <= u) and (u < u0+step):
    u0 = u0+ step # change the condition until it is satisfied
else:
    do something. # condition is satisfied
Run Code Online (Sandbox Code Playgroud)

Sub*_*niC 53

你可以做:

if not (u0 <= u <= u0+step):
    u0 = u0+ step # change the condition until it is satisfied
else:
    do sth. # condition is satisfied
Run Code Online (Sandbox Code Playgroud)

使用循环:

while not (u0 <= u <= u0+step):
   u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
Run Code Online (Sandbox Code Playgroud)


log*_*og0 10

python中的运算符优先级
您可以看到not X优先级高于and.这意味着not 只适用于第一部分(u0 <= u).写:

if not (u0 <= u and u < u0+step):  
Run Code Online (Sandbox Code Playgroud)

甚至

if not (u0 <= u < u0+step):  
Run Code Online (Sandbox Code Playgroud)