简体   繁体   中英

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.

I know that I can write if a:= 0: to check whether a is not equal to 0 .

So, I tried using if a:< 0: , following similar logic. 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 .

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

Well python !> doesn't work.But

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!

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 >= 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) .

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?

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 ]. If you meant operations like "not less than", you are looking for not operator.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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