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

Using break in python - where am I wrong?

Challenge: I need you to help me finish my loopy function. Inside of the function, I need a for loop that prints each thing in items. But, if the current thing is the string "STOP", break the loop.

Code:

def loopy(items): for item in items: print(item) if item == "STOP": break

Steven Parker
Steven Parker
242,770 Points

Try formatting your code so the spacing shows up (in Python, indentation is everything).
Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the text entry area. :arrow_heading_down:

3 Answers

the problem is you are doing the 'if' conditional stuff AFTER the print. Try putting the 'if' stuff BEFORE the print. Code:

def loopy(items):
    for item in items:
        if item == 'STOP':
            break
        print(item)

Hope that helps :smile:

Go Python!

uff, almost punched the screen with this chalenge.

I thought an else was needed for the chalenge. Even if it's not stated.

Can someone explain why?

Hello Nicolas, the reason is because it checks if the item is stop FIRST, and if it is, it will break which will skip everything under it and will stop the loop entirely.

Thank you super helpful!

Steven Parker
Steven Parker
242,770 Points

:point_right: The test for "STOP" (and the break) should come before the print.

Otherwise, the word "STOP" will be printed before the loop ends.

ahaa, got it, no point for an else there.

thanks a lot!!!

No problem! :smile:

and also, you could use an else if you want to, and it'll still work.