Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Difference in indentation between "break" and "continue" in while loop

I indented "continue" two more spaces to the left then "break" in the same loop and it still works. But if I move "break" two space to the left, I get an error. Why is there a difference between those two? They are in the same loop.

my_list = []

def add_to_list():  
  while True:
    new_item = input("Add item to list and press enter:   ")
    if new_item == "DONE":
      show_list()
      break
    else:
      my_list.append(new_item)
    continue

def show_list():
  print(my_list)

add_to_list()

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

The break is inside of an if condition. Moving it two spaces to the left (dedenting/unindenting/whatever you want to call it) causes the if block to end and now the else is floating on its own with no if. That's not allowed.

The continue can be where it is, indented further, or removed entirely because it's at the end of the while loop which automatically repeats so long as the condition is truthy.

Thanks Kenneth. It's clear now

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

It might seem confusing because there is an implied continue as the last statement in a while code block. Increasing your indentation to 4-spaces to help show alignment, let's look at your code.... Neither of the continue statements are necessary.

def add_to_list():  
    while True:
        new_item = input("Add item to list and press enter:   ")
        if new_item == "DONE":
            show_list()
            break
        else:
            my_list.append(new_item)
            # indented continue
            continue #<-- 'else' code block exits to 'while' code block, so this is unnecessary as it will fall into implied continue
        continue  #<-- implied continue. Code behaves the same if removed

Thanks Chris