Automate the boring stuff with Python: Comma Code

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

    As the function must work for all list values passed to it, including integers, therefore it should be able to return/print all values i.e. as str(). My fully working code looks like this:

    spam = ['apples', 'bananas', 'tofu', 'cats', 2]
    
    def commacode(words):
    
        x = len(words)
    
        if x == 1:
            print(str(words[0]))
        else:
            for i in range(x - 1):
                print((str(words[i]) + ','), end=' ')
            print(('and ' + str(words[-1])))
    
    commacode(spam)
    

提交回复
热议问题