python while 循环

while 循环

 

while 条件:
代码块



1,死循环

#!/usr/bin/env python
import time
while n1:
  print('1')
  time.sleep(1)
print('end')

 



2,可控制循环

#!/usr/bin/env python
import time
n1 = True
while n1:
  print('1')
  time.sleep(1)
  n1=False

print('end')

 




使用到time模块 time.sleep(1)


1,需求1:
输出 1 2 3 4 . . . . .. . . .

#!/usr/bin/env python
import time
n1 = 0
while True:
    n1 = n1 + 1
    time.sleep(1)
    print(n1)    
print('end')

 

 

或者

#!/usr/bin/env python
import time
n1=1
while True:
  print(n1)
  time.sleep(1)
  n1 = n1 + 1    
print('end')

 

2,需求2
只打前10个数字

#!/usr/bin/env python
import time
n1 = 1
n2 = True
while n2:
  print(n1)
  time.sleep(1)
  n1 = n1 + 1
  if n1 == 11:
    n2 = False

print('end')

 

 

跳出循环体-break

break 的作用:
可以跳出当前循环体,不继续循环下去,循环体里面的代码不执行,但是外面的代码依然需要执行。


#!/usr/bin/env python
n1 = 1
while True:
    print(n1)
    if n1 == 10:
        break
    n1 = n1 + 1
print('end')


 

输出结果为: 1 2 。 。 。 。 10 end

 continue 作用:
跳出本次循环,继续下次循环

对比:break  continue 

#!/usr/bin/env python
while True:
        print('good')
        break
        print('boy')
print('end')

打印good 后再打印end结束



#!/usr/bin/env python
while True:
    print('good')
    continue
    print('boy')
print('end')

一直打印good (结束本次循环)

 

 需求3:打印1到10的整数,排除7.

n1 = 1
while True:
    if n1 == 7:
        n1 = n1 +1
        continue
    print(n1)
    #n1 = n1 +1
    n1 += 1
    if n1 == 10:
        break

简单说明: n1 = n1 + 1 ==> n1 += 1
n1 = True
n2 = 1
while n1:
    print(n2)
    n2 = n2 + 1
    if n2 == 7:
        n2 = n2 +1
    elif n2 == 10:
        n1 = False

 

posted @ 2017-02-21 20:52  某电商首席日志工程师  阅读(299)  评论(0编辑  收藏  举报