簡體   English   中英

使用Python函數計算復利

[英]Calculating Compound Interest using Python functions

編寫一個函數,在給定的年限之后,使用給定的初始余額和利率計算銀行帳戶的余額。 假設利息每年復利。

我遇到錯誤“ ValueError:索引28不支持的格式字符'I'(0x49)”

到目前為止,這是我的代碼。

def BankBalance():
    InputB = 1000
    return InputB
    print("Your initial balance is $1000")

def Interest():
    InputI = 0.05
    return InputI
    print("The rate of interest is 5%")

def CountNumber():
    InputN = float(input("Please enter the number of times per year you would like your interest to be compounded: "))
    return InputN

def Time():
    InputT = float(input("Please enter the number of years you need to compund interest for:"))
    return InputT

def Compount_Interest(InputB, InputI, InputT, InputN):
    Cinterest = (InputB*(1+(InputI % InputN))**(InputN * InputT))
    print("The compound interest for %.InputT years is %.Cinterest" %Cinterest)

B = BankBalance()
I = Interest()
N = CountNumber()
T = Time()
Compount_Interest(B, I, N, T)

這是您的操作方式。

def main():
# Getting input for Balance
    balance = float(input("Balance: $ "))
# Getting input for Interest Rate
    intRate = float(input("Interest Rate (%) : "))
# Getting input for Number of Years
    years = int(input("Years: "))
    newBalance = calcBalance(balance, intRate, years)

    print ("New baance:  $%.2f"  %(newBalance))
def calcBalance(bal, int, yrs):
    newBal = bal
    for i in range(yrs):
        newBal = newBal + newBal * int/100
    return newBal

# Program run
main()

您正在嘗試將變量用作函數。 試試這個代替:

Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))

Python和大多數其他編程語言不假定兩個相鄰的數學表達式之間沒有運算符就意味着乘法。 您缺少InputB和表達式其余部分之間的乘法運算符( * ):

Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
# Here -------------^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM