I’m reaching out to you all for help with this list project I’m working on. What I need to do is create a program that asks for the user to enter a word, and continue to ask until the user hits enter without typing anything. Once the user hits enter without typing anything, I need to create a list of all the words entered. The code I’ve pasted below does that currently, however, I need to figure out how to add “and” before the last option. I also need to figure out how to add “and” only if we already have more than one word entered.
Here is the code:
listToPrint = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == '':
break
else:
listToPrint.append(newWord)
print('Your items are:') #print items in list here
for newWord in listToPrint:
print(newWord, end=' ')
Ahh… Thank you @mtf. I was able to update the code but now it just looks like I need to figure out how to remove the last , after the and before the last element.
I think I just figured it out actually…
listToPrint = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == '':
break
else:
listToPrint.append(newWord)
print('Your items are:') #print items in list here
if len(listToPrint) > 1:
listToPrint[-1] = ('and ' + listToPrint[-1])
for i in range(len(listToPrint)-1):
print(listToPrint[i], end=', ')
print('' +str(listToPrint[-1]), end='.')