Automate the boring stuff with Python: Comma Code

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

    This code works no matter what data types are in the lists, boolean, int, string, float, etc.

    def commaCode(spam):
        count = 0
        max_count = len(spam) - 1
    
        for x in range(len(spam)):
            if count < max_count:
                print(str(spam[count]) + ', ', end='')
                count += 1
            else:
                print('and ' + str(spam[max_count]))
    
    spam1 = ['cat', 'bananas', 'tofu', 'cats']
    spam2 = [23, '', True, 'cats']
    spam3 = []
    
    commaCode(spam1)
    commaCode(spam2)
    commaCode(spam3)
    

提交回复
热议问题