Ok lets see if I can make things clear for you . The goal of the exercise is to read an array of words and print each word in capitalized form. I will answer your questions you put in the code. So:
words = [“Four”, “score”, “and”, “seven”, “years”, “ago”] #this is the list
That is correct!
i = 0 #counter starts at 0 which is Four in the list
You got that right. In code you start counting at the 0th element. We are making an iterator that runs past all the items in the list based on their
index a.k.a. the position in the list, hence
i. But this could just as easily be any other word since it is a variable with a value of 0. You could have picked
index = 0 or
wordNumber = 0.
while i < len(words): #why am i looking at length of words? Can’t I just tell it to convert the list to capital letters without having to use a loop? This seems unnecessary to me.
Ok this gets a bit more complex but easy if you get your head around. Since we are using a
while loop, we execute something until a certain condition is met.
So what do we want to do, and when does it end?
We want to do something with each word, and we need to stop doing it once we reached the end of the list . And how do we know when we have reached the end of the list? When we have reached the index number, our variable
i that is equal to the length of the list
words. So our condition of the while loop is
i < len(words).
You ask why we can’t just do it without a loop, well the answer to that is, yes. You could use the
map function. But we are discussing
loops now . There are different loops you can use to achieve the same result, but that is the second part of the reddit topic.
waffle = words[i] #is this the new list I want with capital letters? It starts at i because it looks at the value of counter?
waffle is not a list, it is a variable that is used to store the value of the list
words at the index
i the while loop is at that moment. If the while loop is at
i = 3,
waffle will get assigned a value of
words which is ‘seven’. Upon the next iteration
waffle will get assigned a new value of
uppercase_word = waffle.upper()#new variable set to make list into capital letters
The previously stored value of
waffle will be capitalized and stored in yet another variable
print(uppercase_word)#prints the list in capital letters.
All we do now is print that single value of
i += 1#indicates to go to the next item in the list
We have done everything we needed to do with the current word in the list of words, so now we add 1 to the value of
i and the
while loop hops on to the next word.