user82880 user82880 - 2 months ago 8
Python Question

How to keep track of numbered variables made from function call in while loop. How many are there?

So I'm writing a small project using python,
But now I'm in trouble.

I made some code like this:

START_BUTTONS = ("button1", "button2")
markup = types.ReplyKeyboardMarkup()
lengthof = len(START_BUTTONS)
countn = 0
while (countn < lengthof):
exec("itembtn" + str(countn) + " = types.KeyboardButton(START_BUTTONS[" + str(countn) + "])")
countn = countn + 1


So, this will parse something like this (unitl the tuple ends):

itembtn0 = types.KeyboardButton(START_BUTTONS[0])
itembtn1 = types.KeyboardButton(START_BUTTONS[1])


and...

So those variables are usable later.

But, my problem is here. I want to check how many of those variables are there (itembtn0 itembtn1 itembtn2 itembtn3...) and put them like this:

markup.row(itembtn0, itembtn1, itembtn2)


so , if there were 5 of those, it will return something like this:
markup.row(itembtn0, itembtn1, itembtn2, itembtn3, itembtn4)

Actually I have no idea for what I should write.

Thanks for help! & Sorry for my bad english.

Answer

You are trying to create numbered variables, which can in all cases be replaced by an array. Try something simple instead:

START_BUTTONS = ("button1", "button2")
markup = types.ReplyKeyboardMarkup()
itembtn = []
for btn in START_BUTTONS:
  itembtn.append(types.KeyboardButton(btn))

Access it with

itembtn[0]
itembtn[1]
etc.

And you can know how many there are:

len(itembtn)

I am not sure about your markup function, but you can pass the whole array as parameters like this:

markup.row(*itembtn)