Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:
My interpretation of the question is such that a single list item would also be the last list item, and as such would need the 'and' inserted before it, as well as a two item list returning both with ', and' between them. Hence no need to deal with single or two item lists seperately, just the first n items, and the last item.
I'd also note that while great, a lot of the other items use modules and functions not taught in the Automate the Boring Stuff text by the time the student encounters this question (a student like me had seen join and .format elsewhere, but attempted to only use what had been taught in the text).
def commacode(passedlist):
stringy = ''
for i in range(len(passedlist)-1):
stringy += str(passedlist[i]) + ', '
# adds all except last item to str
stringy += 'and ' + str(passedlist[len(passedlist)-1])
# adds last item to string, after 'and'
return stringy
And you could handle the empty list case by:
def commacode(passedlist):
stringy = ''
try:
for i in range(len(passedlist)-1):
stringy += str(passedlist[i]) + ', '
# adds all except last item to str
stringy += 'and ' + str(passedlist[len(passedlist)-1])
# adds last item to string, after 'and'
return stringy
except IndexError:
return ''
#handles the list out of range error for an empty list by returning ''