Home > database >  Concatenating operators with numbers [duplicate]
Concatenating operators with numbers [duplicate]

Time:09-25

Just doing a fun project.

Is it possible to concatenate operators with numbers and then return the statement(s) to a boolean?

import random

num1 = random.randint(1,50)
num2 = random.randint(1,50)

operators = ['<', '>', '<=', '>=', '==']

for i in range(5):
    print("Number 1: "   str(num1))
    print("Number 2: "   str(num2))
    print(num1   operators[i]   num2)

Output: TypeError: unsupported operand type(s) for : 'int' and 'str'

CodePudding user response:

You need to cast num1 and num2 to string before concatenating in the final print:

for i in range(5):
    print("Number 1: "   str(num1))
    print("Number 2: "   str(num2))
    print(str(num1)   operators[i]   str(num2))

CodePudding user response:

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

CodePudding user response:

Or you could use f-strings and in combination with how pythons loops work:

for op in operators:
    print(f"Number 1: {num1}")
    print(f"Number 2: {num2}")
    print(f"{num1} {op} {num2}")
  • Related