How to Use Python Break

Written by Coursera • Updated on

By the end of this tutorial, you will be able to work with break statements in for loops, while loops, and if statements.

[Featured Image] A screen displays colorful lines of code.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

The break command is an important control flow tool for Python programmers to master. It is one of three control statements that enable you to manipulate the sequence of for loops and while loops.

Glossary

TermDefinition
For loopAn iterating function used to execute statements repeatedly.
While loopUsed to iterate over code when the condition is true. This loop type is typically used when the number of times you’ll need to repeat is unknown.
Control statementsIn Python, continue, break, and pass are control statements that change the order of a program’s execution.
Loop statementsLoop statements execute code repeatedly as determined by the user.
Control flowControl flow, or program flow, is the order of execution in a program’s code.
IterateIn programming, iteration is the repetition of a code or a process over and over until a specific condition is met.
IndentationIndentation is the space at the beginning of each line of code. In Python, indentation indicates a new line of code. In other programming languages, it is used only for readability.
ifif is a common conditional statement. It dictates whether a statement should be executed or not by checking for a given condition. If the condition is true, the if block of code will be executed.
elseThe else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero.
breakThe break command terminates the loop that contains it and redirects the program flow to the following statement.

What does break do in Python?

In Python, break allows you to exit a loop when an external condition is met. Normal program execution resumes at the next statement. You can use a break statement with both for loops and while loops. In a nested loop, break will stop execution of the innermost loop. The flow of the program resumes at the next line of code immediately after the block.

Tip

Break behaves the same way in Python as it does in C.

How do break statements work in Python?

The flowchart below demonstrates the flow of a program when you use a break statement in a loop.

Python break

How to write a break statement in Python

Indentation is crucial in Python. When working with loops, remember that indentation tells Python which statements are inside the loop and which are outside the loop. Your break statement should follow your if statement and be indented.

Example:

PYTHON
1
2
3
4
5
6
7
8
9
10
# break statement for for loop
for item in iterable:
    if some_condition:
        break  # exit the loop

# break statement for while loop
while condition:
    # code block
    if some_condition:
        break  # exit the loop

Try it yourself

Write a program that counts from 1 to 100, printing each number. However, for multiples of 3, instead of printing the number, the program should print "Fizz". For multiples of 5, the program should print "Buzz". For numbers that are multiples of both 3 and 5, the program should print "FizzBuzz". The loop should exit after printing the number 100.


PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
count = 1
while True:
  if count % 3 == 0 and count % 5 == 0:
      print("FizzBuzz")
      count = count + 1
      continue
  if count % 3 == 0:
      print("Fizz")
      count = count + 1
      continue
  if count % 5 == 0:
      print("Buzz")
      count = count + 1
      continue
  if count > 100:
      break
  print(count)
  count = count + 1

It's also possible to solve this problem using num and range.

How to use break in Python

As the name suggests, Python break is used to control the sequence of loops. You can also use it to break out of an if statement, but only when the if statement is inside a loop. First, let’s examine how you can break out of an if statement inside a loop. Then, we’ll learn how to use break in for loops, while loops, and nested loops.

How to break out of an if statement using break

Remember, you can’t use break to exit an if statement in Python. You can only use break to exit the loop containing the if statement. Here’s an example:

Screenshot 2023-02-22 at 5.14.59 PM

In this code, we define a list of numbers and use a for loop to iterate through each number in the list. Within the loop, we use an if statement to check if the current number is greater than 100. If it is, we print the number and exit the loop using break. This ensures that we only print the first number that is greater than 100 and not any subsequent numbers that meet the same condition.

Try it yourself

Given a list of strings, write a program that prints the first string that starts with the letter "A".

PYTHON
1
words = ["banana", "cherry", "apricot", "coconut", "kiwi", "avocado", "apple"]

PYTHON
1
2
3
4
for word in words:
    if word.startswith("A") or word.startswith("a"):
        print(word)
        break

In this code, we define a list of words and use a for loop to iterate through each word in the list. Within the loop, we use an if statement to check if the current word starts with the letter "A" (case-insensitive). If it does, we print the word and exit the loop using break.

Using Python break in for loops

Let’s examine the basic structure of a break statement in a Python for loop:

PYTHON
1
2
3
for item in iterable:
    if some_condition:
        break  # exit the loop

The break statement redirects the flow of the program so that the code inside the for loop is skipped over.

Using Python break in while loops

Here’s how a break statement works in a Python while loop:

PYTHON
1
2
3
4
while condition:
    # code block
    if some_condition:
        break  # exit the loop

Just like with for loops, the break statement redirects the flow of the program to skip the code inside the while loop.

Using Python break in nested loops

In Python, the break statement is used to immediately exit a loop when a certain condition is met. When working with nested loops, the break statement can be used to break out of both the inner and outer loops.

If a break statement is encountered in the inner loop, only the inner loop will be exited and the outer loop will continue to iterate. However, if the break statement is included in the outer loop, both the outer and inner loops will be exited and the program will continue executing after the loop.

Example: Screenshot 2023-02-23 at 11.58.52 AM

As we can see from the output, when i is equal to 2 and j is equal to 2, the inner loop is exited and the program continues iterating over the remaining values of j for i=2. However, when i is equal to 3, both the inner and outer loops are exited, and the program stops iterating.

Key takeaways

  • Break is a loop control statement along with continue and pass.
  • You can use break to exit for loops and while loops.
  • Break only exits the innermost loop in a nested loop.
  • You can’t use break to exit an if statement unless the if statement is inside of a loop.

Resources

Keep improving your Python skills with Coursera.

You can practice working with for loops with a Guided Project like Concepts in Python: Loops, Functions, and Returns. Or, take the next step in mastering the Python language and earn a certificate from the University of Michigan in Python 3 programming.


Written by Coursera • Updated on

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Learn without limits