Reputation: 921
I am making a math quiz game in python, where the computer selects 2 numbers and 1 symbol from a list and prints it, then the user answers the question. In my list with the symbols, I have the math symbols as strings, but when I want the computer to get the answer, It can't, because the symbols are strings. How do I convert the '*' string to the * symbol used in math? Any help is appreciated, I will post what I have of the game so far as well.
import random
import time
import math
symbols = ('*', '+', '-', '/')
count = 0
def intro():
print("Hi")
print("Welcome to the math quiz game, where you will be tested on addition")
print("Subtraction, multiplication, and division, and other math skills")
time.sleep(3)
print("Lets begin")
def main(count):
number_1 = random.randrange(10,20+1)
number_2 = random.randrange(1,10+1)
symbol = (random.choice(symbols))
print("Your question is: What is %d %s %d") %(number_1, symbol, number_2)
main(count)
Upvotes: 0
Views: 125
Reputation: 32590
Use the operator
module and map the operators to your desired symbols:
import operator
import random
OPS = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
op_symbol = random.choice(OPS.keys())
operand1 = random.randint(1, 10)
operand2 = random.randint(1, 10)
formula = "{} {} {} = ?".format(operand1, op_symbol, operand2)
operator = OPS[op_symbol]
result = operator(operand1, operand2)
print "Question: {}".format(formula)
print "Result: {}".format(result)
Note that for Python 2.x the /
operator (operator.div
) does integer division - hence I used operator.truediv
instead because otherwise you'd get surprising results when dividing integers.
Upvotes: 6
Reputation: 476624
You can use the eval
functionality to evaluate a string as a command:
result=eval(str(number_1)+str(symbol)+str(number_2))
In that case result
will get the value of the queried question.
However as @icktoofay says, always use eval
with caution: if you don't use it properly it can have side effects (like eval("somecommand()")
) or even worse, it can allow a user to insert python logic in your program: for instance eval(cmd)
where the user can enter the command.
Upvotes: 3
Reputation: 56467
You have to give a meaning to those symbols. One way would be by realizing that each of these symbols is a function that takes two arguments. Thus you can do:
symbols = {
'*': lambda x, y: x*y,
'+': lambda x, y: x+y,
'-': lambda x, y: x-y,
'/': lambda x, y: x/y,
}
and then you can do
number_1 = random.randrange(10,20+1)
number_2 = random.randrange(1,10+1)
symbol = random.choice(symbols.keys())
operator = symbols[symbol]
result = operator(number_1, number_2)
Upvotes: 6