Python 中的 while 循环函数

首页 / Python2入门教程 / Python 中的 while 循环函数

只要给定的条件为真,Python编程语言中的while循环语句就会重复执行目标语句。

while loop - 语法

Python编程语言中while循环的语法是-

while expression:
   statement(s)

while loop - 流程图

while loop in Python

在这里,while循环的关键点是循环可能永远不会运行。当测试条件并且输出为false时,将跳过循环体,并执行while循环后的第一个语句。

while loop - 示例

#!/usr/bin/python

count=0
while (count < 9):
   print 'The count is:', count
   count=count + 1

print "Good bye!"

执行上述代码时,将生成以下输出-

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

此处由PRINT和INCREMENT语句组成的块将重复执行,直到COUNT不再小于9。每次迭代都会显示索引COUNT的当前值,然后增加1。

while loop - 无限循环

如果条件从未变为假,则循环成为无限循环。在使用While循环时必须谨慎,因为此条件可能永远不会解析为False值。这导致了一个永无止境的循环。这样的循环称为无限循环。

#!/usr/bin/python

var=1
while var == 1 :  # This constructs an infinite loop
   num=raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"

执行上述代码时,将生成以下输出-

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number between :Traceback (most recent call last):
   File "test.py", line 5, in <module>
      num=raw_input("Enter a number :")
KeyboardInterrupt

上面的示例是无限循环的,你需要使用CTRL+C退出程序。

Else与循环使用

Python支持将else语句与循环语句相关联。

  • 如果ELSE语句与FOR循环一起使用,则当循环用完迭代列表时,将执行ELSE语句。

  • 如果Else语句与While循环一起使用,则当条件变为False时,将执行Else语句。

    无涯教程网

下面的示例说明了else语句与while语句的组合,该语句将打印小于5的数字,否则将执行else语句。

#!/usr/bin/python

count=0
while count < 5:
   print count, " is  less than 5"
   count=count + 1
else:
   print count, " is not less than 5"

执行上述代码时,将生成以下输出-

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

while loop - 单语句

与if语句语法类似,如果while子句只由一条语句组成,则它可以放置在While标头所在的同一行上。

下面是一行WHILE子句-的语法和

#!/usr/bin/python

flag=1
while (flag): print 'Given flag is really true!'
print "Good bye!"

最好不要尝试上面的示例,因为它进入无限循环,你需要按CTRL+C键退出。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

透视HTTP协议 -〔罗剑锋(Chrono)〕

编译原理之美 -〔宫文学〕

研发效率破局之道 -〔葛俊〕

DDD实战课 -〔欧创新〕

说透敏捷 -〔宋宁〕

Serverless入门课 -〔蒲松洋(秦粤)〕

如何看懂一幅画 -〔罗桂霞〕

A/B测试从0到1 -〔张博伟〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

好记忆不如烂笔头。留下您的足迹吧 :)