如何打印add,mul,sub函数?

时间:2014-09-14 22:40:52

标签: python

我这样做:

        opers = (add, sub, mul)
        rand_choice = random.choice(opers)
        num1 = random.randint(1, operand_level)
        num2 = random.randint(1, operand_level)
        prod = rand_choice(num1, num2)

我想打印问题是sub,add还是mul 所以

       print "what is" " rand_choice (num1 ,num2 )

2 个答案:

答案 0 :(得分:1)

您可以通过__name__属性执行此操作,因此:

print('what is {}({}, {})'.format(rand_choice.__name__, num1, num2))

答案 1 :(得分:0)

发布可以无需修改即可运行的示例很有帮助。需要以下几行才能使示例工作:

from operator import add,sub,mul
import random
operand_level = 10

要打印运算符,请将符号添加到选项列表中:

opers = ('+',add),('-',sub),('x',mul)
symbol,function = random.choice(opers)
num1 = random.randint(1, operand_level)
num2 = random.randint(1, operand_level)
result = function(num1, num2)
print("what is {}{}{}? [{}]".format(num1,symbol,num2,result))

多次运行的输出:

what is 1x9? [9]
what is 7-5? [2]
what is 9-4? [5]
what is 10+4? [14]