gpt4 book ai didi

python - 评估赋值时出现语法错误

转载 作者:太空狗 更新时间:2023-10-30 03:01:03 26 4
gpt4 key购买 nike

出于某种原因,当我运行时

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 弄乱了它?

最佳答案

这是对 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])

[注意原代码中range不对,应该是range(1,7)]

关于python - 评估赋值时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com