Python中的息票债券计算器

2024-06-07 12:42:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做息票债券计算,并不断遇到“类型错误必须是str,而不是int”在下面的代码。我想不出在哪里做一根绳子。在

"""The equation is the (sum from j to n of (c/(1+i)^j))+ (f/(1+i)^n)"""

print('What Are You Trying To Solve For?')
startvariable = str(input(' Price (p), Face (f), Years to Maturity (n), Interest Rate (i), Current Yield (cy), YTM (Y)' ).lower() )
while startvariable == 'p':
    f = (input("Face or Par Value (number only): "))
    i = (input("Interest Rate (as decimal): "))
    c = (input("Coupon (number only): "))
    n = (input("n value:  "))
    j = (input("j (starting) value:  "))
    summation_value = 0

    while j <= n:
        for k in range (j, (n + 1)):
            add_me = (c/(1+i)** j)
            summation_value += add_me
            k += 1
        print('Bond Price: ', (summation_value + ((f) / (1 + i) ** n)))

Tags: toaddnumberonlyinputratevalueprice
2条回答
print('What Are You Trying To Solve For?')
startvariable = str(input(' Price (p), Face (f), Years to Maturity (n), Interest Rate (i), Current Yield (cy), YTM (Y)' ).lower())
while startvariable == 'p':
    f = int(input("Face or Par Value (number only): "))
    i = float(input("Interest Rate (as decimal): "))
    c = int(input("Coupon (number only): "))
    n = int(input("n value: "))
    j = int(input("j (starting) value:  "))
    summation_value = 0

    while j <= n:
        for k in range (j,(n+1)):
            add_me = (c/(1+i)** j)
            summation_value += add_me
            k += 1
        print('Bond Price: ', (summation_value + ((f) / (1 + i) ** n)))

将每个输入转换为特定的数据类型使代码为我运行。虽然我不是金融专家,不知道这些数字意味着什么,也不知道它们是否正确。但它不再打印出你提到的错误。在

input返回文档和教程中定义的字符串。您尝试对一个字符串进行计算;我得到了两个不同的错误,包括第一行input上缺少的rparen,但没有您引用的那一行。在任何情况下,都需要根据需要将输入值从str转换为int和{}

埃格伯特的观点几乎是正确的;美元金额应该是浮动的:

f = float(input("Face or Par Value (number only): "))
i = float(input("Interest Rate (as decimal): "))
c = int(input("Coupon (number only): "))
n = int(input("n value: "))
j = int(input("j (starting) value:  "))

之后,您需要修复您构建的奇怪的无限循环:

^{pr2}$

由于jn在这个循环中永远不会改变,一旦你进入这个循环,它就是无限的。最重要的是,紧随其后的for循环似乎是为了执行相同的迭代。在

完全删除while;我认为在更改之后我看到的是正确的结果。在

相关问题 更多 >

    热门问题