1

出于某种原因,我的脚本拒绝直接从 Text Wrangler 运行,但在导入终端时工作正常。

import math

def main():
    print("This program find the real solutions to a quadratic\n")
    a,b,c, = eval(input("Please enter the coefficients (a,b,c): "))
    discRoot = math.sqrt(b * b -4 * a * c)
    root1 = (-b + discRoot) / (2 * a)
    root2 = (-b - discRoot) / (2 * a)
    print("\nThe solutions are:" , root1, root2)


main()

当我在 textwrangler 中运行它时,我收到错误消息“TypeError: eval() arg 1 must be a string or code object”。使用 eval() 是否意味着以下输入是整数而不是字符串?为什么会这样?

4

2 回答 2

4

在 Python 2 中,input()相当于eval(input())在 Python 3 中。我认为在终端中您正在使用 Python 3 运行它,但 TextWrangler 使用 Python 2 因此 TextWrangle 正在执行eval(eval(input()))- 计算结果为eval(5),这会导致您看到的错误。

要解决此问题,您需要更新 TextWrangler,或在终端中使用 Python 2。如果你想要第二个选项,你应该eval(input())input().

旁注 -eval像这样使用是个坏主意(很危险)。您可能应该执行类似a, b, c = map(int, input().split(","))(在 Python 3 中)的操作。

于 2014-06-30T20:11:50.477 回答
0

问题不在于eval. 问题在于input,它试图从sys.stdin标准输入流中读取。

如果你想绕过它,你应该将参数eval作为参数传递给而不是使用input.

于 2014-06-30T20:11:53.137 回答