如何使用比较和 "如果不" 在 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
已邀请:

窦买办

赞同来自:

你能做到吗:


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

三叔

赞同来自:

http://docs.python.org/referen ... mmary
你可以看到
not X

优先级更高
and

. 代表着
not

仅适用于第一部分
/u0 <= u/

.
写:


if not /u0 <= u and u < u0+step/:


甚至更多


if not /u0 <= u < u0+step/:

涵秋

赞同来自:

在这种特殊情况下,最明确的决定是
https://coderoad.ru/4153260/
S.Lott

但在一些艰难的逻辑条件下,我宁愿使用一些布尔代数来获得清晰的解决方案。

使用de morgana法律 /A^B/ = AvB


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


...

在这种情况下,“清除 " 决定不太清楚 :P

冰洋

赞同来自:

为什么思考? 如果一个
not

让你混淆你切换你的建议 if 和 else, 避免拒绝。

我想确保 / u0 <= u < u0+step / 在做之前 sth.

只是写它。


if u0 <= u < u0+step:
"do sth" # What language is "sth"? No vowels. An odd-looking word.
else:
u0 = u0+ step


为什么这么认为这么多?

如果你需要空
if

- 而且你无法理解逻辑使用
pass

.


if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here

石油百科

赞同来自:

有两种方式。 如果有疑问,您可以随时尝试。 如果它不起作用,则可以添加其他括号以确保:


if not //u0 <= u/ and /u < u0+step//:

要回复问题请先登录注册