Why does this string repeat 5 times


#1

Hey Codecademy community!
So, I was doing the Python course and I found one thing that is concerning me.
The code is the following:

thing = "spam!"

for c in thing:
  print c

word = "eggs!"

for character in word:
  print word

And the output is:

s
p
a
m
!
eggs!
eggs!
eggs!
eggs!
eggs!

Why does the string “eggs!” repeat 5 times and doesn’t give the same output as the “spam!” one?
ps: Don’t mind my last sentence, I figured out why the “spam!” string gave me a different output.

Thanks in advance.


#2

Because it is told to print five times.

print word

Had the instruction been to print the character, then the output would match the first example.


The in operator conveys one element at a time to the iterator variable. Since it is a value (an item) and not an index it is immediately visible.

for z in "red zinger":
    if z = ' ':
        break
    print z
r
e
d

We can use the operator’s inverse, too, and look into a string, a list, a dictionary, set or tuple since they are all iterable.

>>> word = "Antiquarian"
>>> dupe = list(word)
>>> for letter in word:
    if letter in "aeiouAEIOU":
        dupe.remove(letter)

        
>>> word = ''.join(dupe)
>>> word
'ntqrn'
>>> 
>>> word = "Eunoia"
>>> dupe = list(word)
>>> for letter in word:
    if letter in "aeiouAEIOU":
        dupe.remove(letter)

        
>>> word = ''.join(dupe)
>>> word
'n'
>>> 
>>> genus = "iouea"
>>> word = "Eunoia"
>>> for c in genus + genus.upper():
	word = word.replace(c, '')

	
>>> word
'n'
>>> 
>>> def anti_vowel(word):
	return ''.join([x for x in word if x not in 'aeiouAEIOU'])

>>> anti_vowel("Eunoia")
'n'
>>> 

Note that in that last example we do not iterate over the vowel string, only look to see if the the character is present.


#3

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