python小练习之一
下面的练习本身不难,比如打印1到10,计算1+2+3+...+100 ,最后一个是计算 1-2+3-4...-100
用了类的方法实现
用了列表生成器
用“高级”一丢丢的写法来实现这些小练习
# coding:utf-8
class Num(object):
def __init__(self, calNum):
self.calNum = calNum
@property
def seqNum(self):
i = 0
while i < self.calNum:
i += 1
yield i
@property
def sumNum(self):
return reduce(lambda sum, x: sum + x, xrange(self.calNum))
@property
def oddNum(self):
return [ num for num in range(self.calNum) if num % 2 != 0 ]
@property
def evenNum(self):
return [ num for num in range(self.calNum) if num % 2 == 0 ]
@property
def crossSumNum(self):
sum = 0
for i in xrange(self.calNum):
if i % 2 == 0:
sum = sum - i
else:
sum = sum + i
return sum
def Main():
print "======================="
print u"输出1,2,3...10"
print "======================="
n = Num(10)
for i in n.seqNum:
print i,
print "\r"
print "======================="
n = Num(101)
print u"求和1+2+3+...+100"
print "======================="
print n.sumNum
print "======================="
print u"输出1...100范围的奇数"
print "======================="
for i in n.oddNum:
print i,
print "\r"
print "======================="
print u"1...100范围的偶数"
print "======================="
for i in n.evenNum:
print i,
print "\r"
print "======================="
print u"求和1-2+3-4-5+6...+100"
print "======================="
print n.crossSumNum
if __name__ == '__main__':
Main()