解析时意外的 EOF

Unexpected EOF while parsing

目标:我需要读取成本和贴现率以及年数,并计算时间调整后的成本和时间调整后的收益以及两者的累计。

我收到此错误:

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