+ 1
I need someone to explain an example of very basic for loop python code.
words = ["hello", "world", "spam", "eggs"] for word in words: print(word + "!") I don't understand how the code ABOVE prints all the items in the list.Can someone explain? words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 This one has the same output but I actually get this one unlike the for loop one.
1 Answer
+ 1
The first one uses a for-each loop. If you read it as "for each" maybe it will make more sense.
It can be read as:
There's a list of words containing: hello, world, spam and eggs.
For each word in the list of words:
print this word and add an exclamation mark.
In the for-each loop "word" is a variable containing the word we're on in the list. That word is printed out with a '!', the loop continues and the next word is assigned to our "word" variable from the list. It continues until the list ends and there are no more words to print.
Hopefully this make sense.