Skip to content

Python continue vs break vs pass

  • by

Python continues vs break vs pass have very minor differences but logically make a higher difference. Python provides a break used to exit a loop completely continue statements skip a part of the loop and start the next execution.

Python pass statement is used as a placeholder inside loops, functions, classes, and if-statements is meant to be implemented later.

continuebreakpass
The continue statement skips only the current iteration of the loop.The break statement terminates the loop.The pass statement is used to write empty code blocks.
We can use the continue statements only inside a loop.We can use break statements only inside a loop.We can use pass statements anywhere in the Python code.

The break Statement: When encountered inside a loop, break immediately exits the loop, regardless of whether the loop’s condition has been satisfied or not. It terminates the entire loop.

# First Example
for letter in 'Hello':
    if letter == 'e':
        break
    print('Current Letter :', letter)

# Second Example
var = 5
while var > 0:
    print('Current variable value :', var)
    var = var - 1
    if var == 2:
        break

print("Good bye!")

Output:

Python continue vs break vs pass

The continue Statement: When encountered inside a loop (such as for or while), continue immediately stops the current iteration of the loop and proceeds to the next iteration, bypassing the rest of the code inside the loop for the current iteration.

# First Example
for letter in 'Hello':
    if letter == 'e':
        continue
    print('Current Letter :', letter)

# Second Example
var = 5
while var > 0:
    print('Current variable value :', var)
    var = var - 1
    if var == 2:
        continue

print("Good bye!")

Output:

Current Letter : H
Current Letter : l
Current Letter : l
Current Letter : o
Current variable value : 5
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Good bye!

The pass Statement: pass is a null operation, meaning it does nothing. It acts as a placeholder when a statement is syntactically required but you want to do nothing. It is often used as a placeholder for code that will be implemented later.

for letter in 'Python':
    if letter == 'h':
        pass
        print('This is pass block')
    print('Current Letter :', letter)

print("Good bye!")

Output:

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading