In Python, the break
statement is used to terminate a loop prematurely. When a break
statement is encountered inside a loop, it causes the loop to immediately terminate, regardless of whether the loop has finished all of its iterations or not.
The break
statement is commonly used with conditional statements, such as if
and while
, to provide a way to exit the loop early if certain conditions are met.
Here’s an example of using the break
statement with a while
loop:
i = 0 while i < 10: print(i) i += 1 if i == 5: break
In this example, the loop will print out the numbers from 0 to 4, but as soon as i
reaches 5, the break
statement is executed, and the loop is terminated.
The break
statement can also be used with for
loops, as shown in this example:
for i in range(10): print(i) if i == 5: break
In this example, the loop will print out the numbers from 0 to 5, but as soon as i
reaches 5, the break
statement is executed, and the loop is terminated.
Break statement with while loop:
Certainly! Here’s an example of using the break
statement with a while
loop in Python:
count = 0 while count < 5: print("Count is:", count) count += 1 if count == 3: break
In this example, we initialize a variable count
to 0, and then use a while
loop to print out the value of count
and increment it by 1 on each iteration. However, we also have an if
statement inside the loop that checks if count
has reached the value of 3. If it has, we use the break
statement to exit the loop early.
If we run this code, we’ll get the following output:
Count is: 0 Count is: 1 Count is: 2
As you can see, the loop terminates after the third iteration because we used the break
statement when count
was equal to 3. Without the break
statement, the loop would continue to run until count
reached 5, and we would see the output Count is: 3
and Count is: 4
as well.