Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Completed loopy challenge but items print multiple times
I've completed the loopy challenge and added the break, however when I run the code in workspaces (or windows ps, or command prompt or w/e) my item prints out multiple times or on multiple lines (if I change print(item) to print (items). For example, if I make pizza my item by adding loopy(pizza) at the end of the code and run it, I get (on new lines for each): p i z z a
And if I change it to items and use pizza I get (on new lines for each):
pizza pizza pizza pizza pizza
Can anyone tell me why this might be? Seems like it should print only one line and either be a p or pizza.
Thanks in advance.
def loopy(items): for item in items: if item == "STOP": break print(item)
loopy function is designed to work with a list, not a string. If you send it a list like this:
loopy(["pizza"]) # ["pizza"] is a list with one string
Then you would only get one line printed out.
The reason why you get the individual letters printed out when you pass it a string is that Python treats strings as a list of characters. So when you ask Python to loop through a string it will pull out each individual character of the string as if it were an item in a list.
The reason you get repeated prints when you change
print(items) is that
items is the variable that holds the list being looped through, whereas
item is the variable holding the current item that has been pulled out of the list. The loop runs once for each item in the list, so if you tell Python to print out the list itself within the loop then it will print that list once for every item in the list.
Dave StSomeWhere19,822 Points
Your print(item) statement is within the for loop (based on the indentation) and since nothing stops the loop it will execute the print() each time through. The break will only execute and stop the loop when item is equal to "STOP" which is never the case when you pass "pizza".