In Python, the break
statement is used to exit a loop prematurely. It is most commonly used inside a for
or while
loop. When the break
statement is encountered inside a loop, the loop is immediately terminated and the program control moves to the next statement after the loop.
Here is an example of how you can use the break
statement inside a for
loop:
# Print the numbers from 1 to 10, but exit the loop if the number is 5
for i in range(1, 11):
if i == 5:
break
print(i)
In this example, the for
loop iterates over the numbers from 1 to 10, and the if
statement checks if the current number is 5. If it is, the break
statement is executed and the loop is terminated.
You can also use the break
statement inside a while
loop in a similar way:
# Print the numbers from 1 to 10, but exit the loop if the number is 5
i = 1
while i <= 10:
if i == 5:
break
print(i)
i += 1
The break
statement is often used in conjunction with the continue
statement, which skips the rest of the current iteration and moves on to the next one.
For more information on the break
statement in Python, you can refer to the Python documentation or search online for tutorials and examples.
0 댓글