'Break' Statement: Behind the Scenes!




πŸ‘‹ Welcome!

You will use break during the course and in your future projects. It's very important that you understand how it works and when to use it. πŸ’»
Let’s begin! πŸ‘

link

As you can see by the (very subtle hahaha 😁) graphics below, the break statement is the code equivalent of a “STOP” signal.

image

πŸ”§ Use

With the break keyword you can stop the execution of while loops and for loops. If you have nested loops, you will stop the nearest enclosing loop. (You will see examples in this tutorial ✨).

image

✅ Break Statement and While Loops!

Let’s see a break statement inside a while loop and analyze the code in the image below:
  • Using while True means that you will enter an infinite loop if there is nothing stopping the loop because the condition will always evaluate to True.
  • Then, we check the if statement condition. In the first iteration, the condition num > 9 is not True, so we will not enter the if statement and the next lines will be executed.
    print(num)
    num += 1
  • This will happen until the num > 9 condition is True. Since we are increasing the value of num by 1 on every iteration and the initial value is 5, we will definitely reach the value 9 and the condition num > 9 will be True.
  • When this condition is True, we will enter the if statement, print the value AND EXECUTE BREAK! This will stop the loop immediately and then it will jump to the first line after the while loop.

image
image

✅ Break Statement and For Loops!

In for loops, the break statement works exactly the same. For example, we have this for loop that has a break statement. It will immediately stop executing when the i variable takes an even value.




✅ Break Statement and Nested Loops!

In nested loops, the break statement stops the nearest enclosing loop. For example, here we have nested for loops and the inner for loop has a break statement. When this break statement is executed, the inner loop will stop executing and the outer loop will continue.


link



I really hope you liked this tutorial! If you have any questions please do not hesitate to ask on the discussion forums, we will be very glad to help πŸ˜ƒ πŸ‘
Estefania.

Comments