python - Str object has no attribute "add" -


can me fix this:

import random import operator operator import add, sub, mul random import randint  score = 0  name = input("what name? ")  in range(10):     n1 = randint(1,10)     n2 = randint(1,10)     ops =[["+", operator.add],["-", operator.sub],["*", operator.mul]]      randomop = random.choice(list(ops))      operator = randomop[0]     op = randomop[1]      prod = op(int(n1), int(n2))      ask = ("what is",int(n1),operator,int(n2),"?")      ans = input(ask)     if ans == ("%d" % (prod)):         print ("that's right -- done")         score = score + 1     else:         print ("no, answer %d. " % (prod))  print (name, "i asked 10 questions. got %d of them right." % (score)) print ("quiz finished") 

you assigned string operator name:

operator = randomop[0] 

you masking operator module. don't re-use names that, because next iteration of for loop operator.add tries add attribute on string (so 1 of '+', '-' or '*', whatever first iteration picked random choice).

you imported 3 functions directly:

import operator operator import add, sub, mul 

so simple solution use 3 names instead of referencing functions on module:

ops = (("+", add), ("-", sub), ("*", mul)) 

where used tuples instead of lists (since altering ops sequence in code error). move assignment out of for loop well; there little point in recreating each iteration.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -