If you need to stop While Loop at specific point, use break
when you reach that point.
In this case we are stopping when x reaches number 5. After that point everything stops:
x = 0
while x < 10:
print(x)
if x == 5:
break
x = x + 1
Result:
0
1
2
3
4
5
>>>
What if we need to skip specific things. In that case use continue
. Please note - While Loop will run just fine, just specific numbers will be skipped.
In this example, we are skipping over numbers: 3, 5 and 7.
x = 0
while x < 10:
x = x + 1
if x == 3:
continue
if x == 5:
continue
if x == 7:
continue
print(x)
Result:
1
2
4
6
8
9
10
>>>
For Loops are also fun to work with. We will learn about them in next tutorial.
No comments:
Post a Comment