When Can I Use Break or Continue in Python

The Python break statement stops the loop in which the statement is placed. A Python continue statement skips a single iteration in a loop. Both break and continue statements can be used in a for or a while loop.


You may want to skip over a particular iteration of a loop or halt a loop entirely. That's where the break and continue statements come in. These statements let you control the flow of a loop.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses










By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Python's built-in break statement allows you to exit a loop when a condition is met. The continue statement allows you to skip part of a loop when a condition is met. In this guide, we're going to discuss how to use the Python break and continue statements.

Loop Refresher

Programmers use loops to automate and repeat similar tasks. One of the most commonly-used loops is a for loop. A for loop repeats a block of code as long as a certain condition is met. Here's the syntax for a for loop in Python:

for iterating_variable in range: 	run_code

The following for loop will iterate through a list of numbers from 0 through 2 and print them out:

for i in range(0,3): 	print(i)

Our code returns the following:

Our example code printed out the value i three times. This is a basic example of a loop. It demonstrates how a programmer can use loops to run repetitive tasks on a block of code.

Python Break Statement

The Python break statement stops the loop in which the statement is placed. When a break statement is executed, the statements after the contents of the loop are executed.

A break statement can be placed inside a nested loop. If a break statement appears in a nested loop, only the inner loop will stop executing. The outer loop will continue to execute until all iterations have occurred, or until the outer loop is broken using a break statement.

You can use break statements to exit a loop when a specific condition is met. You declare a break statement within your loop, usually under an if statement.

Break Python Example

For example, you may have a list of student names to print out. You want your program to stop after the second name has printed. This will let you verify that the program works. Here's an example of a program that uses a break statement to do so:

students = ["Paul", "Erin", "Connie", "Moira"]  for student in range(0, len(students)): 	if student == 2: 		break     else:         print(students[student])  	print("Counter is " + str(student))  print("Program Complete")

First, we declared a Python list. This list contains the names of students in the class. We then created a for loop. This loop prints out the name of each student to the Python shell.

Inside our for loop, we added a break statement. This statement will execute if a student has the index value 2 in our list. When the break statement runs, the loop will stop.

Our code returns the following:

Paul Counter is 0 Erin Counter is 1 Program Complete

Our program printed out the names of the first two students (who have the index values and 1 in our array). When the program reached the student with the index value 2, the loop is terminated. The Python print statement at the end of our program ran.

We used an else clause to tell our program what to do if our condition is not met. If our condition is not met, the name of the student over which we are iterating is printed to the Python console.

break statements cause a program to stop a loop. The program continues to execute the next statements in a main program after the loop has broken.

Python Continue Statement

The continue statement instructs a loop to continue to the next iteration. Any code that follows the continue statement is not executed. Unlike a break statement, a continue statement does not completely halt a loop.

You can use a continue statement in Python to skip over part of a loop when a condition is met. Then, the rest of a loop will continue running. You use continue statements within loops, usually after an if statement.

Continue Python Example

Let's use an example to illustrate how the continue statement in Python works. In the following example, we use a continue statement to skip printing the second name in our array and then continue iterating:

students = ["Paul", "Erin", "Connie", "Moira"]  for student in range(0, len(students)): 	if student == 2: 		continue     else: 		print(students[student])  	print("Counter is " + str(student))  print("Program Complete")

Our code returns the following:

Paul Counter is 0 Erin Counter is 1 Moira Counter is 3 Program Complete

Our continue statement executes when an external condition is triggered. In our program, this condition is "student == 2". When student is equal to 2, our program stops executing that iteration of the loop.

Our program continued iterating through subsequent list items after our continue statement was executed. If we had used a break statement, our loop would have stopped running entirely.

The continue statement has a number of use cases. For instance, say you were validating data. You may want your loop to skip an iteration if a value is blank. This is because a blank value could interrupt the flow of your validation code.

Conclusion

When you're working with loops in Python, you may want to skip over an iteration or stop your loop entirely. This is where continue and break statements are useful, respectively.

In this tutorial, we discussed how to use break and continue statements in Python to utilize loops in your code more effectively. Now you're ready to work with break, and continue statements like a Python expert!

To learn more about coding in Python, read our complete guide on How to Learn Python.

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

brownabse1982.blogspot.com

Source: https://careerkarma.com/blog/python-break-and-continue/

0 Response to "When Can I Use Break or Continue in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel