+ 2
I don't understand this, please help me(i'm newbie)
words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 Can anyone explain for me so i can understand this?
5 Answers
+ 4
Syakirin Ooi
words = ["hello", "world", "spam", "eggs"]
counter = 0
max_index = len(words) - 1
## counts the number of words in the list above
print(max_index)
## the counter begins at zero and will count forward to the number 3 to equal the max_index
## the while loop will continue to execute until counter equals 3
while counter <= max_index:
## each word in the list will be printed as the first words[0] == "hello", words[1] == "world" and so on...
word = words[counter]
print(word + "!")
## counter is increased by one each time the loop cycles
counter = counter + 1
btw this also can be wrote as a smaller loop using enumerate as:
words = ["hello","world","spam","eggs"]
for count,word in enumerate(words, start=1):
print(word + "!")
+ 7
The oroginal code does only give this output:
hello!
world!
spam!
eggs!
So no counter or enumerate is needed:
words = ["hello", "world", "spam", "eggs"]
for word in words:
print(word+'!')
#or with a comprehension:
[print(word + '!') for word in words]
+ 5
Lothar I was only giving an example that there was a much easier method as you did... verses writing excessive code potentially bogging down the system.
+ 5
BroFar, thanks for your reply. I can not understand why you say your code is much easier than mine, and why do you say that my code is potentially bogging down the system. I am always happy when I can learn something new. But i would appreciate if you could explain your statement a bit more with some facts and numbers like memory consumption and runtime behaviour or what whatever scale you are using. Thanks!