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 trialSabaa Talal
Courses Plus Student 733 Pointshow to break from function using if .
(I need to break out of the loop when the current item is the string "STOP". Help me add that code!) I tried many ways but all failed here is one of my trying answers can you help me figure out what is wrong with it.
def loopy(items):
# Code goes here
for thing in items:
print (thing)
if thing == 'STOP'
break
2 Answers
Steven Parker
231,248 PointsThe code above does not test for "STOP" until after the loop prints every item. But you could move the test inside the loop, and do it before you print each word. Remember that besides line order, anything inside a loop will be indented more than the "for" line. And don't forget to put a colon after your "if" statement.
Ezra Siton
12,644 Pointstwo syntax errors:
- You forgot the ":" in the "if" statement
- Indentation problem - the "if" is outside the for loop
SyntaxError: 'break' outside loop
Now :) After fixing 1+2 the code will work fine but "STOP" print anyway before the break (not like the instructions told you):
def loopy(items):
# Code goes here
for thing in items:
print (thing)
if thing == 'STOP':
break
list = ['apples', 'pears', 'STOP', 'peaches', 'beer']
loopy(list)
# return: apples pears STOP
To fix this you should replace the order ("if" than print)
def loopy(items):
# Code goes here
for thing in items:
if thing == 'STOP':
break
print (thing)
list = ['apples', 'pears', 'STOP', 'peaches', 'beer']
loopy(list)
# return: apples pears ..... misson pass :)
Also, you must use python compiler to learn more about Python (see the errors. test the function results and so on)