Jul-31-2021, 05:06 PM
(This post was last modified: Jul-31-2021, 05:06 PM by deanhystad.)
For loop or while loop doesn't matter. If you can write code using a for loop you can write code to do the same thing using a while loop. I started with the while loop and progressed through the for loop because it naturally leads to the range() function and the range function is a lot like slicing a list.
You do not need to put the words in a list. You need to put the words in a string. The function returns a string. The only reason for putting the words in a list is it makes it easier to make the string if you only have to worry about the even words.
Getting the even words is only half the solution. According to your first post the function is supposed to return a string like "hydrogen, lithium and boron". Now that you have the even words, how are you going to make the string?
This is easy if you know there are 3 words in the list:
You do not need to put the words in a list. You need to put the words in a string. The function returns a string. The only reason for putting the words in a list is it makes it easier to make the string if you only have to worry about the even words.
Getting the even words is only half the solution. According to your first post the function is supposed to return a string like "hydrogen, lithium and boron". Now that you have the even words, how are you going to make the string?
This is easy if you know there are 3 words in the list:
def format_list(my_list): even_words = my_list[::2] return even_words [0] + ', ' + even_words [1] + ' and ' + even_words [2]But your function cannot be written to only work if my_list has 6 or 7 words, it has to work for any length my_list.