Alex
Alex

Reputation: 111

Comparison using modifiable signs (python)

In Python, is there a way of comparing values using a variable comparison sign? For example, I want to be able to change the sign to be < or >, and have the if statement still work.

The code below shows the idea, but it is not valid in Python:

sign = <
if 1 sign 2:
    print("This works")

Upvotes: 1

Views: 27

Answers (1)

kaya3
kaya3

Reputation: 51093

Python's operators like < and > aren't values, so you can't assign them to variables. However, functions are values in Python, so you can assign them. The operator module has functions named lt and gt respectively:

>>> from operator import lt, gt
>>> lt(1, 2)
True
>>> gt(1, 2)
False
>>> sign = lt
>>> sign(1, 2)
True

So you could write:

from operator import lt, gt

sign = lt

if sign(1, 2):
    print('This works')

Upvotes: 3

Related Questions