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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...