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...
4 Respuestas
+ 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!
"""
+ 1
My thanks... I get it slowly now... :D
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
0