Python eval()无法正确相乘

时间:2019-02-27 19:56:52

标签: python python-3.x

我的代码有问题,由于某种原因,“结果”有时会返回一些古怪的数字,而这毫无意义。有更好的方法吗?

import random

number1 = random.randint(1,9)
operator = random.choice(r"+-*")
number2 = random.randint(1,9)
x1 = random.randint(1,9)

print(x1)
result = eval(str(number1)*int(x1) + operator + str(number2)*int(x1))
answer = x1
print("solve for x: {}x {} {}x = {}".format(number1, operator, number2, result))
print(number1*x1,operator,number2*x1,"=",result)

3 个答案:

答案 0 :(得分:3)

表达式str(number1)*int(x1)并没有您认为的那样。它将number1转换为字符串(从1到9的一位数字),然后将其复制x1次,如下所示:

print(str(7)*3)
# '777'

因此,您需要先将乘法 转换为字符串,如下所示:

print(str(7*3))
# 21

或者,将代码的主行更改为此:

result = eval(str(number1*x1) + operator + str(number2*x1))

您应该知道eval通常被认为是一种危险的工具。因此,使用以下方法可能会做得更好:

import random, operator

operators = [
    ('+', operator.add),
    ('-', operator.sub),
    ('*', operator.mul)
]

number1 = random.randint(1, 9)
op_str, op_func = random.choice(operators)
number2 = random.randint(1, 9)
x1 = random.randint(1, 9)

print(x1)
result = op_func(number1 * x1, number2 * x1)
print("solve for x: {}x {} {}x = {}".format(number1, op_str, number2, result))
print(number1 * x1, op_str, number2 * x1, "=" , result)

答案 1 :(得分:0)

import random
number1 = random.randint(1,9)
operator = random.choice(r"+-*")
number2 = random.randint(1,9)
x1 = random.randint(1,9)
print(x1)
result = eval(str(number1*x1) + operator + str(number2*x1))
answer = x1
print("solve for x: {}x {} {}x = {}".format(number1, operator, number2, result))
print(number1*x1,operator,number2*x1,"=",result)

我认为,这是行不通的,原因是eval将所有内容都解释为字符串并试图给出答案。在上面的代码中,我只是将eval中所有内容的类型更改为字符串。

在此处了解更多信息:On Eval

答案 2 :(得分:0)

代替做

result = eval(str(number1)*int(x1) + operator + str(number2)*int(x1))

我会

result = eval(str(number1*x1) + str(operator) + str(number2*x1))