解析时出现意外的EOF

时间:2015-03-27 13:17:41

标签: python python-3.4

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

我收到此错误:

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])

1 个答案:

答案 0 :(得分:2)

当您使用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,包括如何在给出有效输入之前重复询问。