Break
Part of the Fundamentals section of Coddy's Python journey — lesson 37 of 77.
The break statement stops the loop instantly when it's encountered.
For example,
for i in range(10):
if i == 6:
break
print(i)In the following example the loop iterates regularly until it reaches number 6. Then the program enters the if statement and executes the break statement. This exits the loop immediately. The output is:
0
1
2
3
4
5Challenge
BeginnerYou are given a code that prints the numbers from 1 to 10 (including).
Your task is to add if and break statements so that only the numbers from 1 to 5 will be printed, the loop will exit before printing the numbers from 6 to 10.
Cheat sheet
The break statement immediately exits a loop:
for i in range(10):
if i == 6:
break
print(i)This will print numbers 0 to 5, then exit the loop when i equals 6.
Try it yourself
for i in range(1, 11):
print(i)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2