Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

integer - is a mathematical operator classed as an interger in python

in python is a mathematical operator classed as an interger. for example why isnt this code working

import random

score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer = input(int(randomnumberforq)+int(operator[randomoperator])+      int(randomnumberforq))
if answer == useranswer:
print('correct')
else:
    print('wrong')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...