Python中的优惠券债券计算器

时间:2018-05-02 14:53:27

标签: python python-3.x finance

我正在尝试进行优惠券计算,并在下面的代码中继续运行“类型错误必须是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)))

2 个答案:

答案 0 :(得分:1)

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

Egbert几乎是正确的;美元金额应该是浮动的:

float

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

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:  "))

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

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

答案 1 :(得分:0)

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

键入将每个输入转换为特定数据类型,使代码运行。虽然不是金融专家知道数字的含义或是否正确。但它不再打印出你提到的错误。