By the end of this tutorial, you will be able to work with break statements in for loops, while loops, and if statements.
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.
Term | Definition |
---|---|
For loop | An iterating function used to execute statements repeatedly. |
While loop | Used 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 statements | In Python, continue, break, and pass are control statements that change the order of a program’s execution. |
Loop statements | Loop statements execute code repeatedly as determined by the user. |
Control flow | Control flow, or program flow, is the order of execution in a program’s code. |
Iterate | In programming, iteration is the repetition of a code or a process over and over until a specific condition is met. |
Indentation | Indentation 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. |
if | if 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. |
else | The else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero. |
break | The break command terminates the loop that contains it and redirects the program flow to the following statement. |
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
The flowchart below demonstrates the flow of a program when you use a break statement in a loop.
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:
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
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.
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
.
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.
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:
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.
Given a list of strings, write a program that prints the first string that starts with the letter "A".
1
words = ["banana", "cherry", "apricot", "coconut", "kiwi", "avocado", "apple"]
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.
Let’s examine the basic structure of a break statement in a Python for loop:
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.
Here’s how a break statement works in a Python while loop:
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.
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:
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.
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.
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.