Mistake:

elif message.text == '/page_{0}'.format (crow_0]):

UnboundLocalError: local variable 'row' referenced before assignment

Code:

... @bot.message_handler(content_types=['text']) def game(message): if message.text == 'Hello': db_worker = SQLighter(config.database_name) user_id = int(message.from_user.id) row = db_worker.select_single(l[db_worker.read_page(user_id)[2]]) bot.send_message(message.chat.id, row[0], row[1] + '/page' + str(row[0]) db_worker.close() elif message.text == '/page{0}'.format(row[0]): bot.send_message(message.chat.id, row[0]) ... 

    2 answers 2

    The error indicates that at the time of the test the row variable was not yet initialized. It is initialized in another if branch above. I assume that you need to move some of the code from the first if branch to the very if , there will be something like this:

     @bot.message_handler(content_types=['text']) def game(message): db_worker = SQLighter(config.database_name) user_id = int(message.from_user.id) row = db_worker.select_single(l[db_worker.read_page(user_id)[2]]) db_worker.close() if message.text == 'Hello': bot.send_message(message.chat.id, row[0], row[1] + '/page' + str(row[0]) elif message.text == '/page{0}'.format(row[0]): bot.send_message(message.chat.id, row[0]) 

    Although I can be wrong, because I do not know the logic of your program.

    • This option is not suitable, is it possible to somehow implement it differently? Connection to the base should be inside the first if - Kill Noise
    • @Surfer, you should know this better. row at you is filled on demand from base which is in the first if . If the first condition is not met, then the row not filled, and an error occurs on the second condition. From here the conclusion arises - the request needs to be carried out to if . There are no obvious reasons why the connection to the database and the request should be in the first ife, I do not see. If there are, write them down. - insolor

    You have written in the error message that the variable var has not yet been assigned, i.e. it needs to assign some value, for example row='spam' , before the conditional expression if