for语句
import math def main(): money_per_week=10 increase_money=10 total_week=52 saving=0 money_list=[] for i in range(total_week): money_list.append(money_per_week) saving =math.fsum(money_list) print('第{}周,存入{},账户累计{}元'.format(i+1,money_per_week,saving)) money_per_week+=increase_money if __name__=='_main_': main()
For <X> in<list>:
<body>
循环变量X在每次循环时,被赋值成对应的元素内容
与while循环的区别
For 循环的次数固定,即所遍历的序列长度
While为无限循环
Range(n)返回一个可迭代的对象
List(range(n))将迭代类型转换为列表类型
输入
import math def sav_money_in_n_week(money_per_week,increase_money,total_week): saving=0 money_list=[] for i in range(total_week): money_list.append(money_per_week) saving =math.fsum(money_list) print('第{}周,存入{},账户累计{}元'.format(i+1,money_per_week,saving)) money_per_week+=increase_money def main(): money_per_week=float (input('请输入每周存入金额')) increase_money=float (input('请输入每周递增金额')) total_week=float (input('请输入总共的周数:')) sav_money_in_n_week(money_per_week,increase_money,total_week) if __name__=='_main_': main()