while只要条件为真,该语句就可以重复执行语句块。一个while说法是所谓的一个例子循环语句。一条while语句可以有一个可选的else子句。
示例(另存为while.py): number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
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循环,并设置变量running来Truewhile循环之前。首先,我们检查变量running是否为True,然后继续执行相应的while-block。执行该块后,将再次检查条件,在这种情况下为running变量。如果为true,则再次执行while块,否则继续执行可选的else块,然后继续执行下一条语句。 else当while循环条件变为时执行该块False-这甚至可能是第一次检查该条件。如果有循环else子句while,则除非您使用break语句退出循环,否则它将始终执行。
该True和False被称为布尔类型,你可以认为他们是等同于价值1和0分别。 C / C ++程序员注意事项 请记住,您可以else为while循环添加一个子句。
|