Oct. 22, 2015

Break and Continue Statements

Break statements exist in Python to exit or "break" a for or while conditional loop. When the loop ends, the code picks up from and executes the next line immediately following the loop that was broken. 


numbers = (1, 2, 3)
num_sum = 0
count = 0
for x in numbers:
        num_sum = num_sum + x
        count = count + 1
        print(count)
        if count == 2:
                break

In this example, the loop will break after the count is equal to 2.

 

The continue statement is used to skip code within a loop for certain iterations of the loop. After the code is skipped, the loop continues where it left off. 


for x in range(4):
   if (x==2):
      continue
   print(x)

This example would print all numbers from 0-4 except 2.

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.