Can I store a logical condition inside a variable

Viewed 179

For example, I have this code:

a = 33
b = 200
if b > a:
  # do some thing

I want to switch the > sign without using the else/if-else condition to == or <, is there a way I can store logic condition in a variable x and do something like:

if b x a:
  # do something
4 Answers

You can use operator.lt(a, b) or operator.gt(a, b) or operator.eq(a,b).

import operator
a = 33
b = 200
x = operator.lt
if x(a,b):
  print("hello world")

Provided they are just numbers (integers or floats), you could multiply both arguments by positive or negative 1, which switches the < sign

a = 5
b = 6
direction = -1

if direction * a < direction * b:
    # do something
    pass

Note this is a mathematical solution rather than a programming one

For this use-case you could get some inspiration from the "spaceship operator" (three-way comparison on Wikipedia) available in Perl or PHP.

def cmp3w(a, b):
    if a == b:
        return 0
    return -1 if a < b else 1

Then the meaning of cmp3w(a,b) == x condition depends on the variable x (+1 for gt, 0 for eq, -1 for lt).

Related