Normally, a for loop or while loop will continue running iterations until a logical expression or test condition becomes False. However, you may want to change this normal flow by halting the loop early or skipping an iteration. Python lets you complete each of these loop-altering tasks with the break and continue statements. If you want some specific logic to run when the loop finishes normally, you can add an "else" block after the loop body.

Statement Description
break Will immediately cause the loop to exit, skipping any remaining statements and iterations in the loop
continue Will immediately cause the next loop iteration to start, skipping any remaining statements in the loop
else Marks a block of code that will run when the loop has completed normally


Break Statements
Sometimes, you may want to end a loop early, even if your logical expression or test condition remains True. The break statement will immediately halt any loop you might be within at the moment, and the program flow will continue after the loop body.

Let's imagine that you want to write a program that scans a string and prints numeric index that corresponds to the first "e" character. You can visualize a string as a list of characters, and each character is identified by a number starting at 0 and going up by 1 each character to the right. The 7-character string "Banzai!", as shown below, would have character index values from 0 to 6, where the first "B" is index 0 and the last character is index 6.

Index values for the string 'Bonzai!'

We can find search a string using a "for" loop. Remember, the "in" keyword will make the loop iterate once for each letter in the string, storing the letter in the loop variable.

word = "Banzai!"
for letter in word:
# the letter variable holds the current character in the word
Copy
Our search program will initialize a currentIndex variable to 0. This variable represents the index of the letter we are examining, and it will be increased by 1 each time through the loop. The "for" loop will iterate over each letter. Inside the loop body, if the letter is equal to "e", then we print a message showing the currentIndex and break out of the loop. There is no reason to look at the rest of the letters after we find our target letter.

Study the code below to make sure you understand how it works. Try running it a few times with different input words like "hello" and "cheese". Do you get the expected output in each case?

Try It Now


"else" Statement after a "for" Loop
As you have seen, "for" loops are very flexible with many options. One last thing you might want to add to a "for" loop is an "else" statement. The "else" statement marks a body of code that will run after the loop has completely finished. This could be useful if there is some message or some special processing that you want to do when the loop is done.

In the example below, we use a "for" loop to iterate from 2 through 8, printing only the even numbers. An "else" block contains two print() statements that will run after the loop is done. The main logic then continues with two additional print() statements.

Try It Now


Of course, all non-indented statements you place after the loop body will run when the loop is complete. So, what is special about marking a block of code with the "else" statement? The "else" statement will actually be skipped if your loop exits early due to a break. So, you would want to use "else" to mark some final logic to run only if the loop completes normally.

In the example below, we set up a similar "for" loop to display the even numbers from 2 through 8. However, the loop range allows the index to continue past 8 (up to 10). An extra "if" statement will run the break command if the loop index is greater than 8, so this example will always exit through that break statement.

Try It Now


When you run the code, you will still get the same output from the main loop body ("2 4 6 8"). However, the "else" logic is skipped, because the loop halted due to a break statement instead of exiting normally.

Creating a "while" Loop that will Run at Least Once
In some cases, you know you'll want to do something at least one time. Getting user input is a great example. If you want to verify user input - perhaps check a password - you need to get at least one input value and check it against the logical expression. If the expression is True and you enter the loop, you then need to re-prompt the user for a new value.

password = input("Please enter your password: ")

while password != "SECRET": # loop until we get the right password
print("No, try again!") # tell the user they goofed
password = input("Please enter your password: ") # get a new password

print("Password verified.")
Copy
It's somewhat annoying to write the same statement twice - password = input("Please enter your password: "). How can we re-write this loop to avoid duplicate code?

Many languages have a built-in "do-while" loop that will always execute at least one time. A classic "do-while" loop will check the logical expression at the bottom of the loop instead of the top.

do:
password = input("Please enter your password: ") # get a new password
if (password != SECRET):
print("No, try again!") # tell the user they goofed

while password != "SECRET":

print("Password verified.")
Copy
However, the "do-while" loop does not exist in Python. Don't try to write the code pictured above, because it won't work!

Instead, we can use a "while" loop with an interesting logical expression and a break statement to get the same effect. Study the code below. Can you tell how it will always execute at least once, prompt the user for a password, verify the password, take the correct action, and exit the loop when successful?
while True:
password = input("Please enter your password: ") # get a new password
if (password != "SECRET"):
print("No, try again!") # tell the user they goofed
else:
print("Password verified.") # password verified
break # escape this otherwise-infinite loop!
Normally, a logical expression that is simply "True" means the loop would be infinite. However, since our loop body detects an ending condition and uses "break" to exit the loop, it's not as dangerous as it first looks. Run the code and verify for yourself that it works just like our original example at the beginning of the lesson.

Continue Statements
Illustrated Continue Program FlowWhile the break statement will completely exit your current loop, you may just want to halt the remainder of the current iteration early and move on to the next iteration. You can do this with a continue statement. When Python sees a continue statement, it will halt the current loop iteration and start at the top of the loop with the next value. The continue statement will work in both "for" and "while" loops.



In the following example, we use a "for" loop to iterate over a range of values from 1 to 10. We check each value to see if it is even and if so, we continue to the next value. We only reach the print() statement in the "for" loop body if the value is odd.

Try It Now


Remember, the modulus operator (%) will divide the left number by the right number and give you the remainder. If you divide an even number by 2, the remainder should be zero. So, the logical expression (i % 2 == 0) is dividing the loop index value by 2 and returning True if the remainder is 0 (meaning, the loop index value is an even number).

1. What happens when a break statement is encountered inside a loop?
2. Can you describe a situation where a program loop may want to break early?
3. When "else" logic is placed after a loop body when does that logic run? When is it skipped?
4. How can you set up a "while" loop that will run at least once?
5. What happens when a continue statement is encountered inside a loop?
6. Can you describe a situation where a program loop may want to continue early?

1. When a break statement is encountered inside a loop, the loop will immediately exit, skipping any remaining statements and iterations in the loop.

2. A program loop may want to break early when a certain condition is met and there is no need to continue iterating through the loop.
3. "else" logic placed after a loop body will run when the loop has completed normally, meaning it will run if the loop iterates through all the iterations without encountering a break statement. It will be skipped if the loop exits early due to a break statement.
4. To set up a "while" loop that will run at least once, you can use a while True loop with an appropriate condition inside the loop body to break out of the loop when necessary.
5. When a continue statement is encountered inside a loop, the current iteration will be halted and the loop will move on to the next iteration, skipping any remaining statements in the current iteration.
6. A program loop may want to continue early when a certain condition is met and there is a need to skip some statements in the current iteration and move on to the next iteration.