0

In an attempt to avoid using multiple elifs, I tried putting my functions inside a dictionary, so when I call it by it's key, it hopefully would be executed but it isn't working.

The idea was that the user would input a number/key and this would return the desired function.

I've been trying this.

It's in portuguese, but hopefully it's still readable. This is the func to pick the number of the function.

def escolhe_ex():
    while True:
        try:
            escolha = input("Exercício escolhido (1-9) => ")
            if 1 <= int(escolha) <= 9:
                break
        except: 
            if input('Escolha inválida, tente novamente ou digite SAIR para encerrar.').lower == 'sair':
                exit()
            continue

    return escolha

Works as intended, returns a number as string.

But no matter what I put in the following function parameter, it always starts from the first to the last. I wanted to pick only the specific function, but it returns all 9 functions consecutively.

def casos(escolha):
    cases = {
        '1' : ex1(),
        '2' : ex2(),
        '3' : ex3(),
        '4' : ex4(),
        '5' : ex5(),
        '6' : ex6(),
        '7' : ex7(),
        '8' : ex8(),
        '9' : ex9()
    }
    return cases[escolha]

Output I'm getting

I really have a hard time trying to be as clear as possible but if I haven't given enough info, apologies. I'm still learning on how to properly ask questions here.

But summarized, is it possible to store functions inside dics like that and access it by it's key?

  • 1
    Replace `exN()` with `exN` in the dictionary definition, and `cases[escolha]` with `cases[escolha]()` in the return statement. Only the function stored under `escolha` in the dictionary will be executed. – Brian61354270 Feb 11 '23 at 01:00
  • 1
    What about removing the brackets from the fuctions? that is instead of 'ex1()' put just ex1? – TiredButAwake Feb 11 '23 at 01:03
  • @Brian you're an angel, thank you so very much! now it's working! – Filipe Santos Feb 11 '23 at 01:03
  • Amin and TiredButAwake Thanks for the help, my problem is completely solved thanks you all. That's something I'll keep in mind forever, this way seems much cleaner than creating multiple elifs. Again, thanks to all and each of you for the assistance. – Filipe Santos Feb 11 '23 at 01:13

1 Answers1

1

I cannot fully undetstand your questions, though you can try this. I just changed function-call timing

{
    '1': ex1,
    '2': ex2,
    ...
}[escolha]()
Jaewoo Pyo
  • 156
  • 6