如何在python中使用比较和“如果不是”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4153260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use comparison and ' if not' in python?
提问by masti
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.
在我的一个程序中,我怀疑我是否正确使用了比较。我想在做某事之前确保( 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
采纳答案by SubniC
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
回答by log0
Operator precedence in python
You can see that not Xhas higher precedence than and. Which means that the notonly apply to the first part (u0 <= u).
Write:
python中的运算符优先级
你可以看到它的not X优先级高于and. 这意味着not仅适用于第一部分(u0 <= u)。写:
if not (u0 <= u and u < u0+step):
or even
甚至
if not (u0 <= u < u0+step):
回答by Bj?rn Pollex
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)):
回答by S.Lott
Why think? If notconfuses you, switch your if and else clauses around to avoid the negation.
为什么想?如果not让您感到困惑,请切换您的 if 和 else 子句以避免否定。
i want to make sure that ( u0 <= u < u0+step ) before do sth.
我想在做某事之前确保( u0 <= u < u0+step )。
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- 并且无法计算出逻辑 - 使用pass.
if some-condition-that's-too-complex-for-me-to-invert:
pass
else:
do real work here
回答by remosu
In this particular case the clearest solution is the S.Lott answer
在这种特殊情况下,最清晰的解决方案是 S.Lott答案
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
使用德摩根定律 ?(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
...在这种情况下?清楚?解决方案不是更清楚:P

