What did I do?


#1



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


#2

This is what the console box says:

s
p
a
m
!
eggs!e
eggs!g
eggs!g
eggs!s
eggs!!
None


#3

What is the output you're expecting?


#4

I dont know... but how does this work


#5

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.


#6

But what is each item?


#7

The individual letters and punctuation in the string.


#8

Cool!
Thats Awesome :slight_smile:


#9

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