了解Python控制流语句——while 语句

while 语句

Python 中 while 语句能够让你在条件为真的前提下重复执行某块语句。 while 语句是 循环(Looping) 语句的一种。while 语句同样可以拥有 else 子句作为可选选项。

案例(保存为 while.py):

number = 23
running = True

while running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        # 这将导致 while 循环中止
        running = False
    elif guess < number:
        print('No, it is a little higher than that.')
    else:
        print('No, it is a little lower than that.')
else:
    print('The while loop is over.')
    # 在这里你可以做你想做的任何事

print('Done')

输出:

$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

它是如何工作的

在这一程序中,我们依旧通过猜数游戏来演示,不过新程序的优点在于能够允许用户持续猜测直至他猜中为止——而无需像我们在上一节中所做的那样,每次猜测都要重新运行程序。这种变化恰到好处地演示了  while 语句的作用。

首先我们将 input 与 if 语句移到 while 循环之中,并在 while 循环开始前将变量 running 设置为 True。程序开始时,我们首先检查变量 running 是否为 True,之后再执行相应的 while 块。在这一代码块被执行之后,将会重新对条件进行检查,在本例中也就是 running 变量。如果它依旧为 True,我们将再次执行 while 块,否则我们将继续执行可选的 else 块,然后进入到下一个语句中。

else 代码块在 while 循环的条件变为 False 时开始执行——这个开始的时机甚至可能是在第一次检查条件的时候。如果 while 循环中存在一个 else 代码块,它将总是被执行,除非你通过 break 语句来中断这一循环。

True 和 False 被称作布尔(Boolean)型,你可以将它们分别等价地视为 1 与 0

以上为Python教程中最常用的语句,也是必须掌握的。

针对 C/C++ 程序员的提示

你可以在 while 循环中使用 else 从句。

原文地址:https://www.cnblogs.com/yuanrenxue/p/10668863.html