@Tim's answer shows you how to print out the expression, but to actually determine the result of the expression, you should create a dictionary with the operators like this:
import random, operator
num1 = random.randint(1,50)
num2 = random.randint(1,50)
operators = ['<', '>', '<=', '>=', '==']
dct = dict(zip(operators, [operator.lt, operator.gt, operator.le, operator.ge, operator.eq]))
for i in range(5):
print("Number 1: " + str(num1))
print("Number 2: " + str(num2))
print(num1, operators[i], num2)
print(dct[operators[i]](num1, num2))
In this solution instead of:
dct = dict(zip(operators, [operator.lt, operator.gt, operator.le, operator.ge, operator.eq]))
You could define the dictionary as:
dct = {'<': operator.lt, '>': operator.gt, '<=': operator.le, '>=': operator.ge, '==': operator.eq}
Example output:
Number 1: 32
Number 2: 27
32 < 27
False
Number 1: 32
Number 2: 27
32 > 27
True
Number 1: 32
Number 2: 27
32 <= 27
False
Number 1: 32
Number 2: 27
32 >= 27
True
Number 1: 32
Number 2: 27
32 == 27
False
Unless you want to use the evil eval
:
operators = ['<', '>', '<=', '>=', '==']
for i in range(5):
print("Number 1: " + str(num1))
print("Number 2: " + str(num2))
x = str(num1) + ' ' + operators[i] + ' ' + str(num2)
print(x)
print(eval(x))
I suggest not to use the eval
in general! It's bad practice!
But as @MarkTolonen mentioned, in this case, eval
is fine, It wouldn’t be evaluating potentially dangerous user input.