python - 解析时出现意外的 EOF

标签 python python-3.4

目标:我需要读取成本和折扣率以及年数,并计算时间调整成本和时间调整 yield 以及两者的累积。

我收到此错误:

Traceback (most recent call last):
  File "D:\python\codetest\hw.py", line 3, in <module>
    cost = eval(input("Enter Development cost :"))
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

当我删除eval时,代码工作正常。

 #import numpy as np

cost = eval(input("Enter Development cost :"))
discrate = eval(input("Enter discount rate :"))

#operation cost list
opcost = []
#benifits list
benifits = []
#dicount rate list


#dicount rate list
discount=[]
#time adjusted cost
TAC = []
#time adjusted benifits
TAB = []

CTAC=[]

year = eval(input("Enter number of year "))

for i in range (year):
    opcost.append(eval(input("Enter operation cost :")))

for i in range (year):
    benifits.append(eval(input("Enter benifit for this year :")))



for i in range (year):
    pvn = (1/pow(1+discrate,i))
    # print (pvn)
    discount.append(pvn)

for i in range (year):
    TAC.append(discount[i] * opcost[i])

#print(TAC[i])

for i in range(year):
    TAB.append(discount[i] * benifits[i]))


#CTAC = np.cumsum(TAC)

#for i in range (year):
#    print(CTAC[i])

最佳答案

当您使用eval()时,Python 会尝试将您传递给它的字符串解析为 Python 表达式。您传入了一个空字符串:

>>> eval('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

您应该使用特定的转换器,而不是使用eval();如果您的成本是浮点值,则使用 float() 代替:

opcost.append(float(input("Enter operation cost :")))

如果用户只是按 ENTER 并且您得到另一个空字符串,这仍然会导致错误:

>>> float('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 

您仍然可以通过捕获异常来处理这种情况。请参阅Asking the user for input until they give a valid response有关如何最好地做到这一点的更多详细信息,包括如何处理重复询问,直到给出有效的输入。

关于python - 解析时出现意外的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29301641/

相关文章:

python - AttributeError at/account/login/oauth/complete/facebook/'NoneType' 对象没有属性 'userprofile'

python - 模拟 bash 的 [ctrl]-l,**清爽**

python - 从 Jupyter 使用 Python 设置 Drive API 时出错

python - Gdal_rasterize nodata_value 不起作用

qt5 - PyQt5 - pyuic5 模块 PyQt5.uic 未找到

python - 如何导入模块(如果之前导入过则重新加载)

python - 为什么输出只包含 2 个值而不包含整个图像的位移?

python - 为什么 PyQt5 在 Windows 7 中的 Python3.4 中导入失败并显示 `ImportError: DLL load failed`?

python - 为什么一个类变量没有在列表理解中定义,而另一个是?

Python输入停止定时器