This is an exercise in the Automate The Boring Stuff book. I am supposed to create 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. My code also includes a loop for the user to create their list.
def add_and(alist):
if ((alist != []) & (len(alist) > 2)):
for item in alist[:-1]:
print(item + ", ",end="")
print("and", alist[-1])
elif ((alist != []) & (len(alist) == 2)):
print(alist[0], "and", alist[1])
elif ((alist != []) & (len(alist) == 1)):
print(alist[0])
else:
print("")
your_list = []
while True:
print("Enter An Item or nothing")
item = input()
if ((item) == ""):
print("")
break
else:
your_list.append(item)
continue
add_and(your_list)
I know that the code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!
return
, the middle one would need modification, but could also be replaced. But the first two cannot be. You can only return from a function once, not multiple time in a loop; the firstreturn
executed terminates the function. \$\endgroup\$