Python break statement is used to stop current code flow and change to the upper flow. The break statement is generally used with loop statements in order to stop current code flow. Alternatively break statement can be used for other cases like in functions. In this tutorial we examine how to use Python break statement with examples.
break Statement Syntax
The break statement has very simple syntax where it used alone in a line. There is no parameter, extra statement to add. When the break statement is reached the current code block execution is finished.
break
Break For Loop
One of the most popular usage for the break statement is using it with for loop
. The break statement is generally set for a specific conditions by using the if statement
. In the following example we iterate over the list named names
and check every item before print. If the current item is “ahmet” the for loop stopped with the break statement.
names = ["ismail","ahmet","ali"]
for name in names:
if name == "ahmet":
break
print(name)
Break While Loop
The break statement can be also used with the while loop
. In the following example we iterate forever with the while statement and and check every name before printing it. If the current name is “ahmet” the while loop is stopped with the break statement.
names = ["ismail","ahmet","ali"]
i = 0
while True:
name = names[i++]
if name == "ahmet":
break
print(name)
Break Outside Loop Error
The break statement is only used with loops like for loop, while loop. If it is used in other strucutres the “SyntaxError: ‘bread’ outside loop” exception is thrown.
if 1==1:
print("1")
print("2")
break
print("3")
File "<stdin>", line 4 SyntaxError: 'break' outside loop