[英]code into def function
我是 Python 的新手,並試圖解決我的一個練習:下面是描述貨幣增長的代碼,起始價為 100 美元,隨着時間的推移以每年 3% 的速度增長。 某一年年底的余額等於前一年的余額*利率。
balance = 100.0
rate = 0.03
print(0, round(balance,2))
for n in range(1,11):
balance = round(balance * (1 + rate), 2)
print(n, round(balance,2))
我每年打印出所需的 output,總共 10 年。 現在,我如何使用上面的代碼並按照以下說明將其轉換為 function? :
編寫一個名為 function 的復合,它接受三個輸入:balance、rate 和 num_periods。 function 應采用初始余額、固定利率以及余額要復利的時間段數。 您會希望您的 function 在 function 結束時返回當前余額(即本金加上所有應計利息的總和),以便您知道如果您想再投資它有多少錢。
我假設我應該得到與上面的代碼完全相同的 output 嗎?
您的三個輸入是 balance、rate 和 num_periods,它們對應於變量 balance、rate 和 range 方法中的第二個數字。 您的 function 應該看起來與上面的代碼非常相似,除了這些變量是 function 的輸入:
def compound(balance, rate, num_periods):
for n in range(1, num_periods):
balance = round(balance * (1 + rate), 2)
return round(balance, 2)
請注意,在 for 循環內使用舍入 function 可能會導致舍入錯誤。 為避免這種情況,請在 for 循環中使用我們的圓形 function
就像是...
def compound(balance, rate, num_periods):
return balance * (1 + rate)**num_periods
print(compound(100, 0.03, 10))
這是貨幣時間價值的基本問題。 請注意,在這種情況下 num_periods 是每年一次(如您所說的 10 年)。
go 的另一種方法是使用lambda
:
compound = lambda balance, rate, num_periods: balance * ( 1 + rate)**num_periods
用法:
print (round(comp_interest(100.0,0.03,10), 2))
Since a lambda function isn't acceptable to you, here's a function with formatted output, type hints and docstrings:
def compound(balance: float, rate: float, num_periods: float):
"""Calculate balance with compund interest
Keyword arguments:
balance: starting balance
rate: interest rate(1 > rate > 0)
num_periods: number of interest num_periods
"""
for n in range(1, num_periods+1):
balance *= (1 + rate)
print(f"{n:2}, {round(balance,2)}")
return round(balance, 2)
在處理金錢時,通常最好保留四舍五入僅用於顯示目的。 始終以原始格式保留實際金額。
嘗試這個:
def compound(balance, rate, num_periods):
for i in range(num_periods + 1):
print(round(balance * (1 + rate)**i, 2))
print(compound(100, 0.03, 10))
感謝你們。 非常有幫助。 我正在測試下面的代碼,它確實根據需要返回一個值。
def compound(balance, rate, num_periods):
for n in range(1, num_periods):
return balance * (1 + rate)**num_periods
print(compound(100, 0.03,10))
如果我要從 0-10 年開始返回運行總數,我錯過了什么。 所以它看起來像這樣:
0 100.0
1 103.0
2 106.09
3 109.27
4 112.55
5 115.93
6 119.41
7 122.99
8 126.68
9 130.48
10 134.39
Tahnks @tinstaafl,我不能使用 lamda,因為這不是練習的一部分。 這段代碼幾乎返回了我需要的東西,雖然它應該移動一點但不知道如何。
def compound(balance, rate, num_periods):
for n in range(1, num_periods):
balance = round(balance * (1 + rate), 2)
print(n, round(balance,2))
return round(balance, 2)
print(compound(100, 0.03, 10))
我想要的 output:
0 100.0
1 103.0
2 106.09
3 109.27
4 112.55
5 115.93
6 119.41
7 122.99
8 126.68
9 130.48
10 134.39
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.