python学习之while循环

时间:2023-03-08 21:18:14

Python While 循环语句

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

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

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

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

执行流程图如下:

python学习之while循环

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

 #coding=utf-8
'''
@author:Nelson.huang
@Date : 2017.07,25
@Funtion: while循环的练习:
用户输入一个小于1000的数字,输出所有结果,并停在用户输入的结果这里,并且询问用户是否继续循环。
如果用户输入非‘N’的字符串,继续循环,并再次要求用户输入一个停下来的数字,继续。 ''' print_num = input('Please input the count :')
count = 0
while count < 1000:
if count == print_num:
print "There you got the number:", count
choice = raw_input('Do you want to continue to loop?(y/n):')
if choice == 'n':
break
else:
print_num = input('Please re-input the count:') if print_num < count:
print 'your num is passed, please re-input:'
print_num = input('Please input the count :')
continue else:
print 'loop:', count 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):