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

Question:

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?

Asked By: Peaceful

||

Answers:

Instead of a == 0 or a > 0, simply use a >= 0.

See https://docs.python.org/library/stdtypes.html#comparisons for a complete list of available comparison operators.

Answered By: Michael Zhang

Python does not provide e.g. a !< operator, because it is not needed. if a == 0 or a > 0 means the same thing as if a >= 0.

Answered By: DeepSpace

You can use the equal or greater than operator:

if a >= 0:
    print(a)
Answered By: Zentryn

!< does not work in Python; but not can be placed before a comparison to get the opposite effect, like so:

if not a < 70:
    print('The number is Not smaller than 70')
else:
    print('The number is DEFINITELY smaller than 70')
Answered By: user9501848

You could look into the "not" operator with a > or < expression.

Answered By: William Kozlowski

Following worked for me though (not operator does not work, using tilde ~, doesn’t work):

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

Result:

True

To check whether a is not greater than b, use if not (a > b).

Answered By: Dave

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 [i.e. 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, i.e. not True is equivalent to False and not False is equivalent to True.

Answered By: Rajesh Timilsina
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.