Python中while循环,求1-100之间的偶数和的几种写法

1.判断这个数对2取余是否为0,为0则为偶数

sum = 0
a = 0
while a <= 100:
    if a % 2 == 0:
        sum =sum + a
        print(a)
    a = a + 1
print('1-100之间的偶数和',sum)

2.判断这个数对2取余是否为0,为0则为偶数,0的bool值为FALSE,FALSE就不执行,所以就是计算的奇数的和

sum = 0
a = 0
while a <= 100:
    if bool (a % 2):
        sum =sum + a
        print(a)
    a = a + 1
print('1-100之间的偶数和',sum)

3.判断这个数对2取余是否为0,为0则为偶数,0的bool值为FALSE,FALSE就不执行,所以就是计算的奇数的和,再加个not就是计算的偶数的和

sum = 0
a = 0
while a <= 100:
    if not bool (a % 2):
        sum =sum + a
        print(a)
    a = a + 1
print('1-100之间的偶数和',sum)

你可能感兴趣的:(python,python)