Break and Continue Python Examples

In this post, you will learn to use break and continue statements in python with while and for loops.

Python break statement

As the name itself suggests. The break statement is used to break the execution of the loop or any statement.

In Python programming, the break statement is used to terminate or exit the loop. starts executing the next statement.

Syntax of break

break

Flowchart of python break statement

Example: Python break statement in for loop

# Use of python break statement with for loop

for val in "python":
    if val == "t":
        break
    print(val)

print("The end")

Output

p
y
The end

Explanation of above program

In the above program, we have iterated a string like “python”. And checked if the letter “t” matches the string. When “t” matches with the given, at the same time we terminate the loop by doing the break statement.

Example: Python break while loop

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

Output

1
2
3

Python continue statement

In Python, the continue statement is used to skip some blocks of code inside the loop and does not prevent execution.

By skipping the continue statement, a block of code is left inside the loop. But like the break statement, this statement does not end a loop.

Syntax of Continue

continue

Flowchart of python continue statement

Example: Python continue statement for loop

for val in "python":
    if val == "t":
        continue
    print(val)

print("The end")

Output

p
y
h
o
n
The end

Explanation of the above program

In the above program, we have iterated a string like “python”. And checked if the letter “t” matches the string. When “t” matches with the given, at the same time we skip the letter “t” and execute the next statement with using loop by doing the continue statement.

Example: Python Continue with While loop

i = 0
n = 5
while i < 5:
  i += 1
  if i == 3:
    continue
  print(i)

Output

1
2
4
5

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *