出于某种原因,当我跑
时import sys
from fractions import Fraction
for i, j in zip(["a","b","c","d","e","f"], range(1,6)):
eval("{0} = int(sys.argv[{1}])".format(i, j))
if a*d != c*b:
x = (e*d-b*f)/(a*d-c*b)
y = (a*f-c*e)/(a*d-c*b)
print "x = ", x , ", y = ", y
elif e*d-b*f == 0 and a*f-e*c == 0:
print "Infinite solutions"
print "Slope = ", Fraction(-a,b), ", Y-Intercept = ", Fraction(e,b)
else:
print "No solution"
使用python2 py.py 1 3 3 9 5 15
,它会给我以下错误
Traceback (most recent call last):
File "py.py", line 4, in <module>
eval("{0} = int(sys.argv[{1}])".format(i, j))
File "<string>", line 1
a = int(sys.argv[1])
^
SyntaxError: invalid syntax
关于为什么会发生这种情况的任何想法?我确定它是有效的语法,但也许eval搞乱了吗?
答案 0 :(得分:2)
首先(正如其他人所指出的),在这里评估代码是完全不必要的(更不用说性能损失)。参见例如Ned's answer为另一种选择。
现在,关于错误本身:
https://docs.python.org/2/library/functions.html?highlight=eval#eval:
表达式参数被解析并作为Python表达式(技术上讲,条件列表)使用全局和本地字典作为全局和本地命名空间进行评估。
关键短语是“作为Python表达式”。作业不是表达,而是声明。执行语句有exec
。
答案 1 :(得分:2)
这是对eval
的不必要的使用。你的代码:
for i, j in zip(["a","b","c","d","e","f"], range(1,6)):
eval("{0} = int(sys.argv[{1}])".format(i, j))
可以更好地表达为:
a, b, c, d, e, f = map(int, sys.argv[1:7])
或作为:
a, b, c, d, e, f = (int(x) for x in sys.argv[1:7])
[请注意,原始代码的范围错误,应该是范围(1,7)]