How to do a calculation on Python with a random operator -


i making maths test each question either adding, multiplying or subtracting randomly chosen numbers. operator chosen @ random, cannot work out how calculate operator. problem here:

answer = input() if answer ==(number1,operator,number2):     print('correct') 

how can make operator used in calculation. example, if random numbers 2 , five, , random operator '+', how code program end doing calculation , getting answer, in case be:

answer =input() if answer == 10:     print('correct') 

basically, how can calculation check see if answer correct? full code below.

import random score = 0 #score of user questions = 0 #number of questions asked operator = ["+","-","*"] number1 = random.randint(1,20) number2 = random.randint(1,20) print("you have reached next level!this test of addition , subtraction") print("you asked ten random questions") while questions<10: #while have asked less ten questions     operator = random.choice(operator)     question = '{} {} {}'.format(number1, operator, number2)     print("what " + str(number1) +str(operator) +str(number2), "?")     answer = input()     if answer ==(number1,operator,number2):          print("you correct")         score =score+1     else:         print("incorrect") 

sorry if have been unclear, in advance

use functions in dictionary:

operator_functions = {     '+': lambda a, b: + b,      '-': lambda a, b: - b,     '*': lambda a, b: * b,      '/': lambda a, b: / b, } 

now can map operator in string function:

operator_functions[operator](number1, number2) 

there ready-made functions operator module:

import operator  operator_functions = {     '+': operator.add,      '-': operator.sub,     '*': operator.mul,     '/': operator.truediv, } 

note need careful using variable names! used operator first create list of operators, use store 1 operator picked random.choice(), replacing list:

operator = random.choice(operator) 

use separate names here:

operators = ["+","-","*"]  # ...  picked_operator = random.choice(operators) 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -