Python 中 while 循环的几个例子

发表于:2023-4-25 09:13

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:TIAP    来源:TIAP

  说起编程语言中的循环,一般 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......")
  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号