Reputation: 361
The following is my code, and it works. It creates two random numbers, a random operator and puts them together, however it does not sum them after doing this. What I need is for the program to recognise it as an equation, rather than simply printing out the individual variables.
So, to avoid confusion; my question is: How would I get firstNumber
and secondNumber
to be summed together using whatever operator
is selected, rather than simply printing them out together?
from random import choice
from random import randint
ranOperator = ["*", "/", "+", "-"]
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
operator = choice(ranOperator)
generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
print(generateQuestion)
askQuestion()
Current output (example):
4 + 3
Using the same numbers above, what I would want to happen:
7
Upvotes: 1
Views: 223
Reputation: 326
Extending dseuss's answer to incorporate any function and print a math-like equation by mapping a function to its symbol using a dictionary
from random import choice
from random import randint
add = lambda x,y: x+y
substract = lambda x,y: x-y
divide = lambda x,y: x/y
multiply = lambda x,y: x*y
ranOperator = {"*":multiply, "/":divide, "+":add, "-":substract}
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
operator_key = choice(list(ranOperator.keys()))
answer = ranOperator[operator_key](firstNumber,secondNumber)
print("{} {} {} = {}".format(firstNumber, operator_key, secondNumber, answer))
askQuestion()
Upvotes: 3
Reputation: 26039
What you need is eval()
.
eval()
evaluates the passed string as a Python expression and returns the result.
from random import choice
from random import randint
ranOperator = ["*", "/", "+", "-"]
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
operator = choice(ranOperator)
generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
print(eval(generateQuestion))
askQuestion()
Demo:
>>> eval('1+1')
2
>>> eval('5-3')
2
>>> eval('2*3')
6
>>> eval('6/3')
2
Upvotes: 3
Reputation: 1141
One way to not rely on eval
is using the operator
module to represent the operations.
from random import choice
from random import randint
from operator import add, sub, truediv, mul
ranOperator = [add, sub, truediv, mul]
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
the_operator = choice(ranOperator)
result = the_operator(firstNumber, secondNumber)
print(result)
Upvotes: 7