python 基础 2.4 while 循环
#/usr/bin/python
#coding=utf-8
#@Time :2017/10/18 15:31
#@Auther :liuzhenchuan
#@File :while 循环.py
示例1:
1 n = 0 2 while True: 3 print 'hello world' 4 if n == 10: 5 break 6 n +=1
打印如下:
1 hello world 2 hello world 3 hello world 4 hello world 5 hello world 6 hello world 7 hello world 8 hello world 9 hello world 10 hello world 11 hello world
示例2:
1 n = 0 2 while True: 3 if n==10: 4 break 5 print n ,'hello' 6 n +=1
打印如下:
1 0 hello 2 1 hello 3 2 hello 4 3 hello 5 4 hello 6 5 hello 7 6 hello 8 7 hello 9 8 hello 10 9 hello
示例3:
#条件为假的时候,也是退出循环.输入空字符的时候也退出循环
1 rinput = '' 2 while rinput !='q': 3 rinput = raw_input('please input something,q is quite: ') 4 print 'hello' 5 if rinput == '': 6 break
示例4:
#应用逻辑非判断,退出while循环。while条件为假时,退出while循环
1 rinput = '' 2 while rinput !='q': 3 rinput = raw_input('please input something,q is quite: ') 4 print 'hello' 5 if not rinput : 6 break
示例5:
# while...else...:正常结束while循环时会打印else后面的语句.与for...else...循环体一样
1 rinput = '' 2 while rinput !='q': 3 rinput = raw_input('please input something,q is quite: ') 4 print 'hello' 5 if not rinput : 6 break 7 else: 8 print 'hello world'
示例6:
#while 循环嵌套if循环体,支持contine
1 rinput = '' 2 while rinput !='q': 3 rinput = raw_input('please input something,q is quite: ') 4 print 'hello' 5 if not rinput : 6 break 7 elif rinput == 'quite': 8 continue 9 print 'continue' 10 else: 11 print 'hello world'