Automate the boring stuff with Python: Comma Code

前端 未结 29 975
深忆病人
深忆病人 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

    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
    

提交回复
热议问题