You can't just concatenate an operator to a couple of numbers and expect it to be evaluated. You could use eval
to evaluate the final string.
answer = eval(str(randomnumberforq)
+ operator[randomoperator]
+ str(randomnumberforq))
A better way to accomplish what you're attempting is to use the functions found in the operator
module. By assigning the functions to a list, you can choose which one to call randomly:
import random
from operator import mul, add, sub
if __name__ == '__main__':
score = 0
randomnumberforq = random.randint(1,10)
randomoperator = random.randint(0,2)
operator = [[mul, ' * '],
[add, ' + '],
[sub, ' - ']]
answer = operator[randomoperator][0](randomnumberforq, randomnumberforq)
useranswer = input(str(randomnumberforq)
+ operator[randomoperator][1]
+ str(randomnumberforq) + ' = ')
if answer == useranswer:
print('correct')
else:
print('wrong')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…