MWZ

MINDWAREZONE

Break in python

  • The break statement is used to immediately exit a loop.
  • When break is executed, the loop stops running, even if there are remaining iterations.
  • It can be used inside both for and while loops.

Example 1: Break in a for Loop

for num in range(1, 6): 
    if num == 4: 
        break 
    print(num)
            

Output

1
2
3
            

Example 2: Break in a while Loop

count = 1 

while count <= 5: 
    if count == 3: 
        break 
    print(count) 
    count += 1
            

Output

1
2