Python计算存款利息
时间: 2024-09-20 19:00:24 浏览: 74
在Python中,计算存款利息通常涉及到复利计算。下面是一个简单的例子,假设有一个定期存款的函数,它接受本金(principal)、年利率(annual_interest_rate)、存期(years)以及是否按年复利(compound_periodically)作为参数。以下是计算简单利息和复利的代码:
```python
def calculate_interest(principal, annual_interest_rate, years, compound_periodically=False):
# 简单利息(不考虑复利)
simple_interest = principal * annual_interest_rate * years
# 如果复利,每年计算一次利息并累计到本金
if compound_periodically:
interest_each_year = principal * annual_interest_rate / compound_periodically
total_interest = sum(interest_each_year for _ in range(years))
else:
total_interest = simple_interest
return simple_interest, total_interest
# 使用示例
principal = 10000 # 本金
annual_interest_rate = 0.05 # 年利率(5%)
years = 5 # 存款年限
compounding_frequency = 1 # 每年计息一次(等于非复利)
simple_interest, total_interest = calculate_interest(principal, annual_interest_rate, years, compounding_frequency)
print(f"简单利息: {simple_interest:.2f}")
print(f"总利息 (复利): {total_interest:.2f}")
```
在这个例子中,`calculate_interest` 函数返回了简单利息和复利总额。
阅读全文