2

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
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Talha Anwar
  • 2,699
  • 4
  • 23
  • 62
  • No, `x = >` isn't valid syntactically, but you could use a _function_ - `if compare(b, a):`. Then just use https://docs.python.org/3/library/operator.html. – jonrsharpe Nov 25 '21 at 08:16
  • this should help you https://stackoverflow.com/questions/1740726/turn-string-into-operator. – Vinson Ciawandy Nov 25 '21 at 08:17
  • Does this answer your question? [Turn string into operator](https://stackoverflow.com/questions/1740726/turn-string-into-operator) – Rizquuula Nov 25 '21 at 08:17
  • 1
    my code is just an example code, its a complex logic and some time i have to just change the sign manually. – Talha Anwar Nov 25 '21 at 08:20
  • This seems to me as an https://en.wikipedia.org/wiki/XY_problem why do you want to do it in the first place? – Thomas Junk Nov 25 '21 at 08:21

4 Answers4

3

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")
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
joostblack
  • 2,465
  • 5
  • 14
1

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

jezza_99
  • 1,074
  • 1
  • 5
  • 17
0

You can try using the eval built-in function eval

>>> a = "5"
>>> b = "*"
>>> c="1"
>>> eval(a+b+c)
5
>>> d = ">"
>>> eval(a+d+c)
True

Similar thread:assign operator to variable in python?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 5
    NEVER advocate `eval` without mentioning the high risk of using it. A must read: [Eval really is dangerous](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – Matthias Nov 25 '21 at 08:28
0

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

VPfB
  • 14,927
  • 6
  • 41
  • 75