Python 2.4Free video11 minLesson 4 of 4 in Module 2
break, continue and else on Loops
Control a loop from the inside.
Free sample. Everything in this module opens with a free account.
Watch or read the lesson: break, continue and else on Loops
01Early loop exit: a PIN loop with three attempts
Imagine you are withdrawing money from an ATM. You enter your PIN, and if it is correct, you can continue. If it is wrong, you get another chance, and the ATM allows only three attempts.
Here is the interesting part. If you enter the correct PIN on your second attempt, the program should not ask you for a third. It should stop immediately. But if you get all three attempts wrong, it needs to display a different message.
So there are two things to figure out:
- How do you stop a loop before it finishes all its iterations?
- How do you run some code only when the loop finishes without finding what it was looking for?
Python gives you a few tools for exactly this. This lesson covers break, continue, and something you might not expect: an else block attached to a loop. You will build the PIN checker once you understand how break and the loop else work.
02break: leaving a loop early
Start with break in a simple search. Say you recorded how much money you spent over five days. The amounts are $42.10, $18.75, $96.40, $12.00 and finally $130.25.
You want to find the first day when you spent more than $90. Notice the word first: not every day, just the first one. So once you find a match, there is no reason to keep searching.
Writing the loop
Write a for loop. Use enumerate() to get both the day number and the amount spent, and start the numbering at one. Inside the loop, check whether the amount is greater than 90. If it is, print the day and the amount, and then write break:
spending = [42.10, 18.75, 96.40, 12.00, 130.25]
for day, amount in enumerate(spending, start=1):
if amount > 90:
print(f"Day {day}: ${amount:.2f}")
break
So what does break do? The breakKey termEnds the loop at once; the program continues with the first line after it. It ends only the loop it is directly in. statement ends the loop immediately. Python does not finish checking the remaining items. It exits the loop and continues with whatever code comes after it.
Predict first
Which day will stop the loop? Trace the days until the first match. Think it through before reading on.
I have a guess. Show meHide the answer
Day 3: $96.40
Here is how Python got there:
- Day one is $42.10. That is not greater than $90, so the condition is
Falseand the loop continues. - Day two is $18.75, still below $90.
- Day three is $96.40. Now the condition is
True, so Python prints the day and the amount. Then it reachesbreak, and the loop ends immediately.
Python never checks day four or day five, even though day five also has spending above $90.
Without break
Now remove break and run the same loop again. What changes? Think it through before reading on.
I have a guess. Show meHide the answer
for day, amount in enumerate(spending, start=1):
if amount > 90:
print(f"Day {day}: ${amount:.2f}")
Day 3: $96.40
Day 5: $130.25
This time Python prints both day three and day five. Without break, the loop keeps checking the remaining amounts after it finds the first match.
03continue: skipping one iteration
Sometimes you do not want to stop the entire loop. You just want to skip one particular item.
Here is an example. Say you have a list of payments. Some are positive amounts, representing money received, and some are negative amounts, representing refunds: $25.00, minus $5.00, $40.50, minus $12.25 and $10.00.
You want to calculate the total amount received, excluding refunds. You could check every amount and add it only if it is positive. But there is another way: continue.
Writing the loop
Start with total equal to zero, then loop through the payments. Inside the loop, check whether the current amount is negative. If it is, write continue. After that if block, add the amount to total:
payments = [25.00, -5.00, 40.50, -12.25, 10.00]
total = 0.0
for amount in payments:
if amount < 0:
continue
total += amount
print(f"{total:.2f}")
75.50
Here is the important part. continue does not end the entire loop. The continueKey termEnds this iteration; the loop goes on with the next item, or checks its condition again. statement skips the rest of the current iteration, and in a for loop, Python moves on to the next item, if there is one.
Tracing the payments
Follow the loop one payment at a time:
- The first payment is $25.00. That is not negative, so Python skips the
continuestatement and adds 25 tototal. Nowtotalis 25. - Next comes minus 5. This time the condition is
True, so Python executescontinueand immediately moves to the next iteration. Notice what did not happen: Python never reached the line that adds the amount tototal. Sototalstays at 25. - Then comes $40.50. That is positive, so it is added. Now
totalis 65.50. - The next amount is minus $12.25, another refund, so it is skipped.
- Finally, the last payment of $10.00 is added. That brings the total to 75.50.
So the loop calculated the total of the positive payments without including the refunds.
Watch the indentation
Pay attention to the indentation. The line total += amount is inside the loop, but outside the if block. That means it normally runs on every iteration, unless continue causes Python to skip it.
What if you had used break instead of continue? Think it through before reading on.
I have a guess. Show meHide the answer
The moment Python reached the first refund, minus 5, it would end the entire loop. None of the payments after that would ever be processed.
The difference
So remember the difference:
breakends the loop completely.continueskips the rest of the current iteration and lets the loop carry on.
Both of these statements work with while loops too.
04The loop else: when a loop ends without break
Back to the ATM. You know how to stop the loop when the user enters the correct PIN: you use break. But what about the other situation? What if the user gets all three attempts wrong? Then you want to display a message saying the card has been blocked, but only after all three attempts have been used. How can you do that?
Python has a feature that might surprise you: a loop can have an else block. else is not only for if statements. It can also be used with for and while loops.
Here is how it works. The loop elseKey termA block written at the same level as a for or while, that runs when the loop ends without break. block runs when the loop finishes normally, without being stopped by break:
- For a
forloop, finishing normally means it reaches the end of its iterable. - For a
whileloop, it means its condition becomesFalse.
But if the loop ends because of break, Python skips the loop's else block.
Building the PIN checker
Now you are ready to build the PIN checker. For this example, say the correct PIN is "4821". It is stored as a string, so it can be compared directly with the text that input() returns.
You want to allow three attempts, so the loop uses range(1, 4). Remember, the stop value is excluded, so this gives the attempt numbers 1, 2 and 3.
Inside the loop:
- Ask the user to enter their PIN.
- Compare it with the correct PIN. If it matches, print a message saying the PIN was accepted, along with the attempt number, and then use
break. - If the PIN is wrong, Python does not enter that
ifblock. It continues to the next statement in the loop, which printsWrong PIN.
Finally, add an else block to the loop. Notice that this else is aligned with the for statement, not with the if inside it. Inside it, print Card blocked:
for attempt in range(1, 4):
pin = input("PIN: ")
if pin == "4821":
print(f"Unlocked on attempt {attempt}")
break
print("Wrong PIN")
else:
print("Card blocked")
The correct PIN on the second attempt
Now test it. On the first attempt, type 1234, and on the second, type 4821. The notebook shows each prompt followed by what you typed:
PIN: 1234
Wrong PIN
PIN: 4821
Unlocked on attempt 2
1234 is incorrect, so Python prints Wrong PIN, and the loop moves to the second attempt. 4821 is the correct PIN, so Python prints Unlocked on attempt 2 and then executes break. The loop ends. There is no third prompt, and the Card blocked message does not appear. That is exactly what you wanted.
Three wrong PINs
Now run the same cell again, but this time enter three incorrect PINs: 1111, 2222 and finally 3333.
PIN: 1111
Wrong PIN
PIN: 2222
Wrong PIN
PIN: 3333
Wrong PIN
Card blocked
Each time, Python prints Wrong PIN. After the third attempt, there are no more values left in the range, so the loop finishes normally. And because break was never executed, the else block runs, and you get Card blocked.
Notice something else: you did not need to create any extra variable to remember whether the user succeeded or not. The loop's else handles the case where all three attempts fail.
A note on security
This is a small example for understanding loop control. A real ATM or authentication system would need proper security controls, rather than a PIN written directly into a program.
05break and continue must be inside a loop
There is one final restriction worth knowing. You cannot use break or continue just anywhere. They need to appear inside a loop.
If you write break at the top level of a notebook cell, Python raises a SyntaxError:
break
SyntaxError: 'break' outside loop
The same goes for continue:
continue
SyntaxError: 'continue' not properly in loop
And putting them inside an if statement is not enough:
if True:
break
SyntaxError: 'break' outside loop
There still needs to be an enclosing for or while loop.
06Recap and challenge: break, continue, the loop else and Module 2
This lesson covered three ways to control how loops behave:
breakKey termEnds the loop at once; the program continues with the first line after it. It ends only the loop it is directly in. exits a loop immediately, even if there are still items left to process.continueKey termEnds this iteration; the loop goes on with the next item, or checks its condition again. skips the rest of the current iteration and moves on to the next one.- The loop
elseruns a block of code when a loop finishes normally, without executingbreak.
Your challenge
Build a simple savings tracker. Imagine you are saving $150 every month, and your goal is to save more than $1,000.
- Start with zero saved.
- Write a loop that goes through the twelve months of the year.
- Each month, add $150 to your savings.
- As soon as your total goes above $1,000, stop the loop. Then print which month you reached your goal, along with the amount saved.
- If you do not reach your goal within twelve months, your program should display a different message saying that the target was not reached.
Think about where you should use break, and where the loop's else block should go. Once it works, try changing the monthly savings amount or the target, and make sure you test both situations.
If you are ready for something more challenging, look at the module project in the notebook. There, you will build a loan repayment schedule, and the notebook has all the details.
The end of Module 2
You have now learned how to make decisions with conditions, repeat work using loops, and control when those loops stop or skip an iteration. Throughout these lessons, you have already been using lists to store collections of values. The next module takes a closer look at lists themselves: how to access their elements, how to modify them, and what happens when different names refer to the same objects.
Key terms: break, continue and else on Loops
The words this lesson introduces, each in one line. The module’s glossary collects them all, and the AI glossary has every term across the courses.
- break
- Ends the loop at once; the program continues with the first line after it. It ends only the loop it is directly in.
- continue
- Ends this iteration; the loop goes on with the next item, or checks its condition again.
- loop else
- A block written at the same level as a
fororwhile, that runs when the loop ends withoutbreak.
Quiz: break, continue and else on Loops
Your first pick on each question is the one that counts. Getting one wrong here is how the lesson sticks.