首页 > 代码库 > python学习之while循环

python学习之while循环

    

Python While 循环语句

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件:
    执行语句……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件假false时,循环结束。

执行流程图如下:

技术分享

while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:

 1 #coding=utf-8
 2 ‘‘‘
 3 @author:Nelson.huang
 4 @Date  : 2017.07,25
 5 @Funtion: while循环的练习:
 6          用户输入一个小于1000的数字,输出所有结果,并停在用户输入的结果这里,并且询问用户是否继续循环。
 7          如果用户输入非‘N’的字符串,继续循环,并再次要求用户输入一个停下来的数字,继续。
 8 
 9 ‘‘‘
10 
11 print_num = input(Please input the count :)
12 count = 0
13 while count < 1000:
14     if count == print_num:
15         print "There you got the number:", count
16         choice = raw_input(Do you want to continue to loop?(y/n):)
17         if choice == n:
18             break
19         else:
20             print_num = input(Please re-input the count:)
21 
22     if print_num < count:
23         print your num is passed, please re-input:
24         print_num = input(Please input the count :)
25         continue
26 
27     else:
28         print loop:, count
29 
30     count +=1
执行结果:

C:\Python27\python.exe C:/Work/python/while.py
Please input the count :5
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
There you got the number: 5
Do you want to continue to loop?(y/n):y
Please re-input the count:8
loop: 5
loop: 6
loop: 7
There you got the number: 8
Do you want to continue to loop?(y/n):y
Please re-input the count:4
your num is passed, please re-input:
Please input the count :16
loop: 8
loop: 9
loop: 10
loop: 11
loop: 12
loop: 13
loop: 14
loop: 15
There you got the number: 16
Do you want to continue to loop?(y/n):



 

python学习之while循环