Skip to content Skip to sidebar Skip to footer

"comma Code" Program From Automate The Boring Stuff With Python

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':

Solution 1:

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.

defcomma_code(items):
   return', '.join(items[:-1]) + ' and ' + items[-1]

items = []

while1:
    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, you get either a crash or a poorly formatted output, respectively. Try to handle those edge cases as an exercise!

Solution 2:

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']

defniceSentence(list):

    for item inlist[:-1]:
        print(item + ", ", end='')

    print("and " + list[-1])

niceSentence(spam)

niceSentence(otherlist)

Solution 3:

I did mine in two ways, each of which incorporates steps that you used. Both work, but get their list input from different sources. One asks for user input, the same as you did. However, it does not actually define a function; rather, the program is the function. (I modeled this approach off the program "allMyCats2.py" in the middle of Chapter 4.)

anyList = []
while True:
    print('Enter an item for your list, or hit enter to stop.')
    item = input()
    if item == '':
          break
    anyList = anyList + [item]

for item in anyList[:-1]:
    print(item + ",", end='')

print("and " + anyList[-1])

Solution 4:

This combines the two approaches:

defniceSentence(list):
    for item inlist[:-1]:
        print(item + ", ", end='')
    print("and " + list[-1])        #this defines the function that makes the comma list


anyList = []

whileTrue:
    print('Enter an item for your list, or hit enter to stop.')
    item = input()
    if item == '':
          break
    anyList = anyList + [item]      #builds list from inputted strings

niceSentence(anyList)  #calls function on built list

Solution 5:

i did this short one

spam = ['apples', 'bananas', 'tofu', 'cats']

deflist_funk(theliste):
    for mot in theliste[:-1]: # first i work with index 0 to 3print(mot, end=', ')
    print('and ' + str(spam[-1])) # then adding what misses to complete exercise

list_funk(spam)

Post a Comment for ""comma Code" Program From Automate The Boring Stuff With Python"