Start learning free

LESSON 181 OF 673 · LOOPING OVER LIST INDICES

Break the loop in Python

Lesson

With the break statement, we can prematurely terminate a for / while loop from inside that loop.

When Python reaches the break statement, it's going to immediately terminate the loop without checking any conditions.

In this example, we will terminate the loop when we find a "banana" in our list:

fruits = ["kivi", "orange", "banana", "apple", "pear"]
for fruit in fruits:
	print(fruit)
  	if fruit == "banana":
		break

The output of this code is:

kivi
orange
banana

As you can see, our program doesn't print apple and pear.

Here's what happens during this loop:

1. First iteration:
	a. fruit = "kivi"
	b. print(fruit) => Output: kivi
	c. Is fruit == "banana"? No.
	
2. Second iteration:
	a. fruit = "orange"
	b. print(fruit) => Output: orange
	c. Is fruit == "banana"? No.
	
3. Third iteration:
	a. fruit = "banana"
	b. print(fruit) => Output: banana
	c. Is fruit == "banana"? Yes:
      		break => Exit the loop immediately

Assignment
Let's print all the lessons our student finished!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check