Python while 循环使用实例

时间:2016-06-07
while循环是在Python中的循环结构之一。 while循环继续,直到表达式变为假。表达的是一个逻辑表达式,必须返回一个true或false值,本文章向码农介绍Python while 循环使用方法,需要的朋友可以看一下本文章。

一个循环是一个结构,导致第一个程序要重复一定次数。重复不断循环的条件仍是如此。当条件变为假,循环结束和程序的控制传递给后面的语句循环。

while循环:

while循环是在Python中的循环结构之一。 while循环继续,直到表达式变为假。表达的是一个逻辑表达式,必须返回一个true或false值
while循环的语法是:

while expression:
   statement(s)

这里首先计算表达式语句。如果表达式为true是,然后声明块重复执行,直到表达式变为假。否则,下一个语句之后的语句块被执行。
注:在Python中,所有的缩进字符空格后的编程结构相同数量的报表,被认为是一个单一的代码块的一部分。 Python使用缩进作为其语句分组的方法。
例如:

#!/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!

直到计数不再是小于9块,打印和增量语句组成,重复执行。每次迭代,指数计数当前值显示,然后增加1。

无限循环:

使用while循环,因为,这种情况从来没有解决一个假值的可能性时,你必须谨慎使用。这将导致一个循环,永远不会结束。这种循环被称为一个无限循环。

一个无限循环,可能是在客户机/服务器编程有用的服务器需要连续运行,使客户端程序可以与它沟通,并在必要时。
例如:

#!/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, innum = raw_input("Enter a number :")
KeyboardInterrupt

上面的例子会在infite循环,你将需要使用Ctrl + C程序来。

单个语句组: 类似的if语句语法,如果您同时子句只包含一个单独的语句,它可以放在同一行,
这里是一个行而子句的语法:

while expression : statement