Break Statement

Before you head into the text, watch the video:

Here's a really cool way to apply the break statement.

Say you want to print the all the multiples of the number 4 that are less than 40.

You could go the usual way and create a for loop and loop through a range of (1, 40) ... or you could do this:

When we don't really have a condition but we want to make a loop anyway, we use 'while True' - which will always be True as it doesn't actually refer to any location in the memory.

In the first if clause, we check if n is divisible by 4 or not using the modulus operator (it returns the remainder for when the first number is divided by the second). If the remainder is 0, n is printed.

After this, we add 1 to n in each iteration. Then, in the second if clause, we check if n is still less than 40. If it is, the loop keeps going. The iteration where n becomes 40, the break statement is run and the loop is terminated.

So, we get all multiples of 4 in the interval (1, 40) and then the loop ends. Pretty neat, isn't it?

Aight that's all for today. Leave any questions you might have in the comments section and I'll talk about continue next week.

Cya!