Sunday, April 20, 2025

Python Break, Continue

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

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...