4.2_控制流2while__range语句.docx
1. while语句
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:
while判断条件:执行语句……
执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假false时,循环结束。
执行流程图如下:

python_while_loop
Gif 演示 Python while 语句执行过程

实例
#!/usr/bin/pythoncount = 0while(count < 9): print'The count is:', countcount = count + 1print"Good bye!"
运行实例 »
以上代码执行输出结果:
The count is:0The count is:1The count is:2The count is:3The count is:4The count is:5The count is:6The count is:7The count is:8Good bye!
while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:
设置 一直到 用户把 66 猜出来
#while example
number = 66
guess_flag = False
while guess_flag == False:
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
guess_flag = True
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that, keep guessing')
# you must have guessed > number to reach here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
print('Done')
Code:
#For example
number = 59
num_chances = 3
print("you have only 3 chances to guess")
for i in range(1, num_chances + 1):
print("chance " + str(i))
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
break
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# You can do whatever you want in a block ...
else:
print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left')
# you must have guessed > number to reach here
print('Done')