Python eval() not multiplying properly

The expression str(number1)*int(x1) doesn’t do what you think it does. It converts number1 to a string (a single digit from 1 to 9), then it replicates it x1 times, like this:

print(str(7)*3)
# '777'

So you need to do the multiplication before converting to a string, like this:

print(str(7*3))
# 21

Or, change the main line of your code to this:

result = eval(str(number1*x1) + operator + str(number2*x1))

You should know that eval is generally considered a dangerous tool. So you might do better with something like this:

import random, operator

operators = [
    ('+', operator.add),
    ('-', operator.sub),
    ('*', operator.mul)
]

number1 = random.randint(1, 9)
op_str, op_func = random.choice(operators)
number2 = random.randint(1, 9)
x1 = random.randint(1, 9)

print(x1)
result = op_func(number1 * x1, number2 * x1)
print("solve for x: {}x {} {}x = {}".format(number1, op_str, number2, result))
print(number1 * x1, op_str, number2 * x1, "=" , result)

Leave a Comment