随机总和 - python

Random sum - python

我怎样才能让它真正给我一个答案?我希望它输出一个总和,类似于“ 17-5=12 ”

    import random
    no1 =(random.randint(1,20))
    function =(random.choice("+-*"))
    no2 =(random.randint(1,20))
    answer =no2,function,no1
    print(answer)

像这样:

import random
no1 =(random.randint(1,20))
function =(random.choice("+-*"))
no2 =(random.randint(1,20))
answer =str(no1) + function + str(no2)
print(str(no1) + function + str(no2) + '=' + str(eval(answer)))

首先知道有函数可以帮助执行操作

import operator
operator.add(5,7) # 12
operator.sub(5,7) # -2
operator.mul(5,7) # 35

您应该创建运算符到函数的映射

import operator

my_functions = {"+":operator.add,"-":operator.sub,"*":operator.mul}

然后你可以select一个运算符和一个函数很容易

my_operator,my_function = random.choice(my_functions.items())

然后你需要做的就是将它应用到你的数字上(粗略地说,你的数字必须首先是数字)

number1 = 12
number2 = 5

print("%s %s %s = %s"%(number1,my_operator,number2,my_function(number1,number2)))