10 月 122020
#复利计算,利率5%,输入金额,显示1年-8年的资金总额
#invest(amount, rate, time)
amount = input('principal amount: ') #用户输入初始金额赋值变量
rate = float(1 / 20) #固定利率
time = range(1, 9) #显示1-8年
#定义计算函数
def invest(): #变量作为固定参数,首次来自用户输入
total_amount = float(amount) + float(amount) * rate #计算公式
return total_amount
#循环调用函数并打印结果
for i in time:
#amount = invest(amount) # 位置很重要,应当在第一次调用函数后再赋值
print('year ' + str(i) + ': ' + str(invest()))
amount = invest() #打印完第1年总额后将该总额再赋值给amount变量
PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
principal amount: 100
year 1: 105.0
year 2: 110.25
year 3: 115.7625
year 4: 121.550625
year 5: 127.62815624999999
year 6: 134.00956406249998
year 7: 140.71004226562496
year 8: 147.7455443789062
PS D:\Python>
#改造,用户输入函数两个参数,打印1-8年总额
#改造,用户输入函数两个参数,打印1-8年总额
#复利计算,利率5%,输入金额,显示1年-8年的资金总额
#invest(amount, rate, time)
amount = input('principal amount: ') #用户输入初始金额赋值变量
rate = input('input rate %: ') #用户输入利率
rate = float(int(rate) / 100) #固定利率
time = range(1, 9) #显示1-8年
#定义计算函数
def invest(): #变量作为固定参数,首次来自用户输入
total_amount = float(amount) + float(amount) * rate #计算公式
return total_amount
#循环调用函数并打印结果
for i in time:
#amount = invest(amount) # 位置很重要,应当在第一次调用函数后再赋值
print('year ' + str(i) + ': ' + str(invest()))
amount = invest() #打印完第1年总额后将该总额再赋值给amount变量
PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
principal amount: 200
input rate %: 6
year 1: 212.0
year 2: 224.72
year 3: 238.2032
year 4: 252.495392
year 5: 267.64511552
year 6: 283.7038224512
year 7: 300.726051798272
year 8: 318.76961490616833
PS D:\Python>