0

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()
  • 2
    A good answer depends on what all of those functions do. Why do you not simply pass in the value to a common function (eg: `menuchoice(input())`)? – Bryan Oakley Aug 13 '19 at 16:58
  • Also note that in the code you have, in Pyton 3 the `input()` function returns a **string**. not an integer, so **none** of your `if` and `elif` conditions will be true... – martineau Aug 13 '19 at 18:31

2 Answers2

1

You can store those functions in an array:

choices = [
  menuchoice1,
  menuchoice2,
  ...
]

And then get them by index:

menuchoice = int(input())
choices[menuchoice - 1]()
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
1

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.

Priyansh Agrawal
  • 330
  • 2
  • 19
  • @martineau I don't think that is the case. `In [141]: def foo(): ...: print("bar") ...: In [142]: c = {1: foo} In [143]: c[input()]() 1 bar` – Priyansh Agrawal Aug 13 '19 at 18:09