0 python random math variables
我的Python代码需要能够随机生成1到3之间的数字,以确定要执行的函数(加法,乘法或减法).这很好.我随机生成两个数字,需要得到这个随机函数.所以它就像一个基本的数学总和,如3 + 6 = 9.3将被存储为number1(并随机生成).+将作为函数存储,也可以随机生成.6将被存储为number2并且也是随机生成的.
我遇到的问题是将所有变量组合在一起并使其计算出数学.
所以我可以做到以下几点:( 输入的数字将是随机生成的)
number1 = 3
number2 = 8
function = 3 (for the purposes of this: addition)
function then is changed to "+"
Run Code Online (Sandbox Code Playgroud)
我这样做了:
answer = number1, function, number2
Run Code Online (Sandbox Code Playgroud)
这显然不起作用.
你需要使用一个功能!对于相关的功能+,-以及*已经存在的operator.add,operator.sub和operator.mul.
import operator
import random
op_mappings = {"+":operator.add,
"-":operator.sub,
"*":operator.mul}
op = random.choice(["+", "-", "/"])
# this is better than mapping them to numbers, since it's
# immediately obvious to anyone reading your code what's going on
number1 = random.randint(1,20)
number2 = random.randint(1,20)
answer = op_mappings[op](number1, number2)
Run Code Online (Sandbox Code Playgroud)
运算符函数就像普通表达式一样工作,也就是说:
operator.add(x,y) == x + y
# et. al
Run Code Online (Sandbox Code Playgroud)
因此,您可以将它们用作字典中的对象.如果您之前没有使用过字典,那么现在是学习的好时机!它们像我上面那样用作哈希图,非常有用.