简体   繁体   English

python中是否有不小于或不大于的运算?

[英]Is there an operation for not less than or not greater than in python?

Suppose I have this code:假设我有这段代码:

a = 0
if a == 0 or a > 0:
    print(a)

That is: I want to do something when a is not negative.即:我想在a不为负时做某事。

I know that I can write if a:= 0: to check whether a is not equal to 0 .我知道我可以写if a:= 0:来检查a是否不等于0

So, I tried using if a:< 0: , following similar logic.所以,我尝试使用if a:< 0: ,遵循类似的逻辑。 However, this is apparently not supported:但是,这显然不受支持:

>>> if a !< 0:
  File "<stdin>", line 1
    if a !< 0:
         ^
SyntaxError: invalid syntax

Why is this syntax invalid?为什么这个语法无效? What can I use instead to simplify the conditional?我可以用什么来简化条件?

Instead of a == 0 or a > 0 you could just use a >= 0 .您可以使用a >= 0而不是a == 0 or a > 0 a >= 0

https://docs.python.org/library/stdtypes.html#comparisons https://docs.python.org/library/stdtypes.html#comparisons

Well python !> doesn't work.But好吧 python !>不起作用。但是

if not a > 70:

    print(' The number is Not bigger than 70')

else:
    print(' The number is DEFINITELY bigger than 70')

this surprisingly works这令人惊讶地有效

I was surprised to see that this particular operation does not exist in Python!我很惊讶地看到 Python 中不存在这个特定的操作!

I'm not familiar with any language that does have this operator.我不熟悉任何具有此运算符的语言。 It is simply not needed.它根本不需要。

As for your snippets:至于你的片段:

if a == 0 or a > 0

It is exactly the same as if a >= 0if a >= 0完全一样

You can use the equal or greater than operator:您可以使用等于或大于运算符:

if a >= 0:
    print(a)
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
not_duplicates = []
for number in numbers:
   if number != numbers:
      not_duplicates.append(number)
print(not_duplicates)

Ans: [2, 4, 6, 3, 1]

您可以使用 > 或 < 表达式查看“not”运算符。

To check whether a is not greater than b , use if not (a > b) .要检查a是否不大于b ,请使用if not (a > b)

Following worked for me though (not operator does not work, using tilde ~, doesn't work):尽管以下对我有用(不是运算符不起作用,使用波浪号 ~ 不起作用):

((-1 > 0) or (0 > 0)) == False

Result:结果:

True

an operation for not less than or not greater than in python?不小于或不大于 python 的操作?

Ahh, pretty old question.啊,很老的问题了。 But I believe our future programmers are probably searching this one.但我相信我们未来的程序员可能正在寻找这个。 Here it goes:它是这样的:

Well, if you want the above two operations on the same line: you are looking for == operator [ie if a is not less than b and a is also not greater than b , then it ought to be equal to b ].好吧,如果您希望在同一行执行上述两个操作:您正在寻找==运算符 [即如果a不小于b并且a也不大于b ,那么它应该等于b ]。 If you meant operations like "not less than", you are looking for not operator.如果您的意思是“不少于”之类的操作,则您正在寻找not运算符。

if not a < b:
    # do something here. 

The not operator in Python reverts the boolean value, ie not True is equivalent to False and not False is equivalent to True . Python 中的not运算符还原 boolean 值,即not True等同于Falsenot False等同于True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM