【python基础学习】三、while循环、continue、break

i=0
i++
i<3

i=1
i++
i<=3

程序的流程

  • 顺序 :从上向下
  • 分支:条件判断,决定执行分支
  • 循环: 特定代码 重复执行

while循环

例:

i = 1
# 容易忘记写 :
while i <=10:
    print("哦嚯")
    i=i+1

print("done!")

# 若将i自增注释掉,则变为死循环

赋值运算符

在这里插入图片描述

练习0-100求和

# 0-100 求和
result = 0
i=0
while i<=100:
   i += 1
   result += i
print("结果是%d"%result)
   

练习0-100偶数求和

# 0-100 偶数 求和
result = 0
i=0
while i<=100:

    if i%2 ==0:
        result += i
    i += 1

print("偶数累加结果是%d"%result)

在循环体内部的关键字

break 和 continue 都只对当下循环有效

break

直接退出循环

i = 0
while i < 10:
    print(i)
    i += 1
    if i == 3:
        break
0
1
2

continue

排除某一条件后 继续执行原循环

i = 0
while i<10:
    i += 1  # 使用continue 计数器必须修改,否则死循环
    
    # 在这个循环里 i为3 以后立刻跳转到while
    if i == 3 :
        continue
    print(i)
    # 如果i自增是在这里的,则代码陷入死循环
  
1
2
4
5
6
7
8
9
10

循环嵌套

打印小星星

row = 1

while row <= 5:
    print("*"*row)
    row +=1
    
*
**
***
****
*****

print 函数默认换行

print("*" , end="")

row = 1

while row <= 5:
    col = 1
    while col <= row:
        print("*",end="")
        col += 1

    row +=1
***************
row = 1

while row <= 5:
    col = 1
    while col <= row:
        print("*",end="")
        col += 1

    row +=1
    print("") # 每一行结束后换行

乘法表


row = 1


while row <= 9:
    col = 1
    while col <= row:
        print(" %d * %d = %d" % (col , row, col * row),end = "")
        col += 1
    row += 1
    print("")
\t   # 垂直对齐
\n 	 # 换行
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值