I'm currently working through an exercise of Chapter 4 from Automate the Boring Stuff, which reads as follows:
"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."
Since I'm an absolute beginner to Python (and programming in general), I wanted to get some advice on how to make this code cleaner. It works with any size list, but I've reviewed some other solutions on SO and it seems like there are a million ways to build this out. How can I make this more straightforward?
spam = ['apples', 'bananas', 'tofu', 'cats']
def commaCode(listVar):
if len(listVar) == 0: # condition for an empty list
print('There are no items in this list.')
if len(listVar) == 1: # condition for a list with 1 item
return (str(listVar[0])+'.')
if len(listVar) == 2: # condition for a list with 2 items
return (str(listVar[0]) + ' and ' + str(listVar[1]) + '.')
if len(listVar) >=3: # conditions for lists with 3+ items
listDisp = ''
for i in range(len(listVar[:-1])):
listDisp = listDisp + str(listVar[i]) + ', '
listDisp = listDisp + 'and ' + str(listVar[-1])
return (listDisp)
commaCode(spam)
if len(listVar) == 2
branch; the lastif
seems able to hande the 2-items case. \$\endgroup\$