In Python, break statements are used to exit (or "break) a conditional loop that uses "for" or "while". After the loop ends, the code will pick up from the line immediately following the break statement. Here's an example:
even_nums = (2, 4, 6) num_sum = 0 count = 0 for x in even_nums: num_sum = num_sum + x count = count + 1 if count == 4 break
In the example above, the code will break when the count variable is equal to 4.
The continue statement is used to skip over certain parts of a loop. Unlike break, it doesn't cause a loop to be ended or exited, but rather it allows for certain iterations of the loop to be omitted, like this:
for y in range(7) if (y==5): continue print(y)
In this example, all iterations of the loop (numbers 0-7) will be printed except for the number 5, because by using the continue statement the loop was instructed to skip over y when it was equal to 5.
Practice on your own to see how you can use the break and continue statements. Understanding the difference and the purpose of these two statements will allow you to write code that is more clean and efficient.To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.