while(for)循环

本文详细介绍了Python中的while和for循环结构,包括它们的使用场景、实例演示以及嵌套循环。重点讨论了计算1~1000偶数和和while嵌套案例,展示了循环控制语句的实际操作。同时涵盖了break、continue和else语句的应用。
摘要由CSDN通过智能技术生成

while循环语句

ha = 3
while ha == 2 :		#表达式永远为true
    nu = float(input("立即键入一个数字哦:"))
    print("你输入的东西是:",nu)
print("结束")

for循环

for i in [0,1,2]:
    print(i)
0
1
2

for i in range(1,4):
    print(i)
1
2
3

while循环案例——计算1~1000偶数和

i = 0
sum = 0
while i < 101:
    if i % 2 == 0:
        sum += i
    i += 1
print("1到100之间偶数和为:%s"%sum)
print("1到100之间偶数和为:",sum)
1到100之间偶数和为:2550
1到100之间偶数和为: 2550

while嵌套案例

i = 1
while i < 6:
    j = 0
    while j < i:
        print("*",end="")
        j += 1
    print("\n")
    i += 1
*

**

***

****

*****

for语句中的其他语句
break语句

for i in range(8):
    print("------")
    if i == 3:
        break
    print(i)
------
0
------
1
------
2
------

continue语句

for i in range(8):
    i += 1		#从1开始
    print("------")
    if i == 5:
        continue	#结束上面的5,从下一个开始
    print(i)
------
1
------
2
------
3
------
4
------
------
6
------
7
------
8

pass语句

for letter in 'Runoob':
    if letter == "o":
        pass
        print('执行pass模块')
    print('当前字母:',letter)
print("bye!")
当前字母: R
当前字母: u
当前字母: n
执行pass模块
当前字母: o
执行pass模块
当前字母: o
当前字母: b
bye!

else语句

count = 0
while count < 5:
    print(count,"is less than 5")
    count += 2
else:
    print(count,"is not less than 5")
0 is less than 5
2 is less than 5
4 is less than 5
6 is not less than 5
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值