第一题:
编写一个从 1 加到 end 的当型循环。变量 end 的值由键盘输入。假如输入 end
的值为 6,则代码输出的结果应该是 21,也就是 1+2+3+4+5+6 的结果(不要用
sum 作为变量,因为它是内置函数)。
第二题:
假设一年存定期利率为3.25%,计算一下需要过多少年,一万元的一年定期存款连本带息能翻番?
第一题解答,普通方式
end = int(input("请输入end数字")) summary = 0 for i in range(end+1): summary += i print(summary)
或者,列表求和方式
end = int(input("请输入end数字")) print(sum([i for i in range(1,end+1)]))
或者,数学方式
end = int(input("请输入end数字")) print(end*(end+1)//2)
或者,递归方式
def getsumnum(end, res): if end == 0: return res return getsumnum(end-1, res+end) print(getsumnum(100,0))
第二题解答
money = 10000 rate=0.0325 years = 0 while True: if money <= 20000: money += rate*money else: print('需要%d年一万元的存款才能连本带息翻番' % years) break years += 1
或者
found = 10000 target = found * 2 years=0 rate=0.0325 while found < target: found += found*rate years += 1 print(years)