'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! π
As you can see by the (very subtle hahaha π) graphics below, the
break
statement is the code equivalent of a “STOP” signal.π§ 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 ✨).✅ 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 toTrue
. - Then, we check the if statement condition. In the first iteration, the condition
num > 9
is notTrue
, 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 isTrue
. Since we are increasing the value ofnum
by1
on every iteration and the initial value is5
, we will definitely reach the value9
and the conditionnum > 9
will beTrue
. - 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.
✅ 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.
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
Post a Comment