Automate the boring stuff with Python: Comma Code

前端 未结 29 973
深忆病人
深忆病人 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 17:00

    Why is everyone putting so complex codes.

    See my code below. Its the most simple and easiest to understand at one go even for a beginner.

    import random
    
    def comma_code(subject):
    
         a = (len(list(subject)) - 1)
    
         for i in range(0, len(list(subject))):
    
              if i != a:
                   print(str(subject[i]) + ', ', end="")
    
              else:
                  print('and '+ str(subject[i]))            
    
    
    spam = ['apples','banana','tofu','cats']
    

    after coding the above, just type comma_code(spam) in the python shell and you are good to go. Enjoy

提交回复
热议问题