如何将'*'转换为*

时间:2015-03-28 21:54:23

标签: python

我在python中进行数学测验游戏,计算机从列表中选择2个数字和1个符号并打印出来,然后用户回答问题。在带有符号的列表中,我将数学符号作为字符串,但是当我希望计算机得到答案时,它不能,因为符号是字符串。如何转换' *'字符串到数学中使用的*符号?任何帮助表示赞赏,我会发布到目前为止我的游戏内容。

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)

3 个答案:

答案 0 :(得分:6)

你必须给这些符号赋予意义。一种方法是通过认识到这些符号中的每一个都是一个带有两个参数的函数。因此你可以这样做:

symbols = {
    '*': lambda x, y: x*y,
    '+': lambda x, y: x+y,
    '-': lambda x, y: x-y,
    '/': lambda x, y: x/y,
}

然后你可以做

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)

答案 1 :(得分:6)

使用operator模块并将运算符映射到所需的符号:

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)

请注意,对于Python 2.x,/运算符(operator.div)执行整数除法 - 因此我使用了operator.truediv,因为否则在分割整数时会得到令人惊讶的结果。

答案 2 :(得分:3)

您可以使用eval功能将字符串计算为命令:

result=eval(str(number_1)+str(symbol)+str(number_2))

在这种情况下,result将获得查询问题的值。

然而,正如@icktoofay所说,始终谨慎使用eval :如果您没有正确使用它,可能会产生副作用(如eval("somecommand()"))或更糟糕的是,它可以允许用户在程序中插入python逻辑:例如eval(cmd),用户可以在其中输入命令。