0

I want create loop below.. (in python)

            content_cnt = len(content)
            if content_cnt == 0:
                self.bot.send("%s \n %s " % (title, content[0]))
            elif content_cnt == 1:
                self.bot.send("%s \n %s %s" % (title, content[0], content[1]))
            elif content_cnt == 2:
                self.bot.send("%s \n %s %s %s " % (title, content[0], content[1], content[2]))
                           ...
            elif content_cnt == 20:
                self.bot.send("%s \n %s %s %s ... %s " (title, content[0] .... contecnt[20]))

How can I keep my code simple?

Thank you for your help.

I tried to manually write lengthy code. That's very inefficient.

  • There's no loop here. Do you mean simply *conditional statements*? – deceze Apr 05 '22 at 09:38
  • `(title, *content)`…? `(title,) + content`? – deceze Apr 05 '22 at 09:39
  • 1
    first, if `len(content) == 0` , than is empty and that you can't even get `content[0]` solution: `self.bot.send(f"{title} \n {' '.join(content)}")` Here we use: 1) Formatted string literals (also called f-strings) allow to use variables directly in the string. I find it easier to read than using %. [documentation][1] 2) ' '.join to join elements of content in a string, and seperate them by an empty space. [documentation][2] [1]: https://docs.python.org/3/reference/lexical_analysis.html#f-strings [2]: https://docs.python.org/3/library/stdtypes.html#str.join – Seddik Mekki Apr 05 '22 at 09:51

0 Answers0