Bradley Irving
Bradley Irving

Reputation: 13

How do I make this menu selection more concise?

I'm writing a code for my school project and I feel there is a way to make it shorter, but I'm not sure how ?

menuchoice = input()
if menuchoice == 1:
    menuchoice1()
elif menuchoice == 2:
    menuchoice2()
elif menuchoice == 3:
    menuchoice3()
elif menuchoice == 4:
    menuchoice4()
elif menuchoice == 5:
    menuchoice5()
elif menuchoice == 6:
    menuchoice6()

Upvotes: 1

Views: 71

Answers (2)

Priyansh Agrawal
Priyansh Agrawal

Reputation: 344

You can create a map of the choice with the corresponding action.

choice_action_map = {
    1: menuchoice1,
    2: menuchoice2,
    3: menuchoice3,
    4: menuchoice4,
    5: menuchoice5,
    6: menuchoice6,
}

and then execute the corresponding action based on the input like this

choice_action_map[int(input())]()

Also, the action keys can be strings with the action names which will make your code more readable.

Upvotes: 1

Michael Bianconi
Michael Bianconi

Reputation: 5242

You can store those functions in an array:

choices = [
  menuchoice1,
  menuchoice2,
  ...
]

And then get them by index:

menuchoice = int(input())
choices[menuchoice - 1]()

Upvotes: 1

Related Questions