user82880 user82880 - 1 year ago 63
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])


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 Source

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:

Access it with


And you can know how many there are:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download