Please help explaining this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please help explaining this

words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1

31st May 2019, 12:19 PM
Krish Vaidya
Krish Vaidya - avatar
2 Answers
+ 1
Let's go through this line by line, starting at max_index. max_index sets itself to the length of the 'words' array (4) minus 1 (3). This means that the function can't go past the end of the array. For example the index of 'eggs' is 3, so that's where the function should stop. While the counter (currently 0) is less than or equal to the max index, the function will be performed. Word is equal to words[counter] - this sets the index, so for now word = words[0]. The word at words[0] is printed with ! at the end, then counter is increased by one. The function repeats until counter equals max_index (3), printing all the words in the array with a ! at the end.
31st May 2019, 12:31 PM
Rincewind
Rincewind - avatar
0
counter = 0 max_index = 3 ##len(words) counts the number of elements inside the list which will be equal 4 so 4-1 will make it 3## *while counter(0)<=max_index(3): word = words[counter] print(word + "!") counter = counter + 1 --------In that case words[counter] = words[0] meaning the element with zero index inside the list called 'words' so the element with index 0 here is "hello", so print(word+"!") will print 'hello!' Then the line 'counter = counter + 1' will be run so it will be: counter = 0+1, counter = 1 ------now since the statment: while counter <= max_index is still true then the code will loop for thr second time and here is the second loop: counter= 1 max_index = 3 word = words[1] (the element with index 1 which is 'world') print(word+"!") This will print the element with index 1 in the list followed by '!' "world!". counter = counter + 1 (counter = 1+1) counter will be 2 **and the loop will keep going till the counter becomes 4 *sorry if this isn't so clear
31st May 2019, 12:38 PM
Mo Hani
Mo Hani - avatar