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 Python Basics (2015) Shopping List App Break

Soufiane Bdaoui
Soufiane Bdaoui
9,602 Points

Why I shouldn't use else in this case (Python)

Can you please explain to me why if I put my code as follow I get an error, but when I delete the else part it's correct? I'm having a real hard time understanding the logic behind it.

breaks.py
def loopy(items):
    for item in items :
        if item == "STOP" :
            break 
        else :
            print(item)

1 Answer

Steven Parker
Steven Parker
231,248 Points

It worked for me just as it is.

I'm not sure why you had a problem, I pasted your code directly into the challenge and it passed.

I can say that the else is not needed, because when the condition is true the loop will end. But it certainly doesn't hurt to have it there.

I did notice the extra space that Alexander mentions, but it does not seem to have any effect on the challenge.

Wait, the space between the colon and the else or if doesn't cause a syntax error?

Nevermind. I just tried the code in IDLE and it worked. Silly me XD

Soufiane Bdaoui
Soufiane Bdaoui
9,602 Points

I figured it out , thanks tho.