官术网_书友最值得收藏!

The while loop

while loops are not encountered as frequently in Python. A while loop executes as long as a statement is true. The simplest while loop would be a while True statement. This kind of loop would execute forever since the Boolean object True is always True and so the indented code would continually execute.

If you are not careful, you can inadvertently create an infinite loop, which will wreak havoc on your script's intended functionality. It is imperative to utilize conditionals to cover all your bases such as if, elif, and else statements. If you fail to do so, your script can enter an unaccounted situation and crash. This is not to say that while loops are not worth using. while loops are quite powerful and have their own place in Python:

>>> guess = 0
>>> answer = 42
>>> while True:
... if guess == answer:
... print('You've found the answer to this loop: ' + str(answer))
... break
... else:
... print(guess, 'is not the answer.')
... guess += 1

The break, continue, and pass statements are used in conjunction with for and while loops to create more dynamic loops. The break escapes from the current loop, while the continue statement causes the PVM to begin executing code at the beginning of the loop, skipping any indented code following the continue statement. The pass statement literally does nothing and acts as a placeholder. If you're feeling brave or bored, or worse, both, remove the break statement from the previous example and note what happens.

主站蜘蛛池模板: 安溪县| 准格尔旗| 鄱阳县| 乳源| 兴仁县| 大石桥市| 新宁县| 安徽省| 库尔勒市| 福建省| 延川县| 武乡县| 左权县| 沂水县| 万州区| 富宁县| 色达县| 青龙| 哈尔滨市| 华安县| 青海省| 玉溪市| 永顺县| 利川市| 玉树县| 浏阳市| 西充县| 陇川县| 瓮安县| 湖北省| 大竹县| 仁寿县| 蒙自县| 大关县| 定结县| 济南市| 卢湾区| 松桃| 高青县| 云阳县| 台江县|