要求在屏幕上分别显求1到100之间奇数之和与偶数之和

#方法1:for遍历+判断

sum_even=0#偶数之和

sum_odd=0#奇数之和

for i in range(1,101):

      if i % 2==0:

            sum_even+=i

      else:

            sum_odd+=i

print('1到100之间奇数之和为',sum_odd)

print('1到100之间偶数之和为',sum_even)

#方法2:'''递归'''

def getSum(result,end,step):

      if end>100:

            return result

      else:

            result +=end

            end +=step

            return getSum(result,end,step)

print('1到100之间偶数之和为',getSum(0,0,2))

print('1到100之间奇数之和为',getSum(0,1,2))     


#方法3:'''sum'''

print(sum([i for i in range(1,101,2)]))

print(sum([i for i in range(0,101,2)]))

#方法4:'''正则'''

print('1到100之间偶数之和为',eval('+'.join(re.findall(r'(\d*2|\d*4|\d*6|\d*8|\d*0|100)\b',repr([str(i) for i in range(101)])))))

print('1到100之间奇数之和为',eval('+'.join(re.findall(r'(\d*1|\d*3|\d*5|\d*7|\d*9)\b',repr([str(i) for i in range(101)])))))

你可能感兴趣的