Break And Continue Statement In Python

Break Statement : 

The break statement in Python is used to exit a loop early, before the loop condition is met. When the break statement is encountered inside a loop, the current iteration of the loop is terminated and the program control resumes at the next statement following the loop. It is commonly used in conjunction with a conditional statement to create an exit point for the loop. For example, the following code uses a while loop to repeatedly input numbers from the user until they enter a negative number, at which point the loop exits:

while True:                                    
    number = int(input("Enter a number: "))    
    if number < 0:                             
        break                                  
    print("You entered:", number)              
print("Negative number entered, loop exited.") 


It's also worth noting that a break statement can also be used to exit a nested loop when placed inside the inner loop.
The break statement is used to exit a loop early, before the loop condition is met. It can be used in both for and while loops to immediately end the iteration and move on to the next statement after the loop. For example:

for i in range(10):        
    if i == 5:             
        break              
    print(i)               

This code will print the numbers 0-4 and then exit the loop when it reaches 5, instead of continuing to print the numbers up to 9.

Continue statement :

The continue statement in Python is used to skip the current iteration of a loop and move on to the next iteration. It is used inside a loop (for or while) and causes the program to immediately proceed to the next iteration of the loop, without executing any of the remaining statements in the current iteration.

For example:

for i in range(10):    
    if i == 5:         
        continue       
    print(i)           

This will output the numbers 0 to 4, and then 6 to 9, because when i is 5, the continue statement is executed and the print(i) statement is skipped.


Post a Comment

0 Comments