Python 练习实例45
题目:统计 1 到 100 之和。
程序分析:无
程序源代码:
实例
#!/usr/bin/python# -*- coding: UTF-8 -*-tmp = 0foriinrange(1,101):
tmp += iprint('The sum is %d' % tmp)
以上实例输出结果为:
The sum is 5050
题目:统计 1 到 100 之和。
程序分析:无
程序源代码:
以上实例输出结果为:
The sum is 5050
kui
che***[email protected]
以下代码同样实现了计算 1 到 100 之和:
#!/usr/bin/python # -*- coding: UTF-8 -*- m = 1 n = 100 area = (m+n)*(n-m+1)/2 print "sum from %d to %d is %d" %(m,n,area)
kui
che***[email protected]
等一个人
252***[email protected]
参考方案:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- a = [x for x in range(1, 101)] b = (a[0] + a[-1]) * (len(a) // 2) if len(a) % 2 != 0: b += a[(len(a) - 1) // 2] print(b)
等一个人
252***[email protected]
种花家兔子
xyt***[email protected]
ICE·
361***[email protected]
参考方法:
#!/usr/bin/python # -*- coding: UTF-8 -*- #Sn=n*a1+n*(n-1)*d/2 a1=1 d=1 n=100 S100=100*1+100*(100-1)*1/2 print 'total:',S100
ICE·
361***[email protected]
jc
228***[email protected]
使用匿名函数:
>>> reduce(lambda x,y:x+y,range(1,101)) 5050 >>>
jc
228***[email protected]
yulinshui
132***[email protected]
使用while循环统计
i=0 total=0 while i<=100: total=total + i i = i +1 print(total)
yulinshui
132***[email protected]
123
117***[email protected]
递归方法:
# coding: utf-8 def my_sum(x): if x == 100: return 100 else: return x + my_sum(x + 1) print(my_sum(1))
123
117***[email protected]