Reputation: 43
For some reason, when I run
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"
using python2 py.py 1 3 3 9 5 15
, it gives me the following error
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
Any ideas as to why this happens? I'm certain it's valid syntax but maybe the eval messed with it?
Upvotes: 4
Views: 243
Reputation: 36026
First of all (as others pointed out), evaluating code here is totally uncalled for (not to mention the performance hit). See e.g. Ned's answer for one alternative.
Now, regarding the error itself:
https://docs.python.org/2/library/functions.html?highlight=eval#eval:
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.
The key phrase is "as a Python expression". Assignment is not an expression but a statement. There is exec
to execute statements.
Upvotes: 2
Reputation: 375634
This is a needless use of eval
. Your code:
for i, j in zip(["a","b","c","d","e","f"], range(1,6)):
eval("{0} = int(sys.argv[{1}])".format(i, j))
can be better expressed as:
a, b, c, d, e, f = map(int, sys.argv[1:7])
or as:
a, b, c, d, e, f = (int(x) for x in sys.argv[1:7])
[Note that the original code had the range wrong, it should be range(1,7)]
Upvotes: 2