
上QQ阅读APP看书,第一时间看更新
Breaking out of loops
Conditional statements can be used to break out of a loop execution (for loop and while loop). When a specific condition is met, an if statement can be used to break out of a loop:
i = 0
while True:
print("The value of i is ", i)
i += 1
if i > 100:
break
In the preceding example, the while loop is executed in an infinite loop. The value of i is incremented and printed on the screen. The program breaks out of the while loop when the value of i is greater than 100 and the value of i is printed from 1 to 100.