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 trialJohn Hughes
2,015 Pointsbreaks.py
Having trouble breaking out of the loop if a conditional list item exists.
def loopy(items):
for each in items:
if str in items == "STOP":
break
else:
print(items)# Code goes here
2 Answers
hamsternation
26,616 Pointsyour code:
def loopy(items):
for each in items:
if str in items == "STOP":
break
else:
print(items)
first of all, you want to print the variable each and not items. items is the list passed in, printing items will not get you the answer you want.
Your if statement should have an additional indentation since it's nested inside the for loop.
Your if statement should only test each == "STOP"
. If you follow your current code, here's what it would do:
if str in items == "STOP"
python evaluates str in items
and returns False, then compares False == "STOP"
and returns False again. so in the end, it prints the entire list of items back.
The revised code would look like this. Let me know if it makes sense. :)
def loopy(items):
for each in items:
if each == "STOP":
break
else:
print(each)
John Hughes
2,015 Pointsthanks