I am learning Python through the book "Automate the Boring Stuff with Python" by Al Sweigart. I am finishing up a chapter on lists, and I have a program prompt called "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 insrted 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. "
Here is my code so far:
def commaCode(newList):
print(str(newList[:-1]) + 'and' + ' ' + str(newList[-1]))
return
nextlist = []
anotherlist = input('Enter a value')
while anotherlist != '':
nextlist = nextlist + list(anotherlist)
commaCode(nextlist)
I feel this should work, but whenever I type in an input of some sort, the program simply allows me to put in more input, and nothing happens. I then try to exit out of the program and it asks if it wants me to "kill the program". I am not sure what the problem with my code is... I assume it may be with the "while" statement, but I am not sure how to fix it.
Good effort. Your function is reasonably close, but your while will run infinitely because anotherList never changes inside the loop block. nextlist will keep expanding in this loop, though, with whatever string the user passed into input() broken into characters. Eventually, the program will run out of memory and crash.
Don't take my word for it: print the variable that is supposed to terminate the loop inside the loop block and see what it's doing on each pass (important debugging skill).
There's a few ways to fix this. The below approach allows the user to enter input on each loop pass, the result of which either breaks the loop if empty or is appended to the accumulating list of user input if not.
def comma_code(items):
if not items:
return ""
elif len(items) == 1:
return items[0]
return ", ".join(items[:-1]) + f" and {items[-1]}"
if __name__ == "__main__":
items = []
while True:
user_input = input("Enter a value: ")
if user_input == "":
break
items.append(user_input)
print(comma_code(items))
Sample run:
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 3
Enter a value: 4
Enter a value: 5
Enter a value:
1, 2, 3, 3, 4 and 5
Note that the variable names are snake_cased rather than camelCased per the Python coding standard.
I also removed the print that was in your commaCode function. This is a side effect and is generally undesirable because the function isn't multi-purpose: it only prints stuff to stdout and can't offer much else. If you return the result, the caller can choose what to do with it (print it, reverse it, put it in a database...).
Also note that if the user inputs nothing or one item, the original code would either crash or produce a poorly formatted output, respectively. I've handled these cases in the above code.
The second way was to actually use a function on pre-defined lists in the program.
spam = ['apples', 'bananas', 'tofu', 'cats']
otherlist = ['one', 'two', 'three', 'four', 'five']
def niceSentence(list):
for item in list[:-1]:
print(item + ", ", end='')
print("and " + list[-1])
niceSentence(spam)
niceSentence(otherlist)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With