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:
I used a different approach. I am a beginner, so I don't know if it's the cleanest way to do it. To me it seemed as the most simple way:
spam = ['apples', 'pizza', 'dogs', 'cats']
def comma(items):
for i in range(len(items) -2):
print(items[i], end=", ")# minor adjustment from one beginner to another: to make it cleaner, simply move the ', ' to equal 'end'. the print statement should finish like this --> end=', '
print(items[-2] + 'and ' + items[-1])
comma(spam)
Which will give the output:
apples, pizza, dogs and cats
This is what I came up with. There's probably a much cleaner way to write this, but this should work with any sized list as long as there's at least one element in the list.
spam = ['apples', 'oranges' 'tofu', 'cats']
def CommaCode(list):
if len(list) > 1 and len(list) != 0:
for item in range(len(list) - 1):
print(list[item], end=", ")
print('and ' + list[-1])
elif len(list) == 1:
for item in list:
print(item)
else:
print('List must contain more than one element')
CommaCode(spam)
I didn't dig through all the answers but I did see someone suggested using join. I agree but since this question didn't come in the book before learning joins my answer was this.
def To_String(my_list)
try:
for index, item in enumerate(my_list):
if index == 0: # at first index
myStr = str(item) + ', '
elif index < len(my_list) - 1: # after first index
myStr += str(item) + ', '
else:
myStr += 'and ' + str(item) # at last index
return myStr
except NameError:
return 'Your list has no data!'
spam = ['apples', 'bananas', 'tofu', 'cats']
my_string = To_String(spam)
print(my_string)
Result:
apples, bananas, tofu, and cats
Just a simple code. I think we don't need to use any fancy stuff here. :p
def getList(list):
value = ''
for i in range(len(list)):
if i == len(list) - 1:
value += 'and '+list[i]
else:
value += list[i] + ', '
return value
spam = ['apples', 'bananas', 'tofu', 'cats']
print('### TEST ###')
print(getList(spam))
Why is everyone putting so complex codes.
See my code below. Its the most simple and easiest to understand at one go even for a beginner.
import random
def comma_code(subject):
a = (len(list(subject)) - 1)
for i in range(0, len(list(subject))):
if i != a:
print(str(subject[i]) + ', ', end="")
else:
print('and '+ str(subject[i]))
spam = ['apples','banana','tofu','cats']
after coding the above, just type comma_code(spam) in the python shell and you are good to go. Enjoy