BREAK STATEMENT
BREAK STATEMENT
In Python, the break
statement is used to exit or terminate a loop prematurely. It is commonly used with loop structures like for
and while
to control the flow of execution. When a break
statement is encountered inside a loop, the loop is immediately exited, and the program continues executing from the next statement after the loop.
Here's the general syntax of the break
statement in Python:
SYNTAX:
while condition: # code block if condition: break # more code
In the while
loop example, the loop continues to execute as long as the given condition is true. However, when the if
statement's condition is met, the break
statement is executed, and the loop terminates immediately.
SYNTAX:
for item in sequence: # code block if condition: break # more code
Similarly, in the for
loop example, the loop iterates over a sequence of items. When the if
statement's condition is satisfied, the break
statement is triggered, and the loop is terminated
CODE:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
# Output: # 1 # 2
Comments
Post a Comment