Break and continue statement in python; In this tutorial, i am going to show you what is break and continue statements in python and how to use it with while and for loops.
Python Break and Continue Statement Example
- Python break statement
- Python continue statement
Python break statement
As the name itself suggests. The break statement is used to break the execution of the loop or any statement.
In Python programming, the break statement is used to terminate or exit the loop. starts executing the next statement.
Syntax of break Statement in Python
break
Example: Python break statement in for loop
# Use of python break statement with for loop for val in "python": if val == "t": break print(val) print("The end")
Output
p y The end
Explanation of above program
In the above program, we have iterated a string like “python”. And checked if the letter “t” matches the string. When “t” matches with the given, at the same time we terminate the loop by doing the break statement.
Example: Python break while loop
i = 1 n = 5 while i < n: print(i) if (i == 3): break i += 1
Output
1 2 3
Python continue statement
In Python, the continue statement is used to skip some blocks of code inside the loop and does not prevent execution.
By skipping the continue statement, a block of code is left inside the loop. But like the break statement, this statement does not end a loop.
Syntax of Continue Statement in Python
continue
Example: Python continue statement for loop
for val in "python": if val == "t": continue print(val) print("The end")
Output
p y h o n The end
Explanation of the above program
In the above program, we have iterated a string like “python”. And checked if the letter “t” matches the string. When “t” matches with the given, at the same time we skip the letter “t” and execute the next statement with using loop by doing the continue statement.
Example: Python Continue with While loop
i = 0 n = 5 while i < 5: i += 1 if i == 3: continue print(i)
Output
1 2 4 5