Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。当然也可以遍历所有的字符串,列表,元祖等。
其基本形式为:
while 判断条件:
执行语句……
执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假false时,循环结束。
for 循环一般是用在一个有次数的循环上。
while 循环用在有条件的控制上。
来个容易上手的例子:
n = 0 ## 给n赋值初始值 0
while True: ## True为表达式成立
if n == 10: ## 当 n==10的时候
break ## 跳出循环
print n, 'hello' ## 打印 ‘hello’
n += 1 ## n=n+1
## 整体的程序是:使用while循环打印hello,当n==10 的时候就会停止。
执行结果:
0 hello
1 hello
2 hello
3 hello
4 hello
5 hello
6 hello
7 hello
8 hello
9 hello
手动选择停止 while 循环:
while True:
aa = raw_input("pls input anything you want, use 'quit' to stop: ")
if aa == 'quit':
break
输出的结果是:
pls input anything you want, use 'quit' for stop: qawe
pls input anything you want, use 'quit' for stop: 123
pls input anything you want, use 'quit' for stop: q12
pls input anything you want, use 'quit' for stop: quit
Process finished with exit code 0
在 python 中,while … else 在循环条件为 false 时执行 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