What did I do?


Why does this loop so weirdly?

thing = "spam!"

for c in thing:
    print c

word = "eggs!"

# Your code here!
for thing in word:
    print word + thing


This is what the console box says:



What is the output you're expecting?


I dont know... but how does this work


When coding, it is always best to know what output you are expecting. This makes it easier to find bugs when things don't work as expected. If you don't know what's correct or expected then this code is correct and not weird at all.

It is also a way to plan how you are going to reach the expected outcome.

This part seems pretty straightforward, right? It's just printing each item in the string per loop. Hence you get that output.
Moving on:

Your thing now acts just like the c in first loop. It will print each item in the string, eggs! per loop.
word is just eggs! and since there are 5 items in that string, you print eggs! 5 times. Adding those two together, you are putting together eggs! that is repeated 5 times with each item per loop hence why you get that outcome.

You can further see what's going on if you separate word and thing from print word + thing: like this.


But what is each item?


The individual letters and punctuation in the string.


Thats Awesome :slight_smile:


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