You assigned a string to the operator
name:
operator = randomOp[0]
You are now masking the operator
module. Don’t re-use names like that, because the next iteration of your for
loop operator.add
now tries to look up the add
attribute on that string (so one of '+'
, '-'
or '*'
, whatever the first iteration picked by random choice).
You also imported the 3 functions directly:
import operator
from operator import add, sub, mul
so a simple solution would be to use those 3 names instead of referencing the functions on the module:
ops = (("+", add), ("-", sub), ("*", mul))
where I used tuples instead of lists (since altering the ops
sequence in your code would probably be an error). You could move that assignment out of your for
loop as well; there is little point in recreating it each iteration.
solved Str object has no attribute “add”