Will any additional code execute after a break statement?

Question

In this exercise, a break statement is used as the last line in the for loop. If there was any additional code in the for loop after the break, would it execute?

Answer

No, the break statement will terminate the execution of the for loop. It does not allow for the execution of any additional code in the loop if it exists. In other words, break doesn’t stop the loop from completing any new iterations, it completely stops the current iteration at the point break is placed.

In the following example code, the print(counter) statement is called for numbers 1 through 4 but does not print the value 5.

counter = 0
while counter < 10:
    counter += 1
    if counter == 5:
        print("Reached 5")
        break
    print(counter)
13 Likes

Extra Study

The break discussion doesn’t end there. It has a ‘case in tow’ which is else on the while.

while ...
    if ...: break
else:
    # loop completed successfully

Eg.

while counter < 10:
    counter += 1
    if randint(1,11) == 11:
        print ('Won!')
        break
else:
	print ('done')


# Won!

Whoo-hoo! we won with 11 on the first roll!

while counter < 10:
    counter += 1
    if randint(1,11) == 11:
        print ('Won!')
        break
else:
	print ('done')

	
# done

The loop completed and we’re all good. Nothing to report here.


This will come up at some point, so consider the above a pre-imersion not directly relating to this lesson, but akin to, as we will learn, upcoming.

Sidebar:

Begin the practice of using parens on print so it becomes nature. The transition to Python 3 will have less bumps if that is already in your kit.

23 Likes


what is the difference between the example and the exercise as the example you say if item == the item name but the exe answer we have to add if dog == dog_breed_I_want: not ‘dalmation’ as the exa

I don’t think there is a gppd answer to your question. You could easily code the exercise to print out, “They have the dalmatian that I have been looking for!”, but that is not what was asked for. I agree that it would have made the exercise a bit more interesting.

The difference here is that the example is comparing the the contents of item with the string literal “knit_dress”.

In the exercise you are comparing the contents of dog with the contents of dog_breed_I_want. Although you could do another comparison with a string literal, the exercise likely wishes you to take notice that you can use a variable in this case just as well as you could a string literal.

2 Likes

I think, the reason the exercise differed from the example, was to show there are other ways of constructing for-loops.

In a more real world scenario, it might be better practice to compare the element in a list to a variable (as in the exercise-case with <dog_breed_I_want>), rather than a string written directly into the loop (example-case).

Imagine if, next week, you might find yourself wanting a DIFFERENT breed of dog. So instead of skimming through all the potential functions in your program to look for the points where you actually loop and search through the list of dog_breeds_available_for_adoption, you instead just change the value of the variable <dog_breed_I_want>.

2 Likes

It’s really great example of code for me. I’m totally a beginner, though I’m very old. ( Your explanations here in Codeacademy are always of the highest quality.) Thank you.
So, if I understand correctly, “break” stops the whole “while” execution and “else” condition will not go. And how far the “power” of “break” will extend? If it would be a “nest in nest in nest” loop? Sorry for possible stupidness of the question, I’m just a several months old coder.

1 Like

Welcome, @system2120220371,

As I understand, break only applies to the loop it is contained in.

Eg.

a, b, c = 3, 6, 9
while a:
    a -= 1
    while b:
        b -= 2
        while c:
            c -= 3
            print (a, b, c)
            if c == 3: break
        print (a, b)
        if b == 2: break
    print (a)
>>>
(2, 4, 6)
(2, 4, 3)
(2, 4)
(2, 2, 0)
(2, 2)
2
(1, 0)
1
0
>>> 

The code is silly, but it does prove this out.

2 Likes

Thank you!
By the way, it was very interesting to understand “why”(about your “break” snippet). I’m sure you have more of such nice snacks for us.

1 Like

Re: [Codecademy Forums] [Get Help/Python] Will any additional code execute after a break statement?
Thank you very much, Roy.

Sorry for the delay, I check my post irregularly.

I’m sure, you know, but I need to express my admiration: your explanations are the only ones in the course that are always clear “till the last bit”. :slight_smile: And you can play with it.

With great respect

Helena

2 Likes

A post was split to a new topic: Typo in Command Line Project

How to check two element in a list? i try to add one on dog-i-want, use break, it only print one result, not use break it continue to the rest.

dog_breeds_available_for_adoption = ['french_bulldog', 'dalmatian', 'shihtzu', 'poodle', 'collie']
dog_breed_I_want = ['dalmatian','poodle']

for breed in dog_breeds_available_for_adoption:
  print(breed)
  if breed in dog_breed_I_want:
    print("They have the dog I want!")
1 Like

It will be helpful if you post a complete code especially where you added to dog_breed_I_want. Also, your code isn’t showing anywhere you included break.

With the above being said, the below code as you posted seems like it should be together as the for and if codes are not linked.

for breed in dog_breeds_available_for_adoption: print(breed) if breed in dog_breed_I_want: print("They have the dog I want!")

I am a learner like you though. I hope the gurus can help put straight my comment and yours in order to learn

1 Like

As per @8314154157 If you use break in the if statement code block then it will only print the first match because it will stop the loop. That is the expected behaviour of break. You wouldn’t use break in your code to achieve what you want. Unless I am misunderstanding what you are asking.

I noticed that difference, too, but I saw the “teacher’s” choice as one to show force us students to think critically. I also think it’s more likely that we’ll need to write code in which we have a variable after == in this case, rather than a literal string. We haven’t had any real-life practice yet, but when I try to imagine how we’ll use this code (making a mobile app or website, for example), lots of the variables we create are going to represent user input, so we need our code to be as general/abstract as possible. Imagine we were making a website for a humane society about dogs available for adoption. Lots of people (potential dog owners) would visit the site and not all would want the same kind of dog. So if the user (potential dog owner) has to write in/select the type of dog they want, our code would work for any user input, not just for those who chose “dalmatian”. We also wouldn’t have to write separate lines for each possible user choice. The use of a variable would make the code more efficient for the humane society employees too, who may be adding and removing dog breeds from the list as dogs come in and are adopted. But the example probably just used a simple string to show us the syntax as simply as possible.
#formerteacher :wink:

1 Like

Took me a while to get to the bottom of this example.

I found the appearance of (2, 2, 0) confusing, as I thought that was part of the third loop that had already finished due to the break condition c == 3.

But the while condition still holds until c == 0, as I understand it. So the whole code finishes when the condition a, b, c == 0, 0, 0 is met. Right?

Right. The while loops all wind down to zero so that will be the final state for all three variables.

Take a look!

dog_breeds_available_for_adoption = [‘french_bulldog’, ‘dalmatian’, ‘shihtzu’, ‘poodle’, ‘collie’]

dog_breed_I_want = ‘dalmatian’

for breed in dog_breeds_available_for_adoption:

print(breed)

if breed == dog_breed_I_want:

print("They have the dog I want!")

print(True)

break

print(True)

we have 2 statements for ‘True’ in if block, it will print only the first ‘True’ statement if the condition matches.

else, the second ‘True’ statement will never be executed because ‘break’ will terminate to work further.

Once again: Very usefull explanation! Thank you for giving this “extra”.

1 Like

But why is the else statement not indented under the while loop though?