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 trialSoufiane Bdaoui
9,602 PointsWhy 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.
def loopy(items):
for item in items :
if item == "STOP" :
break
else :
print(item)
1 Answer
Steven Parker
231,269 PointsIt 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.
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsWait, the space between the colon and the
else
orif
doesn't cause a syntax error?Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsNevermind. I just tried the code in IDLE and it worked. Silly me XD
Soufiane Bdaoui
9,602 PointsSoufiane Bdaoui
9,602 PointsI figured it out , thanks tho.