Automate the boring stuff with Python: Comma Code

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

    I am a fairly new pythonista. In the question it was asked that the function return the list contents as a string in the format that the other solutions in this forum have 'printed' it. Following is (in my opinion) a cleaner solution to this problem.

    This illustrates the comma code solution of chapter 4 [Lists] in Automate The Boring Stuff.

    def comma_code(argument):
    
        argument_in_string = ''
        argument_len = len(argument)
        for i in range(argument_len):
            if i == (argument_len - 1):
                argument_in_string = argument_in_string + 'and ' + argument[i]
                return argument_in_string
    
            argument_in_string = argument_in_string + argument[i] + ', '
    
    spam = ['apples', 'bananas', 'tofu', 'cats']
    return_value = comma_code(spam)
    print(return_value)"
    

提交回复
热议问题