0

python question abut while loop

hi, I didn't get the following code, would you please explain a bit? for example why you use -1 in the third line? and also this part ( word = words[counter]) words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 thank you

27th Oct 2017, 5:13 PM
Dariush Shiri
Dariush Shiri - avatar
1 Answer
+ 12
1. List indexes start from 0, so the highest possible index of words is 3 (the fourth element). Now words length, so len(words) equals 4 and this is why max_index variable meaning the highest possible index of this list has to be subtracted by 1. 2. The while loop iterates through the words list, assigning its consecutive elements, one by one, to "word" variable. So during the first loop, word becomes words[0], next words[1]... and so on. Each time the counter variable changes (each time the loop is passed), incrementing by 1 up to the maximum number of index --> 3.
27th Oct 2017, 5:35 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar