如何使用算术符号而不是内置函数

时间:2015-03-20 23:43:19

标签: python math

我在python中进行数学测验并使用3个运算符:加,减和乘。我想使用算术运算符,但我发现它很难,因为如果我打印它,python只是将其读作符号。我使用以下代码:

import random
import operator
opslist = [          # This is the bit that I want to change, i also want 
    operator.add,    # the operators all on one line
    operator.sub,
    operator.mul
]

num1 = random.randint(1,10)  # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(opslist) #Random operator for my quiz

total = (ops(num1,num2))    # Answer for my quiz

print (num1,ops,num2)       # Random question for my quiz

这是输出:

6 <built-in function add> 5

1。)如何输出&#34; 6 + 5&#34;

2。)另外,如何使数字只做小计算,得到正答案,所以问题永远不会像&#34; 5-8&#34;

2 个答案:

答案 0 :(得分:1)

您可以使用字典将操作映射到其符号表示。您还可以为减法添加一些逻辑,以确保num2低于num1

import random
import operator
ops = {
    operator.add: '+', 
    operator.sub: '-',
    operator.mul: '*'
}
num1, num2 = random.randint(1, 10), random.randint(1, 10)
op = random.choice(ops.keys())
if op != operator.sub or num2 <= num1:
    print "%d %s %d = %d" % (num1, ops[op], num2, op(num1, num2))

可能的结果:

3 - 2 = 1

答案 1 :(得分:1)

我也会在你的代码中使用字典。这就是我所做的。

import random
import operator

opslist= {
    operator.add: "+",    # the operators all on one line
    operator.sub: "-",
    operator.mul: "x"
}

num1 = random.randint(1,10)  # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(list(opslist.keys())) #Random operator from opslist keys

total = (ops(num1,num2)) # Answer for my quiz

print(num1,opslist[ops],num2)

打印问题时,程序会打印出操作员的标志。为了确保您没有得到负数,请将其添加到总数中

while total < 0:
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    ops = random.choice(opslist)

    total = (ops(num1,num2))