51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 398|回复: 0
打印 上一主题 下一主题

[资料] 分享Python 中 while 循环的几个例子

[复制链接]
  • TA的每日心情
    无聊
    3 天前
  • 签到天数: 941 天

    连续签到: 3 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2023-4-25 14:41:28 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    说起编程语言中的循环,一般 for 循环用的时候比较多,因为相比于 while 循环,for 循环的代码量更少。不过有时候也会用到 while 循环。如果你知道其他编程语言(比如C/C++,Java),那么就会比较容易的理解 Python 中的 while 循环。
      今天我们介绍几个关于 while 循环比较典型的例子,以便大家了解 while 循环是什么以及它是如何工作的。
      Python 中的 while 循环
      while 循环会执行其下面的语句,直到条件为 true。重复执行这些语句也被称为迭代。
      除非条件为 false,否则它将继续执行相同的语句。并且,当条件为 false 时,它会跳过 while 循环下的语句,并执行程序中的下一个语句。
      所以,如果你的设定条件一直为 true,那么它就会是一个无限循环,你必须关闭程序才能停止执行。在本文中我们也将介绍一个无限 while 循环的例子。
      例子1:用 Python 打印一系列数字
      看下面代码:
      number = 0
      while number <=5:
          print(number)
          number +=1
      print("Printed a range of numbers")


      上述例子中,我们使用小于等于运算符来作为循环的条件,循环体中将数字 number + 1 以执行下次循环。
      如果你熟悉 for 循环,可以很容易的看出,使用 while 循环所需要写的代码更多。
      例子2:在 while 循环中使用 if 语句
      看下面代码:
      number = 0
      while number <=5:
          print(number)
          if number == 2:
             print(number)
          number +=1
      print("Printed!")


      在上面例子中,当 number 为 2 的时候,会再次打印 number。就想你平时使用 if 一样,可以根据需要在 while 中使用。
      例子3:使用 while 和 else
      在其他大多数编程语言中,else 往往都是与 if 配对使用的,从未听过 else 与 while 配对使用。这就是 Python 比较特别的地方,看下面的代码:?
      number = 0
      while number <=5:
          print(number)
          number +=1
      else:
        print("Done printing numbers till 5")


      这里需要重申:上述代码没有写错(你也没有看错),else 是上面的 while 循环后的语句。意思是当 while 循环条件为 false 而结束循环后所需要执行的语句。
      例子4:在 while 循环中使用 break 语句
      在 while 循环中遇到 break 语句时,它会停止并跳出循环,然后执行后面的语句。如下所示代码:?
      number = 0
      while number <=5:
          print(number)
          if number == 2:
             break
          number +=1
      print("Printed!")


      例子5:在 while 循环中使用 continue 语句
      当 while 循环中遇到 continue 语句,它会忽略 continue 就后面的代码,直接执行下一次循环。如下代码:
      number = 0
      while number <=5:
          number +=1
          if number == 2:
             continue
          print(number)
      print("Printed!")


      例子6:无限循环
      如果循环条件永远为 true,那么这就是一个无限循环,如下例子:?
      while 1==1:
        print("Looping......")



    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-3 17:28 , Processed in 0.065770 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表