Automate the boring stuff with Python: Comma Code

前端 未结 29 976
深忆病人
深忆病人 2021-02-03 16:17

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:

29条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-03 16:56

    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)
    

提交回复
热议问题