開始使用免費開始

投資報酬預測

在 Python 中,你可以用 = 指派值給變數,就和 MATLAB 一樣。不過不需要使用分號!

# Area of a circle
area = 3.14 * (radius ** 2)

和 MATLAB 一樣,括號內的運算會先被評估。這能確保半徑先平方,再與 \(\pi\) 相乘。

在這個練習中,你會用賺錢的例子來測試 Python 的運算順序!你在投資帳戶中存入一筆金額,需要預測 5 年後帳戶的價值。帳戶的參數如下:

  • 初始投資:$1000
  • 年化報酬率:4.1%

你可以用下列公式計算在經過 X 個 years 後帳戶的最終金額:

\( final = deposit (1 + rate)^{years} \)

本練習屬於課程

給 MATLAB 使用者的 Python

檢視課程

練習說明

  • 分別將初始存款金額、年化報酬率與投資年數指定給變數 depositannual_rateyears
  • 計算投資 years 年後帳戶的最終金額,並存入變數 final
  • 計算最終金額與初始存款的差額,並存入 gain
  • 列印帳戶的獲利金額。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create variables with the initial deposit, annual_rate, and number of years
deposit = 
annual_rate = 
years = 

# Calculate the final value of the account & save it to the variable final
____ = ____

# Define gain as the difference between the final value and deposited value


# Print the gain, in dollars
print(gain)
編輯並執行程式碼