Automate the boring stuff with Python: Comma Code

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

    I am working through the same book and came up with this solution: This allows the user to input some values and create a list from the input.

    userinput = input('Enter list items separated by a space.\n')
    userlist = userinput.split()
    
    def mylist(somelist):
        for i in range(len(somelist)-2): # Loop through the list up until the second from last element and add a comma
            print(somelist[i] + ', ', end='')
        print(somelist[-2] + ' and ' + somelist[-1]) # Add the last two elements of the list with 'and' in-between them
    
    mylist(userlist)
    

    Example:

    user input: one two three four five Output: one, two, three, four and five

提交回复
热议问题