Feb-03-2021, 08:41 PM
Instead of using
eval()
, using the operator module would look a little like this:>>> import operator as op >>> import random >>> rand_ops = {"+": op.add, "-": op.sub, "/": op.truediv, "*": op.mul} >>> num_one = random.randint(0, 100) >>> num_two = random.randint(0, 100) >>> op_key = random.choice(list(rand_ops.keys())) >>> op_key '+' >>> print(f"what's {num_one} {op_key} {num_two} = ?") what's 37 + 1 = ? >>> answer = rand_ops[op_key](num_one, num_two) >>> answer 38