Python Break, Continue and Pass

  • Python

In Python, Break, Continue and Pass are a few statements that we use to modify the flow control in code. In this tutorial, we will learn to use these statements.

In a regular loop statement, the code will end only when the condition applied turns false but what if you want to intermediary end the loop? Break and continue will be used in this situation.

Python break Statement

The break statement is used to end the loop instantly.

Let’s understand this using an example where the code will end while traversing through a list of random numbers as soon as it access number 0.

var = [1, 3, 54, 0, 78, 11]

for i in var:
  if i == 0:
    break
  print(i)

Output :

1
3
54

Let’s check another example with while loop.

x = 6
y = 7

i = 1

while i <= y:
  if i > x:
    break

  print(i)
  i = i + 1 
  
print("Exit") 

Output :

1
2
3
4
5
6
Exit

In the above example, we initially set a limit of 6. The condition was “as soon as the value is greater than the limit”, it will break out of the loop and will exit.

Python continue Statement

Like break statement is used to break out of the loop, continue statement is used to skip the current iteration but the rest of the code remains unaffected. The rest of the code is executed as it should.

Let’s understand this using the same example we used for break statement. With break, the code was terminated as soon as it reached 0. Let’s check for continue.

var = [1, 3, 54, 0, 78, 11]

for i in var:
  if i == 0:
    continue
  print(i)

Output :

1
3
54
78
11

As mentioned before, it skipped that part and ran the rest of the code.

Python pass Statement

Since we cannot leave a loop without a code, pass statement is used to avoid an error. Let’s understand this with an example where we’ll skip all the even numbers and only print the odd in a range of 10.

for i in range(11):
  if i%2 == 0:
    pass
  else:
    print(i)

Output :

1
3
5
7
9

In the above example, pass statement just ignored that piece of code.