Python----While循环

Python学习之路,点击有全套Python笔记

for循环用于针对集合中的每个元素的一个代码块,而while循环不断运行,直到指定的条件不满足为止
  • 基础版:1-100的累加
# while
i = 1
result = 0
while i <= 100:
    result += i
    i += 1
print(result)  # 5050
  • 进阶版 while+if,1-100的偶数和
i = 1
result = 0
while i <= 100:
    if i % 2 == 0:
        result += i
    i += 1
print(result)  # 2550
  • 使用break退出循环

break是终止循环,直接结束,不在运行余下的代码

i = 0
while i < 10:
    if i == 3:
        print('吃了' + str(i) + '碗米饭,吃饱了')
        break
    i += 1
  • 使用continue退出

continue是退出本次循环

i = 0
while i < 10:
    i += 1
    if i == 3:
        print('第' + str(i) + ('个苹果有虫子,换下一个'))
        continue
    print('吃了第' + str(i) + '苹果')
  • while+while
    一周内每天说三遍,PHP是世界上最好的语言
day = 1
while day < 8:
    NB = 1
    print('今天是第' + str(day) + '天')
    while NB < 4:
        print('PHP是世界上最好的语言')
        NB += 1
    day += 1
  • 实践 写九九乘法表
    i = 1
    while i < 10:
    j = 1
    while j <= i:
    print(f’{i}{j}={ij}’, end=" “)
    j += 1
    print(”\n")
    i += 1
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值