If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, the
break
statement is used to exit (terminate) a loop prematurely. When thebreak
statement is encountered inside a loop (e.g.,for
orwhile
loop), the loop execution immediately stops, and the program continues with the first statement after the loop.The
break
statement is often used in combination with conditional statements (if
,else
,elif
) to exit the loop based on specific conditions.Here's an example of how the
break
statement works in afor
loop:pythonCopy code
for num in range(1, 11): if num == 5: break print(num)
Output:
Copy code
1 2 3 4
In this example, the
for
loop iterates over the numbers from 1 to 10 using therange()
function. When the value ofnum
becomes 5, theif
statement checks the conditionnum == 5
, which evaluates toTrue
. As a result, thebreak
statement is executed, causing the loop to terminate prematurely. Therefore, only the numbers 1 to 4 are printed, and the loop stops oncenum
becomes 5.The
break
statement can also be used with awhile
loop to exit the loop based on certain conditions.Example using
break
with awhile
loop:pythonCopy code
count = 0 while True: print("Current count:", count) count += 1 if count >= 5: break
Output:
sqlCopy code
Current count: 0 Current count: 1 Current count: 2 Current count: 3 Current count: 4
In this example, the
while
loop runs indefinitely (while True
) and prints the value ofcount
in each iteration. However, when the value ofcount
becomes 5 or greater, theif
statement withbreak
is executed, causing the loop to break and terminate.The
break
statement is useful when you want to exit a loop early based on certain conditions. It helps to prevent unnecessary iterations and can be a valuable tool for controlling the flow of your program.
Comments: 0