目标:我需要读取成本和折扣率以及年数,并计算时间调整成本和时间调整 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/