G
G
Grigory Shurygin2021-11-04 23:30:14
Python
Grigory Shurygin, 2021-11-04 23:30:14

Why does the function fire twice?

The question is not originally a question as such. I'm just not able to see the error in this block of code (the second day I'm trying to fix it). The essence of the problem is simple - there is a function that creates a kind of console using user input checks to configure the bot:

def admin_panel(user): #панель настройки бота

  if user == "change key":  #если пользователь решил сменить ключ в словаре

    with open("text.pickle", "rb") as file: #открываем файл для чтения
      bd = pickle.load(file) #записываем в новую переменную то, что было в файле

    print(bd) #выводим все что есть в БД
    hellp = input("enter the key you want to change: ") #ввод ключа который нужно заменить
    hellp_2 = input("enter the key you want to insert: ") #ввод ключа на который нужно заменить старый ключ
    firstKey = bd.pop(hellp) #удаление старого ключа и запись хранившихся данных в переменную
    bd[hellp_2] = firstKey #создание нового ключа с идентичными данными

    with open("text.pickle", "wb") as file: #открываем файл в конструкции with...as..: с авто закрытием файла
      pickle.dump(bd, file) #записываем содержимое объекта в файл

    return bd #возвращаем получившуюся БД

  elif user == "change value": #если пользователь хочет поменять значение

    with open("text.pickle", "rb") as file: #открываем файл для чтения
      bd = pickle.load(file) #записываем в новую переменную то, что было в файле

    print(bd) #выводим все ключи и значения в БД
    hellp = input("enter the key to which the value you want to change is assigned :\n") #ввод ключа под которым хранится изменяемое значение
    hellp_2 = input("enter a new value :\n") #запрашиваем новое значение
    bd[hellp] = hellp_2 #запись ответа и вопроса в словарь в виде ключ(вопрос) : значение(ответ)


    with open("text.pickle", "wb") as file: #открываем файл в конструкции with...as..: с авто закрытием файла
      pickle.dump(bd, file) #записываем содержимое объекта в файл

    return bd #возвращаем получившуюся БД

  elif user == "help": #сводка команд
    return "main command:\nchange key - изменение ключей к ответам\nchange value - изменение значений под ключами\nout1 - выход из админ_панели\nout - выход из программы"
  elif user == "out1": #если пользователь вводит "out1" то мы выходим из админ панели
    return 1

  elif user == "out": #если пользователь вводит "out" то мы выходим сразу из программы
    return 0

  #ЗДЕСЬ БУДЕТ ВЫПОЛНЯТЬСЯ ОСНОВНАЯ ФУНКЦИЯ С РАБОТОЙ БОТА
  else: #в случае некорректного ввода
    return "incorrect command 1" #сообщаем о ошибке пользователю

Naturally, I omitted such things as importing the "pickle" library of the function call and itself'
user = input()
I have a request rather than a question. Tell me why when you try to change the value, or the key. My function doesn't get to return and asks for key or value input twice? And exactly twice! There is no looped repetition, the function asks the same thing exactly twice and then return is triggered and everything starts working as it was supposed to from the beginning ... I
admit the possibility that there is no error in the function. But even if this is so, at least I will understand that the error is not in the function, but in the cycle of its call.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-11-05
@avrio

Check your code again. In the given piece, there is no indicated problem: for each option, everything will work only 1 time. You can check the above piece yourself in a separate script. If something is repeated, then either this piece is different from the real code, or the function is repeatedly called in the rest of the code.
And don't comment on every line. Comments should help to understand the logic of how a piece of code works, and not duplicate the code itself. There is no point in such comments:
return bd #возвращаем получившуюся БД

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question