Break Statement
Now we will look at the break
statement, which allows us to exit a loop prematurely. Imagine you want to buy a house, so you look at houses for sale every day. Once you buy a house, you don't want to keep looking at houses because you already have one. The break
statement allows you to do this. The break
statement terminates the current loop.
For example, let's find the first even number between 1 and 10:
number = 1
while number <= 10:
if number % 2 == 0: # If the number is even
print(number)
break # Exit the loop
number = number + 1
This will print:
2
In this example, we go through numbers from 1 to 10. As soon as we encounter the first even number, we print it and exit the loop using break
.
Without break
, the loop would continue and print all even numbers in the sequence.
To explain the condition number % 2 == 0: the % operation returns the remainder of the division, and when the remainder of the division of number
by two is 0, it means that number
is even.
Instructions
Create a variable count
with an initial value of 1.
Using a while
loop, go through count
from 1 to 10 and print count
when it is greater than 5 and then exit the loop. Use the break
statement for this. Don't forget to increase the count
variable by 1.
Start programming for free
4/8