如何在python中使用comparison和if not?

2024-04-19 15:57:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的一个程序中,我怀疑我是否正确地使用了比较。我想在做某事之前确定(u0<;=u<;u0+step)。

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

Tags: andthelt程序ifisstepnot
3条回答

在本例中,最清楚的解决方案是S.Lottanswer

但在一些复杂的逻辑条件下,我更喜欢用布尔代数来得到一个清晰的解。

使用德摩根定律

not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step

那么

if u0 > u or u >= u0+step:
    pass

。。。在这种情况下,«clear»解决方案不太清楚:P

Operator precedence in python
您可以看到not X的优先级高于and。这意味着not只适用于第一部分(u0 <= u)。 写入:

if not (u0 <= u and u < u0+step):  

甚至

if not (u0 <= u < u0+step):  

你可以:

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

使用循环:

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

相关问题 更多 >