I'm working on a project from Chapter 4 of Automate the Boring Stuff with Python. Here's the project's prompt:
"For practice, write programs to do the following tasks. Comma Code Say you have a list value like this: spam = [' apples', 'bananas', 'tofu', 'cats'] Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it."
I wrote a script that creates a list with commas and an 'and' before the last item: But I can't figure out how to make the script work with any list value passed to it. I've tried using the input function to call a list, but that doesn't work (or I can't get to work), since the input function only receives strings and not list names?
Here's the farthest I've gotten:
def listToString(list):
if list[-1]:
list.append('and '+str(list[-1]))
list.remove(list[-2])
for i in range(len(list)):
print(''+list[i]+', ')
spam = ['apples', 'bananas', 'tofu', 'cats']
listToString(spam)
As far as using the input() function, here's the code I've tried to no avail. I enter the spam list in the shell editor and run this:
def listToString(list):
if list[-1]:
list.append('and '+str(list[-1]))
list.remove(list[-2])
for i in range(len(list)):
print(''+list[i]+', ')
list = input("What list do you want to use?")
listToString(list)
['apples']probably shouldn't become'and apples', and['apples', 'bananas']probably shouldn't have a comma in the output.