python写前100奇数或偶数相加的和

python写前100奇数或偶数相加的和,第1张

python写前100奇数偶数相加的和

文章目录
  • 一、偶数和
    • 1、使用while语句
    • 2、使用range语句
    • 3、
  • 二、奇数和
    • 1、使用while语句
    • 2.使用range语句
    • 3、

一、偶数和 1、使用while语句
a=0
y=a
while a<101:
    y += a
    a=a+2
    print(y)

结果
D:pythonpython.exe D:/python/md5.py
0
2
6
12
20
...
中间略
...
2256
2352
2450
2550

Process finished with exit code 0

2、使用range语句
x=range(0,101,2)
print(sum(x))
结果
D:pythonpython.exe D:/python/md5.py
2550

Process finished with exit code 0

3、
x=0
for i in range(101):
    if i%2==0:
       x+=i
print('偶数和为',x)


D:pythonpython.exe D:/python/md5.py
偶数和为 2550

Process finished with exit code 0

二、奇数和 1、使用while语句
a=1
y=0
while a<101:
    y +=a
    a=a+2
    print(y)
结果:
1
4
9
16
...
中间略
...
2025
2116
2209
2304
2401
2500

Process finished with exit code 0

2.使用range语句
x=range(1,101,2)
print(sum(x))

注:
D:pythonpython.exe D:/python/md5.py
2500

Process finished with exit code 0
3、
x=0
for i in range(101):
    if i%2==1:
       x+=i
print('偶数和为',x)


D:pythonpython.exe D:/python/md5.py
偶数和为 2500

Process finished with exit code 0

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4655418.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-06
下一篇2022-11-06

发表评论

登录后才能评论

评论列表(0条)

    保存