Why is the second and nested loop necessary?

Help with Step 19 in Python 3 - String Methods - Project Thread Shed please …

https://www.codecademy.com/courses/learn-python-3/projects/thread-shed

My code for Step 19 is as follows …

Screen Shot 2023-01-16 at 7.49.37 PM

I have compared it with the Solution in the Project Walkthrough video. But I don’t understand why the second and nested loop is necessary. Why doesn’t my code suffice? If I were to narrate my code with the test color of “white”, I’d say, "for the variable “white” that is assigned to the color argument, every time I loop through the list and come across a “white,” add +1 to the counter.

If color happens to be "white", you want to add 1 to the counter (increment counter) only if "white" matches entry in thread_sold_split.

Your code doesn’t check whether "white" matches entry in thread_sold_split, it only iterates through thread_sold_split and adds to counter for any entry in thread_sold_split (which would end up making counter the same as len(thread_sold_split) ).

for color in thread_sold_split:
iterates through all the stuff (elements) in the thread_sold_split array, and assigns each element to the variable color
(Whatever was in color previously, like "white", is overwritten, I think.)

You’d need an if inside the loop to check whether that element of the array matches the argument of that function, and take the appropriate action if it matches.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.