0

Counter variable in Python loops

I have seen this block of code being asked but it doesn't answer my question, so I started a new thread. The code goes : words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 I don't know what is really going on here. I am just stuck here. Someone please explain...

6th Aug 2020, 2:17 AM
Adam Haller
Adam Haller - avatar
4 Respostas
+ 2
words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 """output hello! world! spam! eggs! explanation Here 👇👇 max_index= 4-1=3 { len(words)=4 while 0 <= 3: word = words[o] print("hello"+"i") { hello ! counter= 0+1=1 again run in counter is 1 ,2,3then print world!,spam!,eggs! """
6th Aug 2020, 2:51 AM
Sâñtôsh
Sâñtôsh - avatar
+ 1
My thanks... I get it slowly now... :D
6th Aug 2020, 2:57 AM
Adam Haller
Adam Haller - avatar
0
All it does is iterates over each item in the list and prints those items. So in the first iteration, counter = 0 and words[counter] which would be words[0] takes the first item in that list since index 0 is the first item in the list and stores it in a variable called word. It then prints that variable and adds "!" to it so it would print out hello! And then it increments counter and the loop repeats the process until counter reaches max index which is 3 because len(words) is 4 (4 items in the list) and subtract 1 to get 3 which is the last index in the list. Hope that helps
6th Aug 2020, 4:01 AM
Rdefgekrd
Rdefgekrd - avatar
6th Aug 2020, 7:04 AM
Tomiwa Joseph
Tomiwa Joseph - avatar