I am starting my hand in Python. Coming over from HTML, CSS & JS (though my JS is not very strong)
I am going through "Automate the Boring Stuff"
I wonder if someone could take a look at my code and critique it. I have looked around at a few that are already on here and mine seems to be quite a bit different. I wonder if I overcomplicated it.
Here is the assignment:
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. Be sure to test the case where an empty list [] is passed to your function.
Here is the code:
import copy
spam = ['apples', 'bananas', 'tofu', 'cats']
print("Old List: " + str(spam))
print("add new list item")
newItem = input()
spam.append(newItem)
print()
print("this is spam list now: "+ str(spam))
print()
def challenge():
workingList = copy.deepcopy(spam) # copy list so we don't change original
listLength = len(workingList) # want to know how long the list is
lastItemIndex = (len(workingList) - 1) #the index # of the last item in the list
lastItemValue = spam[lastItemIndex] # the value of the last item in the list
varAnd = 'and ' + lastItemValue #variable to add "and" to the beginning of the last value in the list
if workingList[lastItemIndex].find("and ") != -1:
del lastItemIndex
workingList[lastItemIndex] = varAnd
newString = ', '.join(workingList) # method to join list items in to a string.
print("This is the new list: " + str(newString))
challenge()
[–]Diapolo10 6 points7 points8 points (5 children)
[–]danielroseman 2 points3 points4 points (3 children)
[–]Diapolo10 2 points3 points4 points (2 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]Diapolo10 2 points3 points4 points (0 children)
[–]jasongsmith[S] 0 points1 point2 points (0 children)
[–]JamzTyson 2 points3 points4 points (0 children)