簡體   English   中英

如何在函數參數中傳遞多個值?

[英]How can I pass multiple values in a function parameter?

我正在嘗試制作一個可以計算3個不同列表的復利的程序。 每個列表中的第一項是公式A = P(1 + r)^ n中需要的變量。 這些是說明。

Albert Einstein once said “compound interest” is man’s greatest invention. Use the equation A=P(1+r) n
,
where P is the amount invested, r is the annual percentage rate (as a decimal 5.0%=0.050) and n is the
number of years of the investment.
Input: 3 lists representing investments, rates, and terms
investment = [10000.00, 10000.00, 10000.00, 10000.00, 1.00]
rate = [5.0, 5.0, 10.0, 10.0, 50.00]
term = [20, 40, 20, 40, 40]
Output: Show the final investment.
$26532.98
$70399.89
$67275.00
$452592.56
$11057332.32

這是我到目前為止編寫的代碼:

P = [10000.00, 10000.00, 10000.00, 10000.00, 1.00]
r = [5.0, 5.0, 10.0, 10.0, 50.00]
n = [20, 40, 20, 40, 40]

# A=P(1+r)
def formula(principal,rate,years):
    body = principal*pow((1 + rate),years)
    print "%.2f" %(body)
def sort(lst):
    spot = 0
    for item in lst:
        item /= 100
        lst[spot] = item
        spot += 1

input = map(list,zip(P,r,n))
sort(r)
for i in input:
    for j in i:
        formula()

我首先定義一個計算復利的函數,然后定義一個將利率轉換為正確格式的函數。 然后使用map(我並不完全熟悉),我將每個列表的第一項分成新輸入列表中的元組。 我想做的是找到一種方法,可以將元組中的三個項目輸入到公式函數中的原理,比率和年份。 我願意提出批評和建議。 一般來說,我對編程還是比較陌生的。 謝謝。

首先,我認為您應該從formula return一些內容,即您的計算結果:

def formula(principal,rate,years):
    return principal*pow((1 + rate),years) #return this result

那么您可以使用formulareturn值-用於打印還是用於其他計算。

另外,由於三個列表中的項目數量相同,為什么不只使用range(len(p))遍歷它們呢?

for x in range(len(p)):
    print(formula(p[x],r[x],n[x]))

x in range(len(p)) x將生成具有x值的迭代:

0, 1, ..., len(p) - 1 # in your case, len(p) = 5, thus x ranges from 0 to 4

p[x]是您要從p獲得第x-th-indexed元素的方式。 把它放在您的上下文中,您將獲得如下組合:

when x=   principal   rate   years
----------------------------------
  0       10000.00     5.0     20
  1       10000.00     5.0     40
  2       10000.00    10.0     20
  3       10000.00    10.0     40
  4           1.00    50.0     40

這樣,您不需要使用tuple

暫無
暫無

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

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