Iteration, while loop, and for loop

BartC bc at freeuk.com
Tue Jun 28 09:24:35 EDT 2016


On 28/06/2016 13:36, Elizabeth Weiss wrote:
> I understand this code:
>
> words=["hello", "world", "spam", "eggs"]
> for words in words
>    print(word + "!")
>
> What I do not understand is:
>
> words=["hello", "world", "spam", "eggs"]
> counter=0
> max_index=len(words)-1
>
> while counter<=max_index:
>    word=words[counter]
>    print(word + "!")
>    counter=counter + 1
>
>
>
> Both of these result in the same answer.
> I do not understand the second code. What is counter?
> Why do we use this code if we can use the simpler for loop?
>
> If you could please explain the second code step by step that would be great!

Imagine the words are printed in a book, one per page, and the pages are 
numbered 0, 1, 2 and 3 (starting from 0 as is the perverse say of many 
programming languages).

len(words)-1 is the number of pages in the book (4) less one to account 
for the odd numbering. Max_index is then the number of the last page (3).

Counter then goes through the pages one by one, starting at page 0 and 
ending at page 3 (ie. max_index), reading the word on each and printing 
it out with "!" appended.

However, because the language is zero-based, this would have been better 
written as:

  num_words = len(words)

  while counter < num_words:      # or just while counter < len(words)

That's if you had to write it as while loop. With the for=loop version, 
these details are taken care of behind the scenes.

-- 
Bartc




More information about the Python-list mailing list