Home > Net >  Why is the function inside the dictionary executing before they're called
Why is the function inside the dictionary executing before they're called

Time:04-30

I'm trying to make simple code that reads names and put it on a list, what i am intending to do is a series of functions to add names to the list, remove name, find name position etc. so it will have a lot of ifs, to avoid that i tried to use a dictionary to store the functions that will be called, but when i execute the program the functions inside the dictionary are running before i can input the number to execute it

def addName(nameListAux):
    """Returns a list of names

    Args:
        aux str: name that will add to the list list
    """

    name = str(input('Enter a new name: '))

    while name != 'quit':

        nameListAux.append(name)
        print(nameListAux)
        name = str(input('Enter a new name: '))

    print(nameListAux)
    return nameListAux


def searchName(searchedNameList):
    """Search a name on the list

    Args:
        searchedNameList list: list that will search the name

    Returns:
        int: position of the name in the list
    """
    name = str(input('Enter name to be searched: '))

    listLength = (int(len(searchedNameList)) // 2) - 1

    while listLength <= (int(len(searchedNameList) - 1)):
        if name == searchedNameList[listLength]:
            return print('the name is at position', listLength)
        listLength  = 1

    listLength = (int(len(searchedNameList)) // 2) - 1

    while listLength >= 0:
        if name == searchedNameList[listLength]:
            return print('the name is at position', listLength)
        listLength -= 1


if __name__ == '__main__':

    nameList = []

    selectionDict = {
        1: addName(nameList),
        2: searchName(nameList),
    }

    while True:
        switch = int(input('''Choose a option:
        1- Add name to list
        2- Search for name in list
        '''))

CodePudding user response:

To store a function inside dictionary , you need to store the function name without the bracelet.

So in your case it should be like this :

selection_dict = {1: addName, 2:searchName} 

You should have looked more information on google on how to store a function inside a dict. This link will be an useful example for you : Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

  • Related